title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
Python | Copy and Paste Images onto other Image using Pillow
|
18 Jan, 2022
In this article, we will learn how to copy an image over another image using pillow library. We will use image module from pillow and copy() and paste() methods to achieve this task. We will need to create copies of both images so that it does not affect the original image with the help of copy() method and then paste the image on the other image with the help of paste() method.Input images – Image1:
Image2:
Example 1:
Python3
# import image module from pillowfrom PIL import Image # open the imageImage1 = Image.open('D:\cat.jpg') # make a copy the image so that the# original image does not get affectedImage1copy = Image1.copy()Image2 = Image.open('D:\core.jpg')Image2copy = Image2.copy() # paste image giving dimensionsImage1copy.paste(Image2copy, (0, 0)) # save the imageImage1copy.save('D:\pasted2.png')
Output:
Example 2: Changing parameters to place the Image2 on face of the cat in the Image1.
Python3
# import image module from pillowfrom PIL import Image # open the imageImage1 = Image.open('D:\cat.jpg') # make a copy the image so that# the original image does not get affectedImage1copy = Image1.copy()Image2 = Image.open('D:\core.jpg')Image2copy = Image2.copy() # paste image giving dimensionsImage1copy.paste(Image2copy, (70, 150)) # save the imageImage1copy.save('D:\pasted2.png')
Output:
Akanksha_Rai
sagar0719kumar
Python-pil
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n18 Jan, 2022"
},
{
"code": null,
"e": 433,
"s": 28,
"text": "In this article, we will learn how to copy an image over another image using pillow library. We will use image module from pillow and copy() and paste() methods to achieve this task. We will need to create copies of both images so that it does not affect the original image with the help of copy() method and then paste the image on the other image with the help of paste() method.Input images – Image1: "
},
{
"code": null,
"e": 444,
"s": 433,
"text": " Image2: "
},
{
"code": null,
"e": 457,
"s": 444,
"text": "Example 1: "
},
{
"code": null,
"e": 465,
"s": 457,
"text": "Python3"
},
{
"code": "# import image module from pillowfrom PIL import Image # open the imageImage1 = Image.open('D:\\cat.jpg') # make a copy the image so that the# original image does not get affectedImage1copy = Image1.copy()Image2 = Image.open('D:\\core.jpg')Image2copy = Image2.copy() # paste image giving dimensionsImage1copy.paste(Image2copy, (0, 0)) # save the imageImage1copy.save('D:\\pasted2.png')",
"e": 848,
"s": 465,
"text": null
},
{
"code": null,
"e": 858,
"s": 848,
"text": "Output: "
},
{
"code": null,
"e": 944,
"s": 858,
"text": "Example 2: Changing parameters to place the Image2 on face of the cat in the Image1. "
},
{
"code": null,
"e": 952,
"s": 944,
"text": "Python3"
},
{
"code": "# import image module from pillowfrom PIL import Image # open the imageImage1 = Image.open('D:\\cat.jpg') # make a copy the image so that# the original image does not get affectedImage1copy = Image1.copy()Image2 = Image.open('D:\\core.jpg')Image2copy = Image2.copy() # paste image giving dimensionsImage1copy.paste(Image2copy, (70, 150)) # save the imageImage1copy.save('D:\\pasted2.png')",
"e": 1338,
"s": 952,
"text": null
},
{
"code": null,
"e": 1348,
"s": 1338,
"text": "Output: "
},
{
"code": null,
"e": 1363,
"s": 1350,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 1378,
"s": 1363,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 1389,
"s": 1378,
"text": "Python-pil"
},
{
"code": null,
"e": 1396,
"s": 1389,
"text": "Python"
},
{
"code": null,
"e": 1412,
"s": 1396,
"text": "Python Programs"
}
] |
How to Find the Position of a Number in an Array in MATLAB?
|
04 Jul, 2021
Finding the position of a number in an array, which can be done using the find() function. The find() function is used to find the indices and values of the specified nonzero elements.
find(X)
Parameters: This function accepts a parameter.
X: This is the specified number whose position is going to be found in the array.
Return Value: It returns the position of the given number in a specified array.
Example 1
Matlab
% MATLAB code for getting the position % of element 4X = [2 4 4 5 6 4]; % Initializing an array % of some elements % Calling the find() function to find % the position of 4Position_of_4 = find(X==4)
Output:
Example 2
Matlab
% MATLAB code for getting the position % of element 4 in terms of rows and columns.X = [2 4 4 5 6 4]; % Calling the find() function to find % the position of 4 in terms of rows % and columns[Row, column] = find(X==4)
Output:
MATLAB
MATLAB-programs
Picked
MATLAB
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n04 Jul, 2021"
},
{
"code": null,
"e": 213,
"s": 28,
"text": "Finding the position of a number in an array, which can be done using the find() function. The find() function is used to find the indices and values of the specified nonzero elements."
},
{
"code": null,
"e": 221,
"s": 213,
"text": "find(X)"
},
{
"code": null,
"e": 268,
"s": 221,
"text": "Parameters: This function accepts a parameter."
},
{
"code": null,
"e": 350,
"s": 268,
"text": "X: This is the specified number whose position is going to be found in the array."
},
{
"code": null,
"e": 430,
"s": 350,
"text": "Return Value: It returns the position of the given number in a specified array."
},
{
"code": null,
"e": 442,
"s": 430,
"text": "Example 1 "
},
{
"code": null,
"e": 449,
"s": 442,
"text": "Matlab"
},
{
"code": "% MATLAB code for getting the position % of element 4X = [2 4 4 5 6 4]; % Initializing an array % of some elements % Calling the find() function to find % the position of 4Position_of_4 = find(X==4)",
"e": 649,
"s": 449,
"text": null
},
{
"code": null,
"e": 657,
"s": 649,
"text": "Output:"
},
{
"code": null,
"e": 668,
"s": 657,
"text": "Example 2 "
},
{
"code": null,
"e": 675,
"s": 668,
"text": "Matlab"
},
{
"code": "% MATLAB code for getting the position % of element 4 in terms of rows and columns.X = [2 4 4 5 6 4]; % Calling the find() function to find % the position of 4 in terms of rows % and columns[Row, column] = find(X==4)",
"e": 894,
"s": 675,
"text": null
},
{
"code": null,
"e": 902,
"s": 894,
"text": "Output:"
},
{
"code": null,
"e": 909,
"s": 902,
"text": "MATLAB"
},
{
"code": null,
"e": 925,
"s": 909,
"text": "MATLAB-programs"
},
{
"code": null,
"e": 932,
"s": 925,
"text": "Picked"
},
{
"code": null,
"e": 939,
"s": 932,
"text": "MATLAB"
}
] |
Python – Lemmatization Approaches with Examples
|
11 Apr, 2022
The following is a step by step guide to exploring various kinds of Lemmatization approaches in python along with a few examples and code implementation. It is highly recommended that you stick to the given flow unless you have an understanding of the topic, in which case you can look up any of the approaches given below.
What is Lemmatization? In contrast to stemming, lemmatization is a lot more powerful. It looks beyond word reduction and considers a language’s full vocabulary to apply a morphological analysis to words, aiming to remove inflectional endings only and to return the base or dictionary form of a word, which is known as the lemma.
For clarity, look at the following examples given below:
Original Word ---> Root Word (lemma) Feature
meeting ---> meet (core-word extraction)
was ---> be (tense conversion to present tense)
mice ---> mouse (plural to singular)
TIP: Always convert your text to lowercase before performing any NLP task including lemmatizing.
Various Approaches to Lemmatization: We will be going over 9 different approaches to perform Lemmatization along with multiple examples and code implementations.
WordNetWordNet (with POS tag)TextBlobTextBlob (with POS tag)spaCyTreeTaggerPatternGensimStanford CoreNLP
WordNet
WordNet (with POS tag)
TextBlob
TextBlob (with POS tag)
spaCy
TreeTagger
Pattern
Gensim
Stanford CoreNLP
1. Wordnet Lemmatizer Wordnet is a publicly available lexical database of over 200 languages that provides semantic relationships between its words. It is one of the earliest and most commonly used lemmatizer technique.
It is present in the nltk library in python.
Wordnet links words into semantic relations. ( eg. synonyms )
It groups synonyms in the form of synsets.synsets : a group of data elements that are semantically equivalent.
synsets : a group of data elements that are semantically equivalent.
How to use:
Download nltk package : In your anaconda prompt or terminal, type: pip install nltkDownload Wordnet from nltk : In your python console, do the following : import nltk nltk.download(‘wordnet’) nltk.download(‘averaged_perceptron_tagger’)
Download nltk package : In your anaconda prompt or terminal, type: pip install nltk
Download Wordnet from nltk : In your python console, do the following : import nltk nltk.download(‘wordnet’) nltk.download(‘averaged_perceptron_tagger’)
Code:
Python3
import nltknltk.download('wordnet')from nltk.stem import WordNetLemmatizer # Create WordNetLemmatizer objectwnl = WordNetLemmatizer() # single word lemmatization exampleslist1 = ['kites', 'babies', 'dogs', 'flying', 'smiling', 'driving', 'died', 'tried', 'feet']for words in list1: print(words + " ---> " + wnl.lemmatize(words)) #> kites ---> kite#> babies ---> baby#> dogs ---> dog#> flying ---> flying#> smiling ---> smiling#> driving ---> driving#> died ---> died#> tried ---> tried#> feet ---> foot
Code:
Python3
# sentence lemmatization examplesstring = 'the cat is sitting with the bats on the striped mat under many flying geese' # Converting String into tokenslist2 = nltk.word_tokenize(string)print(list2)#> ['the', 'cat', 'is', 'sitting', 'with', 'the', 'bats', 'on',# 'the', 'striped', 'mat', 'under', 'many', 'flying', 'geese'] lemmatized_string = ' '.join([wnl.lemmatize(words) for words in list2]) print(lemmatized_string) #> the cat is sitting with the bat on the striped mat under many flying goose
2. Wordnet Lemmatizer (with POS tag) In the above approach, we observed that Wordnet results were not up to the mark. Words like ‘sitting’, ‘flying’ etc remained the same after lemmatization. This is because these words are treated as a noun in the given sentence rather than a verb. To overcome come this, we use POS (Part of Speech) tags. We add a tag with a particular word defining its type (verb, noun, adjective etc). For Example, Word + Type (POS tag) —> Lemmatized Worddriving + verb ‘v’ —> drivedogs + noun ‘n’ —> dog
Code:
Python3
# WORDNET LEMMATIZER (with appropriate pos tags) import nltkfrom nltk.stem import WordNetLemmatizernltk.download('averaged_perceptron_tagger')from nltk.corpus import wordnet lemmatizer = WordNetLemmatizer() # Define function to lemmatize each word with its POS tag # POS_TAGGER_FUNCTION : TYPE 1def pos_tagger(nltk_tag): if nltk_tag.startswith('J'): return wordnet.ADJ elif nltk_tag.startswith('V'): return wordnet.VERB elif nltk_tag.startswith('N'): return wordnet.NOUN elif nltk_tag.startswith('R'): return wordnet.ADV else: return None sentence = 'the cat is sitting with the bats on the striped mat under many badly flying geese' # tokenize the sentence and find the POS tag for each tokenpos_tagged = nltk.pos_tag(nltk.word_tokenize(sentence)) print(pos_tagged)#>[('the', 'DT'), ('cat', 'NN'), ('is', 'VBZ'), ('sitting', 'VBG'), ('with', 'IN'),# ('the', 'DT'), ('bats', 'NNS'), ('on', 'IN'), ('the', 'DT'), ('striped', 'JJ'),# ('mat', 'NN'), ('under', 'IN'), ('many', 'JJ'), ('flying', 'VBG'), ('geese', 'JJ')] # As you may have noticed, the above pos tags are a little confusing. # we use our own pos_tagger function to make things simpler to understand.wordnet_tagged = list(map(lambda x: (x[0], pos_tagger(x[1])), pos_tagged))print(wordnet_tagged)#>[('the', None), ('cat', 'n'), ('is', 'v'), ('sitting', 'v'), ('with', None),# ('the', None), ('bats', 'n'), ('on', None), ('the', None), ('striped', 'a'),# ('mat', 'n'), ('under', None), ('many', 'a'), ('flying', 'v'), ('geese', 'a')] lemmatized_sentence = []for word, tag in wordnet_tagged: if tag is None: # if there is no available tag, append the token as is lemmatized_sentence.append(word) else: # else use the tag to lemmatize the token lemmatized_sentence.append(lemmatizer.lemmatize(word, tag))lemmatized_sentence = " ".join(lemmatized_sentence) print(lemmatized_sentence)#> the cat can be sit with the bat on the striped mat under many fly geese
3. TextBlob TextBlob is a python library used for processing textual data. It provides a simple API to access its methods and perform basic NLP tasks.
Download TextBlob package : In your anaconda prompt or terminal, type: pip install textblob
Code:
Python3
from textblob import TextBlob, Word my_word = 'cats' # create a Word objectw = Word(my_word) print(w.lemmatize())#> cat sentence = 'the bats saw the cats with stripes hanging upside down by their feet.' s = TextBlob(sentence)lemmatized_sentence = " ".join([w.lemmatize() for w in s.words]) print(lemmatized_sentence)#> the bat saw the cat with stripe hanging upside down by their foot
4. TextBlob (with POS tag) Same as in Wordnet approach without using appropriate POS tags, we observe the same limitations in this approach as well. So, we use one of the more powerful aspects of the TextBlob module the ‘Part of Speech’ tagging to overcome this problem.
Code:
Python3
from textblob import TextBlob # Define function to lemmatize each word with its POS tag # POS_TAGGER_FUNCTION : TYPE 2def pos_tagger(sentence): sent = TextBlob(sentence) tag_dict = {"J": 'a', "N": 'n', "V": 'v', "R": 'r'} words_tags = [(w, tag_dict.get(pos[0], 'n')) for w, pos in sent.tags] lemma_list = [wd.lemmatize(tag) for wd, tag in words_tags] return lemma_list # Lemmatizesentence = "the bats saw the cats with stripes hanging upside down by their feet"lemma_list = pos_tagger(sentence)lemmatized_sentence = " ".join(lemma_list)print(lemmatized_sentence)#> the bat saw the cat with stripe hang upside down by their foot lemmatized_sentence = " ".join([w.lemmatize() for w in t_blob.words])print(lemmatized_sentence)#> the bat saw the cat with stripe hanging upside down by their foot
Here is a link for all the types of tag abbreviations with their meanings. (scroll down for the tags table)
5. spaCy spaCy is an open-source python library that parses and “understands” large volumes of text. Separate models are available that cater to specific languages (English, French, German, etc.).
Download spaCy package :(a) Open anaconda prompt or terminal as administrator and run the command:
(b) Now, open anaconda prompt or terminal normally and run the command:
If successful, you should see a message like:
Linking successful
C:\Anaconda3\envs\spacyenv\lib\site-packages\en_core_web_sm -->
C:\Anaconda3\envs\spacyenv\lib\site-packages\spacy\data\en
You can now load the model via
Code:
Python3
import spacynlp = spacy.load('en_core_web_sm') # Create a Doc objectdoc = nlp(u'the bats saw the cats with best stripes hanging upside down by their feet') # Create list of tokens from given stringtokens = []for token in doc: tokens.append(token) print(tokens)#> [the, bats, saw, the, cats, with, best, stripes, hanging, upside, down, by, their, feet] lemmatized_sentence = " ".join([token.lemma_ for token in doc]) print(lemmatized_sentence)#> the bat see the cat with good stripe hang upside down by -PRON- foot
In the above code, we observed that this approach was more powerful than our previous approaches as :
Even Pro-nouns were detected. ( identified by -PRON-)
Even best was changed to good.
6. TreeTagger The TreeTagger is a tool for annotating text with part-of-speech and lemma information. The TreeTagger has been successfully used to tag over 25 languages and is adaptable to other languages if a manually tagged training corpus is available.
How to use:
1. Download TreeTagger package : In your anaconda prompt or terminal, type:
2. Download TreeTagger Software: Click on TreeTagger and download the software as per your OS.
(Steps of installation given on website)
Code:
Python3
# 6. TREETAGGER LEMMATIZERimport pandas as pdimport treetaggerwrapper as tt t_tagger = tt.TreeTagger(TAGLANG ='en', TAGDIR ='C:\Windows\TreeTagger') pos_tags = t_tagger.tag_text("the bats saw the cats with best stripes hanging upside down by their feet") original = []lemmas = []tags = []for t in pos_tags: original.append(t.split('\t')[0]) tags.append(t.split('\t')[1]) lemmas.append(t.split('\t')[-1]) Results = pd.DataFrame({'Original': original, 'Lemma': lemmas, 'Tags': tags})print(Results) #> Original Lemma Tags# 0 the the DT# 1 bats bat NNS# 2 saw see VVD# 3 the the DT# 4 cats cat NNS# 5 with with IN# 6 best good JJS# 7 stripes stripe NNS# 8 hanging hang VVG# 9 upside upside RB# 10 down down RB# 11 by by IN# 12 their their PP$# 13 feet foot NNS
7. Pattern Pattern is a Python package commonly used for web mining, natural language processing, machine learning, and network analysis. It has many useful NLP capabilities. It also contains a special feature which we will be discussing below.
How to use:
Download Pattern package: In your anaconda prompt or terminal, type:
Code:
Python3
# PATTERN LEMMATIZERimport patternfrom pattern.en import lemma, lexemefrom pattern.en import parse sentence = "the bats saw the cats with best stripes hanging upside down by their feet" lemmatized_sentence = " ".join([lemma(word) for word in sentence.split()]) print(lemmatized_sentence)#> the bat see the cat with best stripe hang upside down by their feet # Special Feature : to get all possible lemmas for each word in the sentenceall_lemmas_for_each_word = [lexeme(wd) for wd in sentence.split()]print(all_lemmas_for_each_word) #> [['the', 'thes', 'thing', 'thed'],# ['bat', 'bats', 'batting', 'batted'],# ['see', 'sees', 'seeing', 'saw', 'seen'],# ['the', 'thes', 'thing', 'thed'],# ['cat', 'cats', 'catting', 'catted'],# ['with', 'withs', 'withing', 'withed'],# ['best', 'bests', 'besting', 'bested'],# ['stripe', 'stripes', 'striping', 'striped'],# ['hang', 'hangs', 'hanging', 'hung'],# ['upside', 'upsides', 'upsiding', 'upsided'],# ['down', 'downs', 'downing', 'downed'],# ['by', 'bies', 'bying', 'bied'],# ['their', 'theirs', 'theiring', 'theired'],# ['feet', 'feets', 'feeting', 'feeted']]
NOTE : if the above code raises an error saying ‘generator raised StopIteration’. Just run it again. It will work after 3-4 tries.
8. Gensim Gensim is designed to handle large text collections using data streaming. Its lemmatization facilities are based on the pattern package we installed above.
gensim.utils.lemmatize() function can be used for performing Lemmatization. This method comes under the utils module in python.
We can use this lemmatizer from pattern to extract UTF8-encoded tokens in their base form=lemma.
Only considers nouns, verbs, adjectives, and adverbs by default (all other lemmas are discarded).
For example
Word ---> Lemmatized Word
are/is/being ---> be
saw ---> see
How to use:
1. Download Pattern package: In your anaconda prompt or terminal, type:
2. Download Gensim package: Open your anaconda prompt or terminal as administrator and type:
OR
Code:
Python3
from gensim.utils import lemmatize sentence = "the bats saw the cats with best stripes hanging upside down by their feet" lemmatized_sentence = [word.decode('utf-8').split('.')[0] for word in lemmatize(sentence)] print(lemmatized_sentence)#> ['bat / NN', 'see / VB', 'cat / NN', 'best / JJ',# 'stripe / NN', 'hang / VB', 'upside / RB', 'foot / NN']
NOTE : if the above code raises an error saying ‘generator raised StopIteration‘. Just run it again. It will work after 3-4 tries.
In the above code as you may have already noticed, the gensim lemmatizer ignore the words like ‘the’, ‘with’, ‘by’ as they did not fall into the 4 lemma categories mentioned above. (noun/verb/adjective/adverb)
9. Stanford CoreNLP CoreNLP enables users to derive linguistic annotations for text, including token and sentence boundaries, parts of speech, named entities, numeric and time values, dependency and constituency parses, sentiment, quote attributions, and relations.
CoreNLP is your one stop shop for natural language processing in Java!
CoreNLP currently supports 6 languages, including Arabic, Chinese, English, French, German, and Spanish.
How to use:
1. Get JAVA 8 : Download Java 8 (as per your OS) and install it.
2. Get Stanford_coreNLP package :
2.1) Download Stanford_CoreNLP and unzip it.
2.2) Open terminal
(a) go to the directory where you extracted the above file by doing
cd C:\Users\...\stanford-corenlp-4.1.0 on terminal
(b) then, start your Stanford CoreNLP server by executing the following command on terminal:
java -mx4g -cp "*" edu.stanford.nlp.pipeline.StanfordCoreNLPServer -annotators "tokenize, ssplit, pos, lemma, parse, sentiment" -port 9000 -timeout 30000
**(leave your terminal open as long as you use this lemmatizer)**
3. Download Standford CoreNLP package: Open your anaconda prompt or terminal, type:
Code:
Python3
from stanfordcorenlp import StanfordCoreNLPimport json # Connect to the CoreNLP server we just startednlp = StanfordCoreNLP('http://localhost', port = 9000, timeout = 30000) # Define properties needed to get lemmaprops = {'annotators': 'pos, lemma', 'pipelineLanguage': 'en', 'outputFormat': 'json'} sentence = "the bats saw the cats with best stripes hanging upside down by their feet"parsed_str = nlp.annotate(sentence, properties = props)print(parsed_str) #> "sentences": [{"index": 0,# "tokens": [# {# "index": 1,# "word": "the",# "originalText": "the",# "lemma": "the", <--------------- LEMMA# "characterOffsetBegin": 0,# "characterOffsetEnd": 3,# "pos": "DT",# "before": "",# "after": " "# },# {# "index": 2,# "word": "bats",# "originalText": "bats",# "lemma": "bat", <--------------- LEMMA# "characterOffsetBegin": 4,# "characterOffsetEnd": 8,# "pos": "NNS",# "before": " ",# "after": " "# },# {# "index": 3,# "word": "saw",# "originalText": "saw",# "lemma": "see", <--------------- LEMMA# "characterOffsetBegin": 9,# "characterOffsetEnd": 12,# "pos": "VBD",# "before": " ",# "after": " "# },# {# "index": 4,# "word": "the",# "originalText": "the",# "lemma": "the", <--------------- LEMMA# "characterOffsetBegin": 13,# "characterOffsetEnd": 16,# "pos": "DT",# "before": " ",# "after": " "# },# {# "index": 5,# "word": "cats",# "originalText": "cats",# "lemma": "cat", <--------------- LEMMA# "characterOffsetBegin": 17,# "characterOffsetEnd": 21,# "pos": "NNS",# "before": " ",# "after": " "# },# {# "index": 6,# "word": "with",# "originalText": "with",# "lemma": "with", <--------------- LEMMA# "characterOffsetBegin": 22,# "characterOffsetEnd": 26,# "pos": "IN",# "before": " ",# "after": " "# },# {# "index": 7,# "word": "best",# "originalText": "best",# "lemma": "best", <--------------- LEMMA# "characterOffsetBegin": 27,# "characterOffsetEnd": 31,# "pos": "JJS",# "before": " ",# "after": " "# },# {# "index": 8,# "word": "stripes",# "originalText": "stripes",# "lemma": "stripe", <--------------- LEMMA# "characterOffsetBegin": 32,# "characterOffsetEnd": 39,# "pos": "NNS",# "before": " ",# "after": " "# },# {# "index": 9,# "word": "hanging",# "originalText": "hanging",# "lemma": "hang", <--------------- LEMMA# "characterOffsetBegin": 40,# "characterOffsetEnd": 47,# "pos": "VBG",# "before": " ",# "after": " "# },# {# "index": 10,# "word": "upside",# "originalText": "upside",# "lemma": "upside", <--------------- LEMMA# "characterOffsetBegin": 48,# "characterOffsetEnd": 54,# "pos": "RB",# "before": " ",# "after": " "# },# {# "index": 11,# "word": "down",# "originalText": "down",# "lemma": "down", <--------------- LEMMA# "characterOffsetBegin": 55,# "characterOffsetEnd": 59,# "pos": "RB",# "before": " ",# "after": " "# },# {# "index": 12,# "word": "by",# "originalText": "by",# "lemma": "by", <--------------- LEMMA# "characterOffsetBegin": 60,# "characterOffsetEnd": 62,# "pos": "IN",# "before": " ",# "after": " "# },# {# "index": 13,# "word": "their",# "originalText": "their",# "lemma": "they"#, <--------------- LEMMA# "characterOffsetBegin": 63,# "characterOffsetEnd": 68,# "pos": "PRP$",# "before": " ",# "after": " "# },# {# "index": 14,# "word": "feet",# "originalText": "feet",# "lemma": "foot", <--------------- LEMMA# "characterOffsetBegin": 69,# "characterOffsetEnd": 73,# "pos": "NNS",# "before": " ",# "after": ""# }# ]# }# ]
Code:
Python3
# To get the lemmatized sentence as output # ** RUN THE ABOVE SCRIPT FIRST ** lemma_list = []for item in parsed_dict['sentences'][0]['tokens']: for key, value in item.items(): if key == 'lemma': lemma_list.append(value) print(lemma_list)#> ['the', 'bat', 'see', 'the', 'cat', 'with', 'best', 'stripe', 'hang', 'upside', 'down', 'by', 'they', 'foot'] lemmatized_sentence = " ".join(lemma_list)print(lemmatized_sentence)#>the bat see the cat with best stripe hang upside down by the foot
Conclusion: So these are the various Lemmatization approaches that you can refer while working on an NLP project. The selection of the Lemmatization approach is solely dependent upon project requirements. Each approach has its set of pros and cons. Lemmatization is mandatory for critical projects where sentence structure matter like language applications etc.
abhishek0719kadiyan
anikakapoor
simmytarika5
rkbhola5
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 Apr, 2022"
},
{
"code": null,
"e": 353,
"s": 28,
"text": "The following is a step by step guide to exploring various kinds of Lemmatization approaches in python along with a few examples and code implementation. It is highly recommended that you stick to the given flow unless you have an understanding of the topic, in which case you can look up any of the approaches given below. "
},
{
"code": null,
"e": 682,
"s": 353,
"text": "What is Lemmatization? In contrast to stemming, lemmatization is a lot more powerful. It looks beyond word reduction and considers a language’s full vocabulary to apply a morphological analysis to words, aiming to remove inflectional endings only and to return the base or dictionary form of a word, which is known as the lemma."
},
{
"code": null,
"e": 740,
"s": 682,
"text": "For clarity, look at the following examples given below: "
},
{
"code": null,
"e": 994,
"s": 740,
"text": "Original Word ---> Root Word (lemma) Feature\n\n meeting ---> meet (core-word extraction)\n was ---> be (tense conversion to present tense)\n mice ---> mouse (plural to singular)"
},
{
"code": null,
"e": 1091,
"s": 994,
"text": "TIP: Always convert your text to lowercase before performing any NLP task including lemmatizing."
},
{
"code": null,
"e": 1255,
"s": 1091,
"text": "Various Approaches to Lemmatization: We will be going over 9 different approaches to perform Lemmatization along with multiple examples and code implementations. "
},
{
"code": null,
"e": 1360,
"s": 1255,
"text": "WordNetWordNet (with POS tag)TextBlobTextBlob (with POS tag)spaCyTreeTaggerPatternGensimStanford CoreNLP"
},
{
"code": null,
"e": 1368,
"s": 1360,
"text": "WordNet"
},
{
"code": null,
"e": 1391,
"s": 1368,
"text": "WordNet (with POS tag)"
},
{
"code": null,
"e": 1400,
"s": 1391,
"text": "TextBlob"
},
{
"code": null,
"e": 1424,
"s": 1400,
"text": "TextBlob (with POS tag)"
},
{
"code": null,
"e": 1430,
"s": 1424,
"text": "spaCy"
},
{
"code": null,
"e": 1441,
"s": 1430,
"text": "TreeTagger"
},
{
"code": null,
"e": 1449,
"s": 1441,
"text": "Pattern"
},
{
"code": null,
"e": 1456,
"s": 1449,
"text": "Gensim"
},
{
"code": null,
"e": 1473,
"s": 1456,
"text": "Stanford CoreNLP"
},
{
"code": null,
"e": 1696,
"s": 1473,
"text": "1. Wordnet Lemmatizer Wordnet is a publicly available lexical database of over 200 languages that provides semantic relationships between its words. It is one of the earliest and most commonly used lemmatizer technique. "
},
{
"code": null,
"e": 1741,
"s": 1696,
"text": "It is present in the nltk library in python."
},
{
"code": null,
"e": 1803,
"s": 1741,
"text": "Wordnet links words into semantic relations. ( eg. synonyms )"
},
{
"code": null,
"e": 1915,
"s": 1803,
"text": "It groups synonyms in the form of synsets.synsets : a group of data elements that are semantically equivalent. "
},
{
"code": null,
"e": 1985,
"s": 1915,
"text": "synsets : a group of data elements that are semantically equivalent. "
},
{
"code": null,
"e": 1999,
"s": 1985,
"text": "How to use: "
},
{
"code": null,
"e": 2235,
"s": 1999,
"text": "Download nltk package : In your anaconda prompt or terminal, type: pip install nltkDownload Wordnet from nltk : In your python console, do the following : import nltk nltk.download(‘wordnet’) nltk.download(‘averaged_perceptron_tagger’)"
},
{
"code": null,
"e": 2319,
"s": 2235,
"text": "Download nltk package : In your anaconda prompt or terminal, type: pip install nltk"
},
{
"code": null,
"e": 2472,
"s": 2319,
"text": "Download Wordnet from nltk : In your python console, do the following : import nltk nltk.download(‘wordnet’) nltk.download(‘averaged_perceptron_tagger’)"
},
{
"code": null,
"e": 2479,
"s": 2472,
"text": "Code: "
},
{
"code": null,
"e": 2487,
"s": 2479,
"text": "Python3"
},
{
"code": "import nltknltk.download('wordnet')from nltk.stem import WordNetLemmatizer # Create WordNetLemmatizer objectwnl = WordNetLemmatizer() # single word lemmatization exampleslist1 = ['kites', 'babies', 'dogs', 'flying', 'smiling', 'driving', 'died', 'tried', 'feet']for words in list1: print(words + \" ---> \" + wnl.lemmatize(words)) #> kites ---> kite#> babies ---> baby#> dogs ---> dog#> flying ---> flying#> smiling ---> smiling#> driving ---> driving#> died ---> died#> tried ---> tried#> feet ---> foot",
"e": 3005,
"s": 2487,
"text": null
},
{
"code": null,
"e": 3012,
"s": 3005,
"text": "Code: "
},
{
"code": null,
"e": 3020,
"s": 3012,
"text": "Python3"
},
{
"code": "# sentence lemmatization examplesstring = 'the cat is sitting with the bats on the striped mat under many flying geese' # Converting String into tokenslist2 = nltk.word_tokenize(string)print(list2)#> ['the', 'cat', 'is', 'sitting', 'with', 'the', 'bats', 'on',# 'the', 'striped', 'mat', 'under', 'many', 'flying', 'geese'] lemmatized_string = ' '.join([wnl.lemmatize(words) for words in list2]) print(lemmatized_string) #> the cat is sitting with the bat on the striped mat under many flying goose",
"e": 3521,
"s": 3020,
"text": null
},
{
"code": null,
"e": 4118,
"s": 3521,
"text": "2. Wordnet Lemmatizer (with POS tag) In the above approach, we observed that Wordnet results were not up to the mark. Words like ‘sitting’, ‘flying’ etc remained the same after lemmatization. This is because these words are treated as a noun in the given sentence rather than a verb. To overcome come this, we use POS (Part of Speech) tags. We add a tag with a particular word defining its type (verb, noun, adjective etc). For Example, Word + Type (POS tag) —> Lemmatized Worddriving + verb ‘v’ —> drivedogs + noun ‘n’ —> dog"
},
{
"code": null,
"e": 4125,
"s": 4118,
"text": "Code: "
},
{
"code": null,
"e": 4133,
"s": 4125,
"text": "Python3"
},
{
"code": "# WORDNET LEMMATIZER (with appropriate pos tags) import nltkfrom nltk.stem import WordNetLemmatizernltk.download('averaged_perceptron_tagger')from nltk.corpus import wordnet lemmatizer = WordNetLemmatizer() # Define function to lemmatize each word with its POS tag # POS_TAGGER_FUNCTION : TYPE 1def pos_tagger(nltk_tag): if nltk_tag.startswith('J'): return wordnet.ADJ elif nltk_tag.startswith('V'): return wordnet.VERB elif nltk_tag.startswith('N'): return wordnet.NOUN elif nltk_tag.startswith('R'): return wordnet.ADV else: return None sentence = 'the cat is sitting with the bats on the striped mat under many badly flying geese' # tokenize the sentence and find the POS tag for each tokenpos_tagged = nltk.pos_tag(nltk.word_tokenize(sentence)) print(pos_tagged)#>[('the', 'DT'), ('cat', 'NN'), ('is', 'VBZ'), ('sitting', 'VBG'), ('with', 'IN'),# ('the', 'DT'), ('bats', 'NNS'), ('on', 'IN'), ('the', 'DT'), ('striped', 'JJ'),# ('mat', 'NN'), ('under', 'IN'), ('many', 'JJ'), ('flying', 'VBG'), ('geese', 'JJ')] # As you may have noticed, the above pos tags are a little confusing. # we use our own pos_tagger function to make things simpler to understand.wordnet_tagged = list(map(lambda x: (x[0], pos_tagger(x[1])), pos_tagged))print(wordnet_tagged)#>[('the', None), ('cat', 'n'), ('is', 'v'), ('sitting', 'v'), ('with', None),# ('the', None), ('bats', 'n'), ('on', None), ('the', None), ('striped', 'a'),# ('mat', 'n'), ('under', None), ('many', 'a'), ('flying', 'v'), ('geese', 'a')] lemmatized_sentence = []for word, tag in wordnet_tagged: if tag is None: # if there is no available tag, append the token as is lemmatized_sentence.append(word) else: # else use the tag to lemmatize the token lemmatized_sentence.append(lemmatizer.lemmatize(word, tag))lemmatized_sentence = \" \".join(lemmatized_sentence) print(lemmatized_sentence)#> the cat can be sit with the bat on the striped mat under many fly geese",
"e": 6147,
"s": 4133,
"text": null
},
{
"code": null,
"e": 6298,
"s": 6147,
"text": "3. TextBlob TextBlob is a python library used for processing textual data. It provides a simple API to access its methods and perform basic NLP tasks."
},
{
"code": null,
"e": 6391,
"s": 6298,
"text": " Download TextBlob package : In your anaconda prompt or terminal, type: pip install textblob"
},
{
"code": null,
"e": 6398,
"s": 6391,
"text": "Code: "
},
{
"code": null,
"e": 6406,
"s": 6398,
"text": "Python3"
},
{
"code": "from textblob import TextBlob, Word my_word = 'cats' # create a Word objectw = Word(my_word) print(w.lemmatize())#> cat sentence = 'the bats saw the cats with stripes hanging upside down by their feet.' s = TextBlob(sentence)lemmatized_sentence = \" \".join([w.lemmatize() for w in s.words]) print(lemmatized_sentence)#> the bat saw the cat with stripe hanging upside down by their foot",
"e": 6791,
"s": 6406,
"text": null
},
{
"code": null,
"e": 7062,
"s": 6791,
"text": "4. TextBlob (with POS tag) Same as in Wordnet approach without using appropriate POS tags, we observe the same limitations in this approach as well. So, we use one of the more powerful aspects of the TextBlob module the ‘Part of Speech’ tagging to overcome this problem."
},
{
"code": null,
"e": 7069,
"s": 7062,
"text": "Code: "
},
{
"code": null,
"e": 7077,
"s": 7069,
"text": "Python3"
},
{
"code": "from textblob import TextBlob # Define function to lemmatize each word with its POS tag # POS_TAGGER_FUNCTION : TYPE 2def pos_tagger(sentence): sent = TextBlob(sentence) tag_dict = {\"J\": 'a', \"N\": 'n', \"V\": 'v', \"R\": 'r'} words_tags = [(w, tag_dict.get(pos[0], 'n')) for w, pos in sent.tags] lemma_list = [wd.lemmatize(tag) for wd, tag in words_tags] return lemma_list # Lemmatizesentence = \"the bats saw the cats with stripes hanging upside down by their feet\"lemma_list = pos_tagger(sentence)lemmatized_sentence = \" \".join(lemma_list)print(lemmatized_sentence)#> the bat saw the cat with stripe hang upside down by their foot lemmatized_sentence = \" \".join([w.lemmatize() for w in t_blob.words])print(lemmatized_sentence)#> the bat saw the cat with stripe hanging upside down by their foot",
"e": 7887,
"s": 7077,
"text": null
},
{
"code": null,
"e": 7996,
"s": 7887,
"text": "Here is a link for all the types of tag abbreviations with their meanings. (scroll down for the tags table) "
},
{
"code": null,
"e": 8194,
"s": 7996,
"text": "5. spaCy spaCy is an open-source python library that parses and “understands” large volumes of text. Separate models are available that cater to specific languages (English, French, German, etc.). "
},
{
"code": null,
"e": 8663,
"s": 8194,
"text": "Download spaCy package :(a) Open anaconda prompt or terminal as administrator and run the command:\n \n \n (b) Now, open anaconda prompt or terminal normally and run the command:\n \n\nIf successful, you should see a message like:\n\n Linking successful\n C:\\Anaconda3\\envs\\spacyenv\\lib\\site-packages\\en_core_web_sm -->\n C:\\Anaconda3\\envs\\spacyenv\\lib\\site-packages\\spacy\\data\\en\n\nYou can now load the model via "
},
{
"code": null,
"e": 8671,
"s": 8663,
"text": "Code: "
},
{
"code": null,
"e": 8679,
"s": 8671,
"text": "Python3"
},
{
"code": "import spacynlp = spacy.load('en_core_web_sm') # Create a Doc objectdoc = nlp(u'the bats saw the cats with best stripes hanging upside down by their feet') # Create list of tokens from given stringtokens = []for token in doc: tokens.append(token) print(tokens)#> [the, bats, saw, the, cats, with, best, stripes, hanging, upside, down, by, their, feet] lemmatized_sentence = \" \".join([token.lemma_ for token in doc]) print(lemmatized_sentence)#> the bat see the cat with good stripe hang upside down by -PRON- foot",
"e": 9196,
"s": 8679,
"text": null
},
{
"code": null,
"e": 9300,
"s": 9196,
"text": "In the above code, we observed that this approach was more powerful than our previous approaches as : "
},
{
"code": null,
"e": 9354,
"s": 9300,
"text": "Even Pro-nouns were detected. ( identified by -PRON-)"
},
{
"code": null,
"e": 9386,
"s": 9354,
"text": "Even best was changed to good. "
},
{
"code": null,
"e": 9643,
"s": 9386,
"text": "6. TreeTagger The TreeTagger is a tool for annotating text with part-of-speech and lemma information. The TreeTagger has been successfully used to tag over 25 languages and is adaptable to other languages if a manually tagged training corpus is available. "
},
{
"code": null,
"e": 9892,
"s": 9643,
"text": "How to use: \n1. Download TreeTagger package : In your anaconda prompt or terminal, type:\n \n2. Download TreeTagger Software: Click on TreeTagger and download the software as per your OS. \n(Steps of installation given on website)"
},
{
"code": null,
"e": 9899,
"s": 9892,
"text": "Code: "
},
{
"code": null,
"e": 9907,
"s": 9899,
"text": "Python3"
},
{
"code": "# 6. TREETAGGER LEMMATIZERimport pandas as pdimport treetaggerwrapper as tt t_tagger = tt.TreeTagger(TAGLANG ='en', TAGDIR ='C:\\Windows\\TreeTagger') pos_tags = t_tagger.tag_text(\"the bats saw the cats with best stripes hanging upside down by their feet\") original = []lemmas = []tags = []for t in pos_tags: original.append(t.split('\\t')[0]) tags.append(t.split('\\t')[1]) lemmas.append(t.split('\\t')[-1]) Results = pd.DataFrame({'Original': original, 'Lemma': lemmas, 'Tags': tags})print(Results) #> Original Lemma Tags# 0 the the DT# 1 bats bat NNS# 2 saw see VVD# 3 the the DT# 4 cats cat NNS# 5 with with IN# 6 best good JJS# 7 stripes stripe NNS# 8 hanging hang VVG# 9 upside upside RB# 10 down down RB# 11 by by IN# 12 their their PP$# 13 feet foot NNS",
"e": 10805,
"s": 9907,
"text": null
},
{
"code": null,
"e": 11051,
"s": 10805,
"text": "7. Pattern Pattern is a Python package commonly used for web mining, natural language processing, machine learning, and network analysis. It has many useful NLP capabilities. It also contains a special feature which we will be discussing below. "
},
{
"code": null,
"e": 11149,
"s": 11051,
"text": "How to use: \nDownload Pattern package: In your anaconda prompt or terminal, type:\n "
},
{
"code": null,
"e": 11156,
"s": 11149,
"text": "Code: "
},
{
"code": null,
"e": 11164,
"s": 11156,
"text": "Python3"
},
{
"code": "# PATTERN LEMMATIZERimport patternfrom pattern.en import lemma, lexemefrom pattern.en import parse sentence = \"the bats saw the cats with best stripes hanging upside down by their feet\" lemmatized_sentence = \" \".join([lemma(word) for word in sentence.split()]) print(lemmatized_sentence)#> the bat see the cat with best stripe hang upside down by their feet # Special Feature : to get all possible lemmas for each word in the sentenceall_lemmas_for_each_word = [lexeme(wd) for wd in sentence.split()]print(all_lemmas_for_each_word) #> [['the', 'thes', 'thing', 'thed'],# ['bat', 'bats', 'batting', 'batted'],# ['see', 'sees', 'seeing', 'saw', 'seen'],# ['the', 'thes', 'thing', 'thed'],# ['cat', 'cats', 'catting', 'catted'],# ['with', 'withs', 'withing', 'withed'],# ['best', 'bests', 'besting', 'bested'],# ['stripe', 'stripes', 'striping', 'striped'],# ['hang', 'hangs', 'hanging', 'hung'],# ['upside', 'upsides', 'upsiding', 'upsided'],# ['down', 'downs', 'downing', 'downed'],# ['by', 'bies', 'bying', 'bied'],# ['their', 'theirs', 'theiring', 'theired'],# ['feet', 'feets', 'feeting', 'feeted']]",
"e": 12292,
"s": 11164,
"text": null
},
{
"code": null,
"e": 12427,
"s": 12292,
"text": "NOTE : if the above code raises an error saying ‘generator raised StopIteration’. Just run it again. It will work after 3-4 tries. "
},
{
"code": null,
"e": 12595,
"s": 12427,
"text": "8. Gensim Gensim is designed to handle large text collections using data streaming. Its lemmatization facilities are based on the pattern package we installed above. "
},
{
"code": null,
"e": 12723,
"s": 12595,
"text": "gensim.utils.lemmatize() function can be used for performing Lemmatization. This method comes under the utils module in python."
},
{
"code": null,
"e": 12820,
"s": 12723,
"text": "We can use this lemmatizer from pattern to extract UTF8-encoded tokens in their base form=lemma."
},
{
"code": null,
"e": 12918,
"s": 12820,
"text": "Only considers nouns, verbs, adjectives, and adverbs by default (all other lemmas are discarded)."
},
{
"code": null,
"e": 12930,
"s": 12918,
"text": "For example"
},
{
"code": null,
"e": 13014,
"s": 12930,
"text": "Word ---> Lemmatized Word \nare/is/being ---> be\nsaw ---> see"
},
{
"code": null,
"e": 13293,
"s": 13014,
"text": "How to use: \n1. Download Pattern package: In your anaconda prompt or terminal, type:\n \n \n2. Download Gensim package: Open your anaconda prompt or terminal as administrator and type:\n \n OR\n "
},
{
"code": null,
"e": 13300,
"s": 13293,
"text": "Code: "
},
{
"code": null,
"e": 13308,
"s": 13300,
"text": "Python3"
},
{
"code": "from gensim.utils import lemmatize sentence = \"the bats saw the cats with best stripes hanging upside down by their feet\" lemmatized_sentence = [word.decode('utf-8').split('.')[0] for word in lemmatize(sentence)] print(lemmatized_sentence)#> ['bat / NN', 'see / VB', 'cat / NN', 'best / JJ',# 'stripe / NN', 'hang / VB', 'upside / RB', 'foot / NN']",
"e": 13659,
"s": 13308,
"text": null
},
{
"code": null,
"e": 13794,
"s": 13659,
"text": "NOTE : if the above code raises an error saying ‘generator raised StopIteration‘. Just run it again. It will work after 3-4 tries. "
},
{
"code": null,
"e": 14005,
"s": 13794,
"text": "In the above code as you may have already noticed, the gensim lemmatizer ignore the words like ‘the’, ‘with’, ‘by’ as they did not fall into the 4 lemma categories mentioned above. (noun/verb/adjective/adverb) "
},
{
"code": null,
"e": 14274,
"s": 14005,
"text": "9. Stanford CoreNLP CoreNLP enables users to derive linguistic annotations for text, including token and sentence boundaries, parts of speech, named entities, numeric and time values, dependency and constituency parses, sentiment, quote attributions, and relations. "
},
{
"code": null,
"e": 14345,
"s": 14274,
"text": "CoreNLP is your one stop shop for natural language processing in Java!"
},
{
"code": null,
"e": 14450,
"s": 14345,
"text": "CoreNLP currently supports 6 languages, including Arabic, Chinese, English, French, German, and Spanish."
},
{
"code": null,
"e": 15268,
"s": 14450,
"text": "How to use: \n1. Get JAVA 8 : Download Java 8 (as per your OS) and install it.\n\n2. Get Stanford_coreNLP package : \n 2.1) Download Stanford_CoreNLP and unzip it. \n 2.2) Open terminal \n \n (a) go to the directory where you extracted the above file by doing\n cd C:\\Users\\...\\stanford-corenlp-4.1.0 on terminal\n \n (b) then, start your Stanford CoreNLP server by executing the following command on terminal: \n java -mx4g -cp \"*\" edu.stanford.nlp.pipeline.StanfordCoreNLPServer -annotators \"tokenize, ssplit, pos, lemma, parse, sentiment\" -port 9000 -timeout 30000\n **(leave your terminal open as long as you use this lemmatizer)** \n \n3. Download Standford CoreNLP package: Open your anaconda prompt or terminal, type:\n "
},
{
"code": null,
"e": 15275,
"s": 15268,
"text": "Code: "
},
{
"code": null,
"e": 15283,
"s": 15275,
"text": "Python3"
},
{
"code": "from stanfordcorenlp import StanfordCoreNLPimport json # Connect to the CoreNLP server we just startednlp = StanfordCoreNLP('http://localhost', port = 9000, timeout = 30000) # Define properties needed to get lemmaprops = {'annotators': 'pos, lemma', 'pipelineLanguage': 'en', 'outputFormat': 'json'} sentence = \"the bats saw the cats with best stripes hanging upside down by their feet\"parsed_str = nlp.annotate(sentence, properties = props)print(parsed_str) #> \"sentences\": [{\"index\": 0,# \"tokens\": [# {# \"index\": 1,# \"word\": \"the\",# \"originalText\": \"the\",# \"lemma\": \"the\", <--------------- LEMMA# \"characterOffsetBegin\": 0,# \"characterOffsetEnd\": 3,# \"pos\": \"DT\",# \"before\": \"\",# \"after\": \" \"# },# {# \"index\": 2,# \"word\": \"bats\",# \"originalText\": \"bats\",# \"lemma\": \"bat\", <--------------- LEMMA# \"characterOffsetBegin\": 4,# \"characterOffsetEnd\": 8,# \"pos\": \"NNS\",# \"before\": \" \",# \"after\": \" \"# },# {# \"index\": 3,# \"word\": \"saw\",# \"originalText\": \"saw\",# \"lemma\": \"see\", <--------------- LEMMA# \"characterOffsetBegin\": 9,# \"characterOffsetEnd\": 12,# \"pos\": \"VBD\",# \"before\": \" \",# \"after\": \" \"# },# {# \"index\": 4,# \"word\": \"the\",# \"originalText\": \"the\",# \"lemma\": \"the\", <--------------- LEMMA# \"characterOffsetBegin\": 13,# \"characterOffsetEnd\": 16,# \"pos\": \"DT\",# \"before\": \" \",# \"after\": \" \"# },# {# \"index\": 5,# \"word\": \"cats\",# \"originalText\": \"cats\",# \"lemma\": \"cat\", <--------------- LEMMA# \"characterOffsetBegin\": 17,# \"characterOffsetEnd\": 21,# \"pos\": \"NNS\",# \"before\": \" \",# \"after\": \" \"# },# {# \"index\": 6,# \"word\": \"with\",# \"originalText\": \"with\",# \"lemma\": \"with\", <--------------- LEMMA# \"characterOffsetBegin\": 22,# \"characterOffsetEnd\": 26,# \"pos\": \"IN\",# \"before\": \" \",# \"after\": \" \"# },# {# \"index\": 7,# \"word\": \"best\",# \"originalText\": \"best\",# \"lemma\": \"best\", <--------------- LEMMA# \"characterOffsetBegin\": 27,# \"characterOffsetEnd\": 31,# \"pos\": \"JJS\",# \"before\": \" \",# \"after\": \" \"# },# {# \"index\": 8,# \"word\": \"stripes\",# \"originalText\": \"stripes\",# \"lemma\": \"stripe\", <--------------- LEMMA# \"characterOffsetBegin\": 32,# \"characterOffsetEnd\": 39,# \"pos\": \"NNS\",# \"before\": \" \",# \"after\": \" \"# },# {# \"index\": 9,# \"word\": \"hanging\",# \"originalText\": \"hanging\",# \"lemma\": \"hang\", <--------------- LEMMA# \"characterOffsetBegin\": 40,# \"characterOffsetEnd\": 47,# \"pos\": \"VBG\",# \"before\": \" \",# \"after\": \" \"# },# {# \"index\": 10,# \"word\": \"upside\",# \"originalText\": \"upside\",# \"lemma\": \"upside\", <--------------- LEMMA# \"characterOffsetBegin\": 48,# \"characterOffsetEnd\": 54,# \"pos\": \"RB\",# \"before\": \" \",# \"after\": \" \"# },# {# \"index\": 11,# \"word\": \"down\",# \"originalText\": \"down\",# \"lemma\": \"down\", <--------------- LEMMA# \"characterOffsetBegin\": 55,# \"characterOffsetEnd\": 59,# \"pos\": \"RB\",# \"before\": \" \",# \"after\": \" \"# },# {# \"index\": 12,# \"word\": \"by\",# \"originalText\": \"by\",# \"lemma\": \"by\", <--------------- LEMMA# \"characterOffsetBegin\": 60,# \"characterOffsetEnd\": 62,# \"pos\": \"IN\",# \"before\": \" \",# \"after\": \" \"# },# {# \"index\": 13,# \"word\": \"their\",# \"originalText\": \"their\",# \"lemma\": \"they\"#, <--------------- LEMMA# \"characterOffsetBegin\": 63,# \"characterOffsetEnd\": 68,# \"pos\": \"PRP$\",# \"before\": \" \",# \"after\": \" \"# },# {# \"index\": 14,# \"word\": \"feet\",# \"originalText\": \"feet\",# \"lemma\": \"foot\", <--------------- LEMMA# \"characterOffsetBegin\": 69,# \"characterOffsetEnd\": 73,# \"pos\": \"NNS\",# \"before\": \" \",# \"after\": \"\"# }# ]# }# ]",
"e": 20118,
"s": 15283,
"text": null
},
{
"code": null,
"e": 20125,
"s": 20118,
"text": "Code: "
},
{
"code": null,
"e": 20133,
"s": 20125,
"text": "Python3"
},
{
"code": "# To get the lemmatized sentence as output # ** RUN THE ABOVE SCRIPT FIRST ** lemma_list = []for item in parsed_dict['sentences'][0]['tokens']: for key, value in item.items(): if key == 'lemma': lemma_list.append(value) print(lemma_list)#> ['the', 'bat', 'see', 'the', 'cat', 'with', 'best', 'stripe', 'hang', 'upside', 'down', 'by', 'they', 'foot'] lemmatized_sentence = \" \".join(lemma_list)print(lemmatized_sentence)#>the bat see the cat with best stripe hang upside down by the foot",
"e": 20648,
"s": 20133,
"text": null
},
{
"code": null,
"e": 21011,
"s": 20648,
"text": "Conclusion: So these are the various Lemmatization approaches that you can refer while working on an NLP project. The selection of the Lemmatization approach is solely dependent upon project requirements. Each approach has its set of pros and cons. Lemmatization is mandatory for critical projects where sentence structure matter like language applications etc. "
},
{
"code": null,
"e": 21031,
"s": 21011,
"text": "abhishek0719kadiyan"
},
{
"code": null,
"e": 21043,
"s": 21031,
"text": "anikakapoor"
},
{
"code": null,
"e": 21056,
"s": 21043,
"text": "simmytarika5"
},
{
"code": null,
"e": 21065,
"s": 21056,
"text": "rkbhola5"
},
{
"code": null,
"e": 21082,
"s": 21065,
"text": "Machine Learning"
},
{
"code": null,
"e": 21089,
"s": 21082,
"text": "Python"
},
{
"code": null,
"e": 21106,
"s": 21089,
"text": "Machine Learning"
}
] |
Path of greater than equal to k length | Practice | GeeksforGeeks
|
Given a graph, a source vertex in the graph, and a number k, find if there is a simple path, of path length greater than or equal to k,(without any cycle) starting from a given source and ending at any other vertex.
Source vertex should always be 0.
Example 1:
Input:
V = 4 , E = 3 and K = 8
A[] = [0, 1, 5, 1, 2, 1, 2, 3, 1]
Output: 0
Explanation:
There exists no path which has a distance
of 8.
Example 2:
Input:
V = 9, E = 14 and K = 60
A[] = [0, 1, 4, 0, 7, 8, 1, 2, 8, 1, 7,
11, 2, 3, 7, 2, 5, 4, 2, 8, 2, 3, 4, 9,
3, 5, 14, 4, 5, 10, 5, 6, 2, 6, 7, 1, 6,
8, 6, 7, 8, 7]
Output: 0
Explanation:
Your Task:
You don't need to read input or print anything. Your task is to complete the function pathMoreThanK() which takes the integer V, Edges E, an integer K and Array A which is having (Source, Destination, Weight) as input parameters and returns 1 if the path of at least k distance exists, else returns 0.
Expected Time Complexity: O(N!)
Expected Auxiliary Space: O(N)
Constraints:
2 ≤ V ≤ 5
1 ≤ E ≤ 20
1 ≤ K ≤ 100
0
putyavka4 days ago
struct EE { int u, d; };
vector<int> F;
bool dfs(vector<vector<EE>>& G, int v, int d, int k) {
if (F[v]) return false;
if (d >= k) return true;
F[v] = 1;
for (auto &e: G[v])
if (dfs(G, e.u, d+e.d, k)) return true;
F[v] = 0;
return false;
}
bool pathMoreThanK(int V, int E, int k, int *a) {
vector<vector<EE>> G(V); F.resize(V);
for (int i = 0; i < E; i++)
G[a[i*3]].push_back({a[i*3+1],a[i*3+2]}),
G[a[i*3+1]].push_back({a[i*3],a[i*3+2]});
return dfs(G, 0, 0, k);
}
0
kvatsadeo6 days ago
public:
bool helper(int i,int k,vector<bool> &vis,vector<pair<int,int>> adj[]){
if(vis[i]==true) return false;
if(k<=0) return true;
vis[i]=1;
for(auto it:adj[i]){
if(!vis[it.first]){
if(helper(it.first,k-it.second,vis,adj)) return true;
}
}
vis[i]=0;
return false;
}
bool pathMoreThanK(int V, int E, int k, int *a)
{
// Code Here
vector<pair<int,int>> adj[V];
int n=3*E;
for(int i=0;i<=n-3;i+=3){
int u=a[i];
int v=a[i+1];
int wt=a[i+2];
adj[u].push_back({v,wt});
adj[v].push_back({u,wt});
}
// for(int i=0;i<V;i++){
// for(auto it:adj[i]){
// cout<<i<<" "<<it.first<<"-->"<<it.second<<endl;
// }
// }
vector<bool> vis(V,0);
return helper(0,k,vis,adj);
}
};
0
vickyupadhyay361 week ago
Easy C++ Code using DFS
int dfs(vector<pair<int,int>> adj[],vector<int> &vis,int &k,int &m,int dis,int node){
if(m>=k) return 1;
vis[node]=1;
int i,wt;
for(auto x:adj[node]){
i=x.first;
wt=x.second;
if(!vis[i]){
m=max(m,dis+wt);
if(dfs(adj,vis,k,m,dis+wt,i)) return 1;
}
}
vis[node]=0;
return 0;
}
bool pathMoreThanK(int V, int E, int k, int *a)
{
// Code Here
vector<pair<int,int>> adj[V];
int n=3*E;
for(int i=0;i<n-2;i+=3){
adj[a[i]].push_back({a[i+1],a[i+2]});
adj[a[i+1]].push_back({a[i],a[i+2]});
}
vector<int> vis(V,0);
int dis=0,m=0;
return dfs(adj,vis,k,m,dis,0);
}
0
shubhamkulkarni16291 week ago
bool dfs(int node,vector<pair<int,int>>adj[],vector<int>&visited,int &ans,int k){ visited[node]=1; if(ans>=k) return true; for(auto x:adj[node]) { //base case if(!visited[x.first]) { ans=ans+x.second; if(dfs(x.first,adj,visited,ans,k)) { return true; } ans=ans-x.second; } } visited[node]=0; return false;}
bool pathMoreThanK(int V, int E, int k, int *a) { // Code Here vector<pair<int,int>>adj[V+1]; for(int i=0; i<3*E-2; i+=3) { adj[a[i]].push_back({a[i+1], a[i+2]}); adj[a[i+1]].push_back({a[i],a[i+2]}); } vector<int>visited(V,0); int ans=0; if(dfs(0,adj,visited,ans,k)) { return true; } return false; } };
0
roboto7o32oo32 weeks ago
Clean C++ Solution ✨ ✨
class Solution {
public:
bool solve(vector<vector<vector<int>>>& AList, unordered_set<int>& visited, int k, int u){
if(visited.count(u)){
return false;
}
if(k <= 0){
return true;
}
visited.insert(u);
for(vector<int> edge : AList[u]){
if(solve(AList, visited, k-edge[1], edge[0])){
return true;
}
}
visited.erase(u);
return false;
}
bool pathMoreThanK(int V, int E, int k, int *a)
{
vector<vector<vector<int>>> AList(V, vector<vector<int>>());
for(int i=0; i<E; i++){
int u = a[3*i];
int v = a[3*i + 1];
int w = a[3*i + 2];
AList[u].push_back({v,w});
AList[v].push_back({u,w});
}
unordered_set<int> visited;
return solve(AList, visited, k, 0);
}
};
+1
ashishkyjp113 weeks ago
// Easy C++ code (really very easy)
void dfs(vector<pair<int, int>> g[], vector<int> &path, int key, int cost, int k, bool &ans)
{
if(ans)
return;
path[key]=1;
if(cost>=k)
{
ans=true;
return;
}
for(auto a:g[key])
{
if(!path[a.first])
{
// path[key]=0;
// return;
dfs(g, path, a.first, cost+a.second, k, ans);
}
}
path[key]=0;
}
bool pathMoreThanK(int V, int E, int k, int *a)
{
// Code Here
// dfgjhkfdgh
vector<pair<int, int>> g[V+1];
vector<int> path(V+1);
bool ans=false;
for(int i=0; i<3*E-2; i+=3)
{
g[a[i]].push_back({a[i+1], a[i+2]});
g[a[i+1]].push_back({a[i],a[i+2]});
}
dfs(g, path, 0, 0, k, ans);
return ans;
}
0
shivaraj54 weeks ago
//simple recursive solution
bool solve(int src,int k,vector<pair<int,int>>adj[],vector<bool>&vis){ vis[src]=true; if(k<=0) return true; for(auto x:adj[src]){ int v=x.first; int w=x.second; if(vis[v])//it there is a cycle continue; if(w>=k) return true; if(solve(v,k-w,adj,vis)) return true; } vis[src]=false; return false; } bool pathMoreThanK(int n, int m, int k, int *a) { // Code Here vector<pair<int,int>>adj[n]; for(int i=0;i<m;i++){ adj[*a].push_back({*(a+1),*(a+2)}); adj[*(a+1)].push_back({*a,*(a+2)}); a=a+3; } vector<bool>vis(n,0); return solve(0,k,adj,vis); }
0
bishtrockkak1 month ago
int ans;
void dfs(vector<vector<pair<int,int>>>&g,int node,vector<int>&vis,int path){
ans=max(ans,path);
for(auto i : g[node]){
if(vis[i.first]==1){
continue;
}
else{
vis[i.first]=1;
dfs(g,i.first,vis,path+i.second);
vis[i.first]=0;
}
}
}
0
kartik_ey_11 month ago
void dfs(vector<pair<int,int>>adj[] , vector<bool>&visited , int &count, int k , int h , int node){ if(h>=k)count++; visited[node]=true; for(auto m:adj[node]){ if(!visited[m.first]){ dfs(adj,visited,count , k , h+m.second , m.first); } } visited[node]=false; } bool pathMoreThanK(int V, int E, int k, int *a) { // Code Here vector<pair<int,int>>adj[V]; for(int i=0;i<3*E-2;i+=3){ adj[a[i]].push_back({a[i+1],a[i+2]}); adj[a[i+1]].push_back({a[i],a[i+2]}); } vector<bool>visited(V,0); int count = 0; int r=0; dfs(adj,visited,count,k,r,0); return count; }
+4
dev1713 months ago
SIMPLE C++ DFS + BACKTRACKING
bool solve(int node,int path,int k,vector<pair<int,int>>adj[],vector<int>vis){
if(path>=k)
return true;
vis[node]=1;
for(auto it:adj[node]){
if(!vis[it.first]){
if(solve(it.first,path+it.second,k,adj,vis))
return true;
}
}
vis[node]=0;
return false;
}
bool pathMoreThanK(int v, int e, int k, int *a)
{
// Code Here
vector<pair<int,int>>adj[v];
for(int i=0;i<3*e-2;i+=3){
adj[a[i]].push_back({a[i+1],a[i+2]});
adj[a[i+1]].push_back({a[i],a[i+2]});
}
vector<int>vis(v,0);
vis[0]=1;
return solve(0,0,k,adj,vis);
}
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested
against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code.
On submission, your code is tested against multiple test cases consisting of all
possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as
the final solution code.
You can view the solutions submitted by other users from the submission tab.
Make sure you are not using ad-blockers.
Disable browser extensions.
We recommend using latest version of your browser for best experience.
Avoid using static/global variables in coding problems as your code is tested
against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases in coding problems does not guarantee the
correctness of code. On submission, your code is tested against multiple test cases
consisting of all possible corner cases and stress constraints.
|
[
{
"code": null,
"e": 477,
"s": 226,
"text": "Given a graph, a source vertex in the graph, and a number k, find if there is a simple path, of path length greater than or equal to k,(without any cycle) starting from a given source and ending at any other vertex.\nSource vertex should always be 0."
},
{
"code": null,
"e": 488,
"s": 477,
"text": "Example 1:"
},
{
"code": null,
"e": 627,
"s": 488,
"text": "Input:\nV = 4 , E = 3 and K = 8\nA[] = [0, 1, 5, 1, 2, 1, 2, 3, 1]\nOutput: 0\nExplanation:\nThere exists no path which has a distance \nof 8. \n"
},
{
"code": null,
"e": 640,
"s": 629,
"text": "Example 2:"
},
{
"code": null,
"e": 839,
"s": 640,
"text": "Input:\nV = 9, E = 14 and K = 60\nA[] = [0, 1, 4, 0, 7, 8, 1, 2, 8, 1, 7, \n11, 2, 3, 7, 2, 5, 4, 2, 8, 2, 3, 4, 9, \n3, 5, 14, 4, 5, 10, 5, 6, 2, 6, 7, 1, 6, \n8, 6, 7, 8, 7]\nOutput: 0\nExplanation:\n\n \n\n"
},
{
"code": null,
"e": 1219,
"s": 839,
"text": "\nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function pathMoreThanK() which takes the integer V, Edges E, an integer K and Array A which is having (Source, Destination, Weight) as input parameters and returns 1 if the path of at least k distance exists, else returns 0.\n\nExpected Time Complexity: O(N!)\nExpected Auxiliary Space: O(N)"
},
{
"code": null,
"e": 1267,
"s": 1221,
"text": "Constraints:\n2 ≤ V ≤ 5\n1 ≤ E ≤ 20\n1 ≤ K ≤ 100"
},
{
"code": null,
"e": 1269,
"s": 1267,
"text": "0"
},
{
"code": null,
"e": 1288,
"s": 1269,
"text": "putyavka4 days ago"
},
{
"code": null,
"e": 1816,
"s": 1288,
"text": "struct EE { int u, d; };\nvector<int> F;\nbool dfs(vector<vector<EE>>& G, int v, int d, int k) {\n if (F[v]) return false;\n if (d >= k) return true;\n F[v] = 1;\n for (auto &e: G[v])\n if (dfs(G, e.u, d+e.d, k)) return true;\n F[v] = 0;\n return false;\n}\nbool pathMoreThanK(int V, int E, int k, int *a) { \n vector<vector<EE>> G(V); F.resize(V);\n for (int i = 0; i < E; i++)\n G[a[i*3]].push_back({a[i*3+1],a[i*3+2]}),\n G[a[i*3+1]].push_back({a[i*3],a[i*3+2]});\n return dfs(G, 0, 0, k);\n} "
},
{
"code": null,
"e": 1818,
"s": 1816,
"text": "0"
},
{
"code": null,
"e": 1838,
"s": 1818,
"text": "kvatsadeo6 days ago"
},
{
"code": null,
"e": 2766,
"s": 1838,
"text": "public:\n bool helper(int i,int k,vector<bool> &vis,vector<pair<int,int>> adj[]){\n if(vis[i]==true) return false;\n if(k<=0) return true;\n vis[i]=1;\n for(auto it:adj[i]){\n if(!vis[it.first]){\n if(helper(it.first,k-it.second,vis,adj)) return true;\n }\n }\n vis[i]=0;\n return false;\n }\n bool pathMoreThanK(int V, int E, int k, int *a) \n { \n // Code Here\n vector<pair<int,int>> adj[V];\n int n=3*E;\n for(int i=0;i<=n-3;i+=3){\n int u=a[i];\n int v=a[i+1];\n int wt=a[i+2];\n adj[u].push_back({v,wt});\n adj[v].push_back({u,wt});\n }\n // for(int i=0;i<V;i++){\n // for(auto it:adj[i]){\n // cout<<i<<\" \"<<it.first<<\"-->\"<<it.second<<endl;\n // }\n // }\n vector<bool> vis(V,0);\n return helper(0,k,vis,adj);\n } \n};"
},
{
"code": null,
"e": 2768,
"s": 2766,
"text": "0"
},
{
"code": null,
"e": 2794,
"s": 2768,
"text": "vickyupadhyay361 week ago"
},
{
"code": null,
"e": 2819,
"s": 2794,
"text": "Easy C++ Code using DFS "
},
{
"code": null,
"e": 3609,
"s": 2819,
"text": "int dfs(vector<pair<int,int>> adj[],vector<int> &vis,int &k,int &m,int dis,int node){\n if(m>=k) return 1;\n vis[node]=1;\n int i,wt;\n for(auto x:adj[node]){\n i=x.first;\n wt=x.second;\n if(!vis[i]){\n m=max(m,dis+wt);\n if(dfs(adj,vis,k,m,dis+wt,i)) return 1;\n }\n }\n vis[node]=0;\n return 0;\n }\n bool pathMoreThanK(int V, int E, int k, int *a) \n { \n // Code Here\n vector<pair<int,int>> adj[V];\n int n=3*E;\n for(int i=0;i<n-2;i+=3){\n adj[a[i]].push_back({a[i+1],a[i+2]});\n adj[a[i+1]].push_back({a[i],a[i+2]});\n }\n \n vector<int> vis(V,0);\n int dis=0,m=0;\n return dfs(adj,vis,k,m,dis,0);\n } "
},
{
"code": null,
"e": 3611,
"s": 3609,
"text": "0"
},
{
"code": null,
"e": 3641,
"s": 3611,
"text": "shubhamkulkarni16291 week ago"
},
{
"code": null,
"e": 4105,
"s": 3641,
"text": "bool dfs(int node,vector<pair<int,int>>adj[],vector<int>&visited,int &ans,int k){ visited[node]=1; if(ans>=k) return true; for(auto x:adj[node]) { //base case if(!visited[x.first]) { ans=ans+x.second; if(dfs(x.first,adj,visited,ans,k)) { return true; } ans=ans-x.second; } } visited[node]=0; return false;}"
},
{
"code": null,
"e": 4554,
"s": 4105,
"text": " bool pathMoreThanK(int V, int E, int k, int *a) { // Code Here vector<pair<int,int>>adj[V+1]; for(int i=0; i<3*E-2; i+=3) { adj[a[i]].push_back({a[i+1], a[i+2]}); adj[a[i+1]].push_back({a[i],a[i+2]}); } vector<int>visited(V,0); int ans=0; if(dfs(0,adj,visited,ans,k)) { return true; } return false; } };"
},
{
"code": null,
"e": 4556,
"s": 4554,
"text": "0"
},
{
"code": null,
"e": 4581,
"s": 4556,
"text": "roboto7o32oo32 weeks ago"
},
{
"code": null,
"e": 4604,
"s": 4581,
"text": "Clean C++ Solution ✨ ✨"
},
{
"code": null,
"e": 5592,
"s": 4606,
"text": "class Solution {\n\npublic:\n\n bool solve(vector<vector<vector<int>>>& AList, unordered_set<int>& visited, int k, int u){\n if(visited.count(u)){\n return false;\n }\n if(k <= 0){\n return true;\n }\n \n visited.insert(u);\n \n for(vector<int> edge : AList[u]){\n if(solve(AList, visited, k-edge[1], edge[0])){\n return true;\n }\n }\n \n visited.erase(u);\n \n return false;\n }\n\n bool pathMoreThanK(int V, int E, int k, int *a) \n { \n vector<vector<vector<int>>> AList(V, vector<vector<int>>());\n \n for(int i=0; i<E; i++){\n int u = a[3*i];\n int v = a[3*i + 1];\n int w = a[3*i + 2];\n \n AList[u].push_back({v,w});\n AList[v].push_back({u,w});\n }\n \n unordered_set<int> visited;\n \n return solve(AList, visited, k, 0);\n } \n};"
},
{
"code": null,
"e": 5595,
"s": 5592,
"text": "+1"
},
{
"code": null,
"e": 5619,
"s": 5595,
"text": "ashishkyjp113 weeks ago"
},
{
"code": null,
"e": 6640,
"s": 5619,
"text": "// Easy C++ code (really very easy)\n\nvoid dfs(vector<pair<int, int>> g[], vector<int> &path, int key, int cost, int k, bool &ans)\n {\n if(ans)\n return;\n path[key]=1;\n \n if(cost>=k)\n {\n ans=true;\n return;\n }\n \n for(auto a:g[key])\n {\n if(!path[a.first])\n {\n // path[key]=0;\n // return;\n \n dfs(g, path, a.first, cost+a.second, k, ans);\n }\n \n }\n \n \n path[key]=0;\n }\n\n bool pathMoreThanK(int V, int E, int k, int *a) \n { \n // Code Here\n // dfgjhkfdgh\n vector<pair<int, int>> g[V+1];\n vector<int> path(V+1);\n bool ans=false;\n \n for(int i=0; i<3*E-2; i+=3)\n {\n g[a[i]].push_back({a[i+1], a[i+2]});\n g[a[i+1]].push_back({a[i],a[i+2]});\n }\n \n dfs(g, path, 0, 0, k, ans);\n \n return ans;\n } "
},
{
"code": null,
"e": 6646,
"s": 6644,
"text": "0"
},
{
"code": null,
"e": 6667,
"s": 6646,
"text": "shivaraj54 weeks ago"
},
{
"code": null,
"e": 6695,
"s": 6667,
"text": "//simple recursive solution"
},
{
"code": null,
"e": 7369,
"s": 6695,
"text": "bool solve(int src,int k,vector<pair<int,int>>adj[],vector<bool>&vis){ vis[src]=true; if(k<=0) return true; for(auto x:adj[src]){ int v=x.first; int w=x.second; if(vis[v])//it there is a cycle continue; if(w>=k) return true; if(solve(v,k-w,adj,vis)) return true; } vis[src]=false; return false; } bool pathMoreThanK(int n, int m, int k, int *a) { // Code Here vector<pair<int,int>>adj[n]; for(int i=0;i<m;i++){ adj[*a].push_back({*(a+1),*(a+2)}); adj[*(a+1)].push_back({*a,*(a+2)}); a=a+3; } vector<bool>vis(n,0); return solve(0,k,adj,vis); } "
},
{
"code": null,
"e": 7371,
"s": 7369,
"text": "0"
},
{
"code": null,
"e": 7395,
"s": 7371,
"text": "bishtrockkak1 month ago"
},
{
"code": null,
"e": 7778,
"s": 7395,
"text": "int ans;\n void dfs(vector<vector<pair<int,int>>>&g,int node,vector<int>&vis,int path){\n ans=max(ans,path);\n for(auto i : g[node]){\n if(vis[i.first]==1){\n continue;\n }\n else{\n vis[i.first]=1;\n dfs(g,i.first,vis,path+i.second);\n vis[i.first]=0;\n }\n }\n }"
},
{
"code": null,
"e": 7780,
"s": 7778,
"text": "0"
},
{
"code": null,
"e": 7803,
"s": 7780,
"text": "kartik_ey_11 month ago"
},
{
"code": null,
"e": 8485,
"s": 7803,
"text": " void dfs(vector<pair<int,int>>adj[] , vector<bool>&visited , int &count, int k , int h , int node){ if(h>=k)count++; visited[node]=true; for(auto m:adj[node]){ if(!visited[m.first]){ dfs(adj,visited,count , k , h+m.second , m.first); } } visited[node]=false; } bool pathMoreThanK(int V, int E, int k, int *a) { // Code Here vector<pair<int,int>>adj[V]; for(int i=0;i<3*E-2;i+=3){ adj[a[i]].push_back({a[i+1],a[i+2]}); adj[a[i+1]].push_back({a[i],a[i+2]}); } vector<bool>visited(V,0); int count = 0; int r=0; dfs(adj,visited,count,k,r,0); return count; } "
},
{
"code": null,
"e": 8488,
"s": 8485,
"text": "+4"
},
{
"code": null,
"e": 8507,
"s": 8488,
"text": "dev1713 months ago"
},
{
"code": null,
"e": 8537,
"s": 8507,
"text": "SIMPLE C++ DFS + BACKTRACKING"
},
{
"code": null,
"e": 9265,
"s": 8537,
"text": "\n bool solve(int node,int path,int k,vector<pair<int,int>>adj[],vector<int>vis){\n if(path>=k)\n return true;\n vis[node]=1;\n for(auto it:adj[node]){\n if(!vis[it.first]){\n if(solve(it.first,path+it.second,k,adj,vis))\n return true;\n }\n }\n vis[node]=0;\n return false;\n }\n bool pathMoreThanK(int v, int e, int k, int *a) \n { \n // Code Here\n vector<pair<int,int>>adj[v];\n for(int i=0;i<3*e-2;i+=3){\n adj[a[i]].push_back({a[i+1],a[i+2]});\n adj[a[i+1]].push_back({a[i],a[i+2]});\n }\n vector<int>vis(v,0);\n vis[0]=1;\n return solve(0,0,k,adj,vis);\n } "
},
{
"code": null,
"e": 9411,
"s": 9265,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 9447,
"s": 9411,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 9457,
"s": 9447,
"text": "\nProblem\n"
},
{
"code": null,
"e": 9467,
"s": 9457,
"text": "\nContest\n"
},
{
"code": null,
"e": 9530,
"s": 9467,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 9715,
"s": 9530,
"text": "Avoid using static/global variables in your code as your code is tested \n against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 9999,
"s": 9715,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code.\n On submission, your code is tested against multiple test cases consisting of all\n possible corner cases and stress constraints."
},
{
"code": null,
"e": 10145,
"s": 9999,
"text": "You can access the hints to get an idea about what is expected of you as well as\n the final solution code."
},
{
"code": null,
"e": 10222,
"s": 10145,
"text": "You can view the solutions submitted by other users from the submission tab."
},
{
"code": null,
"e": 10263,
"s": 10222,
"text": "Make sure you are not using ad-blockers."
},
{
"code": null,
"e": 10291,
"s": 10263,
"text": "Disable browser extensions."
},
{
"code": null,
"e": 10362,
"s": 10291,
"text": "We recommend using latest version of your browser for best experience."
},
{
"code": null,
"e": 10549,
"s": 10362,
"text": "Avoid using static/global variables in coding problems as your code is tested \n against multiple test cases and these tend to retain their previous values."
}
] |
Flutter – Using Google fonts
|
21 Oct, 2020
Any UI developer that builds an application has to deal with fonts. Google Fonts provides a wide range of fonts that can be used to improve the fonts of the User Interface. Flutter provides a Google fonts package that can be used to implements various available fonts. Some fonts that are available for use through the Google fonts package are listed below:
Roboto
Open sans
Lato
Oswald
Raleway
In this article, we will build a simple app and implement some Google fonts to it. To do so follow the below steps:
Add the google_fonts dependency to the pubspec.yaml file.
Import the dependency to the main.dart file.
Use the StatelessWidget to give the structure to the application
Use a StatefulWidget to design the homepage for the application
Add a text to the body of the app body and apply the fonts
Use the Google fonts dependency in the pubspec.yaml as shown below:
To import the dependency in the main.dart file as below:
import 'package:google_fonts/google_fonts.dart';
Use the StatelessWidget to give a simple structure to the application as shown below:
Dart
class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(title: 'GeeksForGeeks'), ); }}
To design, the homepage for the application makes use of the StatefulWidget. Initiate the state at 0 that counts the number of clicks on the button that we will be adding to the homepage. To do so use the below:
Dart
class MyHomePage extends StatefulWidget { MyHomePage({Key key, this.title}) : super(key: key); final String title; @override _MyHomePageState createState() => _MyHomePageState();} class _MyHomePageState extends State<MyHomePage> { int _counter = 0; void _incrementCounter() { setState(() { _counter++; }); }
The font that we will be Oswald font and Lato font. In the TextStyle property you can add the same as shown below:
Dart
children: <Widget>[ Text( 'You have pushed the button this many times:', style: GoogleFonts.oswald(textStyle: display1), ), Text( '$_counter', style: GoogleFonts.lato(fontStyle: FontStyle.italic), ), ], ),),
Complete Source Code:
Dart
import 'package:flutter/material.dart';import 'package:google_fonts/google_fonts.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(title: 'GeeksForGeeks'), ); }} class MyHomePage extends StatefulWidget { MyHomePage({Key key, this.title}) : super(key: key); final String title; @override _MyHomePageState createState() => _MyHomePageState();} class _MyHomePageState extends State<MyHomePage> { int _counter = 0; void _incrementCounter() { setState(() { _counter++; }); } @override Widget build(BuildContext context) { final TextStyle display1 = Theme.of(context).textTheme.headline4; return Scaffold( appBar: AppBar( title: Text(widget.title), backgroundColor: Colors.green, ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text( 'You have pushed the button this many times:', style: GoogleFonts.oswald(textStyle: display1), ), Text( '$_counter', style: GoogleFonts.lato(fontStyle: FontStyle.italic), ), ], ), ), floatingActionButton: FloatingActionButton( onPressed: _incrementCounter, tooltip: 'Increment', child: Icon(Icons.play_arrow), ), ); }}
Output:
android
Flutter
Flutter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Oct, 2020"
},
{
"code": null,
"e": 386,
"s": 28,
"text": "Any UI developer that builds an application has to deal with fonts. Google Fonts provides a wide range of fonts that can be used to improve the fonts of the User Interface. Flutter provides a Google fonts package that can be used to implements various available fonts. Some fonts that are available for use through the Google fonts package are listed below:"
},
{
"code": null,
"e": 393,
"s": 386,
"text": "Roboto"
},
{
"code": null,
"e": 403,
"s": 393,
"text": "Open sans"
},
{
"code": null,
"e": 408,
"s": 403,
"text": "Lato"
},
{
"code": null,
"e": 415,
"s": 408,
"text": "Oswald"
},
{
"code": null,
"e": 423,
"s": 415,
"text": "Raleway"
},
{
"code": null,
"e": 539,
"s": 423,
"text": "In this article, we will build a simple app and implement some Google fonts to it. To do so follow the below steps:"
},
{
"code": null,
"e": 597,
"s": 539,
"text": "Add the google_fonts dependency to the pubspec.yaml file."
},
{
"code": null,
"e": 642,
"s": 597,
"text": "Import the dependency to the main.dart file."
},
{
"code": null,
"e": 707,
"s": 642,
"text": "Use the StatelessWidget to give the structure to the application"
},
{
"code": null,
"e": 771,
"s": 707,
"text": "Use a StatefulWidget to design the homepage for the application"
},
{
"code": null,
"e": 830,
"s": 771,
"text": "Add a text to the body of the app body and apply the fonts"
},
{
"code": null,
"e": 898,
"s": 830,
"text": "Use the Google fonts dependency in the pubspec.yaml as shown below:"
},
{
"code": null,
"e": 955,
"s": 898,
"text": "To import the dependency in the main.dart file as below:"
},
{
"code": null,
"e": 1005,
"s": 955,
"text": "import 'package:google_fonts/google_fonts.dart';\n"
},
{
"code": null,
"e": 1091,
"s": 1005,
"text": "Use the StatelessWidget to give a simple structure to the application as shown below:"
},
{
"code": null,
"e": 1096,
"s": 1091,
"text": "Dart"
},
{
"code": "class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(title: 'GeeksForGeeks'), ); }}",
"e": 1357,
"s": 1096,
"text": null
},
{
"code": null,
"e": 1569,
"s": 1357,
"text": "To design, the homepage for the application makes use of the StatefulWidget. Initiate the state at 0 that counts the number of clicks on the button that we will be adding to the homepage. To do so use the below:"
},
{
"code": null,
"e": 1574,
"s": 1569,
"text": "Dart"
},
{
"code": "class MyHomePage extends StatefulWidget { MyHomePage({Key key, this.title}) : super(key: key); final String title; @override _MyHomePageState createState() => _MyHomePageState();} class _MyHomePageState extends State<MyHomePage> { int _counter = 0; void _incrementCounter() { setState(() { _counter++; }); }",
"e": 1907,
"s": 1574,
"text": null
},
{
"code": null,
"e": 2022,
"s": 1907,
"text": "The font that we will be Oswald font and Lato font. In the TextStyle property you can add the same as shown below:"
},
{
"code": null,
"e": 2027,
"s": 2022,
"text": "Dart"
},
{
"code": " children: <Widget>[ Text( 'You have pushed the button this many times:', style: GoogleFonts.oswald(textStyle: display1), ), Text( '$_counter', style: GoogleFonts.lato(fontStyle: FontStyle.italic), ), ], ),),",
"e": 2291,
"s": 2027,
"text": null
},
{
"code": null,
"e": 2313,
"s": 2291,
"text": "Complete Source Code:"
},
{
"code": null,
"e": 2318,
"s": 2313,
"text": "Dart"
},
{
"code": "import 'package:flutter/material.dart';import 'package:google_fonts/google_fonts.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(title: 'GeeksForGeeks'), ); }} class MyHomePage extends StatefulWidget { MyHomePage({Key key, this.title}) : super(key: key); final String title; @override _MyHomePageState createState() => _MyHomePageState();} class _MyHomePageState extends State<MyHomePage> { int _counter = 0; void _incrementCounter() { setState(() { _counter++; }); } @override Widget build(BuildContext context) { final TextStyle display1 = Theme.of(context).textTheme.headline4; return Scaffold( appBar: AppBar( title: Text(widget.title), backgroundColor: Colors.green, ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text( 'You have pushed the button this many times:', style: GoogleFonts.oswald(textStyle: display1), ), Text( '$_counter', style: GoogleFonts.lato(fontStyle: FontStyle.italic), ), ], ), ), floatingActionButton: FloatingActionButton( onPressed: _incrementCounter, tooltip: 'Increment', child: Icon(Icons.play_arrow), ), ); }}",
"e": 3877,
"s": 2318,
"text": null
},
{
"code": null,
"e": 3885,
"s": 3877,
"text": "Output:"
},
{
"code": null,
"e": 3893,
"s": 3885,
"text": "android"
},
{
"code": null,
"e": 3901,
"s": 3893,
"text": "Flutter"
},
{
"code": null,
"e": 3909,
"s": 3901,
"text": "Flutter"
}
] |
Linux Virtualization : Resource throttling using cgroups
|
05 Nov, 2021
In Linux Virtualization – Chroot Jail article, we discussed about kernel namespaces and process jailing. To understand this article, you may not need to read the earlier one, but I strongly suggest that you go through it once before diving into resource throttling. It should help tremendously in understanding what’s going on.
What are cgroups?
cgroups (abbreviated from control groups) is a Linux kernel feature that limits, accounts for, and isolates the resource usage (CPU, memory, disk I/O, network, etc.) of a collection of processes. This feature was originally developed by 2 engineers from Google, under the name “process containers” but later merged in the Linux kernel mainline with name “cgroups”.
Why is it required?
One of the design goals of cgroups is to provide a unified interface to many different use cases, from controlling single processes (by using nice, for example) to whole operating system-level virtualization. In simple words, cgroups provides:
Resource limiting: Groups can be set to not exceed a configured memory limit, which also includes the file system cache.
Prioritization – Some groups may get a larger share of CPU utilization or disk I/O throughput.
Accounting – measures a group’s resource usage, which may be used, for example, for billing purposes.
Control – freezing groups of processes, their checkpointing and restarting.
How are they used, directly or indirectly?
Control groups can be used in multiple ways:
By accessing the cgroup virtual file system manually.By creating and managing groups on the fly using tools like cgcreate, cgexec, and cgclassify (from libcgroup).Through the “rules engine daemon” that can automatically move processes of certain users, groups, or commands to cgroups as specified in its configuration.Indirectly through other software that uses cgroups, such as Docker, Linux Containers (LXC) virtualization, libvirt, systemd, Open Grid Scheduler/Grid Engine, and Google’s lmctfy.
By accessing the cgroup virtual file system manually.
By creating and managing groups on the fly using tools like cgcreate, cgexec, and cgclassify (from libcgroup).
Through the “rules engine daemon” that can automatically move processes of certain users, groups, or commands to cgroups as specified in its configuration.
Indirectly through other software that uses cgroups, such as Docker, Linux Containers (LXC) virtualization, libvirt, systemd, Open Grid Scheduler/Grid Engine, and Google’s lmctfy.
You might be surprised but this silent daemon makes up a substantial part of your online experience as quite a bunch of websites use containers/virtualization to host multiple servers or websites, including NetFlix, heruko and reddit.
Installing cgroups: Some Linux versions come pre-installed with cgroups. To check if they are already installed/mounted, check the output of:
$ mount | grep "^cgroup"
If you see files mounted on /sys/fs/cgroup/ then you can jump to the next topic directly to skip the installation part. The 2nd command installs the cgroup-tools which makes it easier to control and monitor control groups. We would be using the commands from the same in this tutorial. We will use the iotop utility to monitor disk I/O rates.
$ sudo apt-get install cgroup-bin cgroup-lite libcgroup1 cgroup-lite
$ sudo apt-get install cgroup-tools
$ sudo apt-get install iotop
If you installed the cgroups but cannot see them mounted at /sys/fs/cgroup, then use these commands,
$ mount -t tmpfs cgroup_root /sys/fs/cgroup
$ mkdir /sys/fs/cgroup/blkio
$ mount -t cgroup -o blkio none /sys/fs/cgroup/blkio
Example 1: We will create a disk-controlled group so that we may run any process with a finite amount of disk read/writes available. i.e. we want to throttle reads and writes done by a process or a group of processes.
Step 1: To create a cgroup simply create a directory in /sys/fs/cgroup or if you have a cgroup-tools setup, then we can use them, in the appropriate directory for the subsystem. The kernel automatically fills the cgroup’s directory with the settings file nodes. Though, it’s recommended to use the cgroup-tools API,
# Switch to root for the rest of the commands
$ sudo su
$ cgcreate -g blkio:myapp OR mkdir /sys/fs/cgroup/blkio/myapp
This command will create a sub-group “myapp” under the “blkio” system. The Block I/O (blkio) subsystem controls and monitors access to I/O on block devices by tasks in cgroups. Writing values to these files provides controlled access to various resources. You can check if your group is created, by running the command, lscgroup, which lists all the control groups.
$ lscgroup | grep blkio:/myapp
blkio:/myapp
Important: These files are not normal files on disk. These are pseudo files and are used directly by the kernel to read and modify the configuration. Do not open them in a text editor and try to save them. Always use the “echo” command to write to them.
Before diving into easy stuff, let’s look at the directory structure of the newly created group. Here are some of the important files that we will need for this tutorial to understand how cgroup works. (Most important ones are highlighted in the image)
Step 2: We create 2 terminal and place them one below the other. Become root user in both the terminals. In the top-terminal we run the iotop utility to monitor the disk I/O,
$ sudo su
$ iotop -o
While on the below terminal, we create a temporary file of 512 MB using the “dd” command
$ sudo su
$ dd if=/dev/zero of=~/test_if bs=1M count=512
In the dd command, “if” represents the input file, “of” is the output file, “bs” is the block size and “count” is the no of times it writes the block. Once the command finishes, ~/temp_if is created with size 512 MB. You can see the realtime I/O rates on the top-terminal window.
Step 3: Now for our next experiment, we need to make sure that we have flushed all the file system buffers to disk and dropped all the caches so that they do not interfere with our results.
$ free -m
$ sync
$ echo 3 > /proc/sys/vm/drop_caches
$ free -m
Now, you should see a increase in the available RAM and reduced cache size.
Step 3: Now to setup throttling limits, we use the following commands. Say, we would like to set a read/write limit of 5 MB for a process. From the kernel documentation, you’ll find that, blkio.throttle.read_bps_device and blkio.throttle.write_bps_device accept entries of the format,
<major>:<minor> <rates_per_second>
where, major and minor are the values for a particular device, which we want to rate limit. rates_per_second is the maximum rate that can be achieved by the process of that group.
Getting the major and minor numbers is easy. The machine i am working on only has one disk /dev/sda so on running the command, ls -l /dev/sda* I can get the major, minor numbers.
The highlighted values are the major and minor numbers for my /dev/sda disk.
Now, we write the following values to limit the read rate to 5 Mb/sec
$ echo "8:0 5242880" > /sys/fs/cgroup/blkio/myapp/blkio.throttle.read_bps_device
$ cat /sys/fs/cgroup/blkip/myapp/blkio.throttle.read_bps_device
Before running the controlled process, we must get an idea of the read speed without any throttling. Read the file that we created earlier, by running this command in the bottom-terminal.
$ dd if=~/test_if of=/dev/null
Step 5: You can see the real-time read rates in the top-terminal. After the file creation completes, you can also see the average rate, which is displayed by the dd command. Flush data to disk and drop all the caches, as shown earlier to avoid any ambiguity in the results.
To run this command under the throttling, we use cgexec
$ cgexec -g blkio:/myapp dd if=~/test_if of=/dev/null
where we provide the : name to the -g argument, in this case it is “blkio:myapp” The rates in the top-terminal should look something similar to this.
The interesting part of this is that we can take any application which does not have rate-limiting built-in, we can throttle it as needed.
The above plot is plotted while reading 2 files, whose processes belong to the same cgroup, with a read throttle limit of 50 Mb/sec. As you can see initially, the read-rate jumps to maximum, but as soon as the 2nd read starts, it comes in equilibrium and a total of 50MB/s, as expected. Once the read for “file-abc” ends, the rate jumps to achieve the maxima again.
You can change the rate in real time by echoing new values in the blkio.throttle files. Kernel will update the configurations automatically.
Example 2: We follow similar steps to create a memory throttled application. I’ll skip the explanation since most of it is same, and directly jump to the commands.
Step 1 : I have created a simple c-program that allocates 1MB in each iteration and run for a total of 50 iterations, allocating a total of 50 MB.
// a simple c-program that allocates 1MB in each
// iteration and run for a total of 50 iterations,
// allocating a total of 50 MB
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
int i;
char *p;
for (i = 0; i < 50; ++i)
{
// Allocate 1 MB each time.
if ((p = malloc(1<<20)) == NULL)
{
printf("Malloc failed at %d MB\n", i);
return 0;
}
memset(p, 0, (1<<20));
printf("Allocated %d to %d MB\n", i, i+1);
}
printf("Done!\n");
return 0;
}
$ sudo su # Switch to root for the rest of the commands
$ cgcreate -g memory:myapp_mem OR mkdir /sys/fs/cgroup/memory/myapp_mem
$ cd /sys/fs/cgroup/memory/myapp_mem
$ lscgroup # To check if the group was created successfully.
Now, the format for throttling config for memory can be obtained from the kernel documentation.(Link in references)
$ echo "5242880" > memory.limit_in_bytes
Before running the code, we need to disable swap. If the program cannot obtain memory from RAM (since we have limited), it will try to allocate memory on swap, which is not desirable in our case.
$ sudo swapoff -a # Disable swap
Swap status must be similar to the one shown above.
$ gcc mem_limit.c -o mem_limit
First, run the code without any memory limits,
$ ./mem_limit
Now, compare its output when run from within the controlled cgroup,
$ cgexec -g memory:myapp_mem /root/mem_limit
You could check various resource accounting information like current memory usage, maximum memory used, limit of on memory etc from,
$ cat memory.usage_in_bytes
$ cat memory.max_usage_in_bytes
$ cat memory.limit_in_bytes
There are more parameters that you can explore such as, memory.failcnt, memory.kmem.* and memory.kmem.tcp.* The more you read the documentation, the better will be your understanding.
We can extend this method and create throttled applications. This method was created a long time ago, but it is recently that it has been widely used in numerous applications. Virtual machines, containers etc use this to enforce resource limits. The purpose of understand cgroups was to understand how actually resource throttling is done in containers. Next topic to explore is containers. We’ll talk about it in details in next article.
References:
https://www.kernel.org/doc/Documentation/cgroup-v1/
https://www.kernel.org/doc/Documentation/cgroup-v1/blkio-controller.txt
https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/6/html/Resource_Management_Guide/ch-Subsystems_and_Tunable_Parameters.html
https://lwn.net/Articles/604609/
https://help.ubuntu.com/lts/serverguide/cgroups.html
https://www.youtube.com/watch?v=sK5i-N34im8 A very good presentation by docker team. This video will act as the bridge between this article and the next article. I’ll refer to it once again at the beginning of the next article. It is quite handy in understanding namespaces and cgroups.
About the Author: Pinkesh Badjatiya hails from IIIT Hyderabad. He is a geek at heart with ample projects worth looking for. His project work can be seen here. If you also wish to showcase your blog here, please see GBlog for guest blog writing on GeeksforGeeks.
mail1
sweetyty
surindertarika1234
virtualization
GBlog
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
DSA Sheet by Love Babbar
GEEK-O-LYMPICS 2022 - May The Geeks Force Be With You!
Geek Streak - 24 Days POTD Challenge
What is Hashing | A Complete Tutorial
GeeksforGeeks Jobathon - Are You Ready For This Hiring Challenge?
GeeksforGeeks Job-A-Thon Exclusive - Hiring Challenge For Amazon Alexa
Roadmap to Learn JavaScript For Beginners
How To Switch From A Service-Based To A Product-Based Company?
What is the Role of Fuzzy Logic in Algorithmic Trading?
What is Data Structure: Types, Classifications and Applications
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n05 Nov, 2021"
},
{
"code": null,
"e": 383,
"s": 54,
"text": "In Linux Virtualization – Chroot Jail article, we discussed about kernel namespaces and process jailing. To understand this article, you may not need to read the earlier one, but I strongly suggest that you go through it once before diving into resource throttling. It should help tremendously in understanding what’s going on. "
},
{
"code": null,
"e": 402,
"s": 383,
"text": "What are cgroups? "
},
{
"code": null,
"e": 768,
"s": 402,
"text": "cgroups (abbreviated from control groups) is a Linux kernel feature that limits, accounts for, and isolates the resource usage (CPU, memory, disk I/O, network, etc.) of a collection of processes. This feature was originally developed by 2 engineers from Google, under the name “process containers” but later merged in the Linux kernel mainline with name “cgroups”. "
},
{
"code": null,
"e": 789,
"s": 768,
"text": "Why is it required? "
},
{
"code": null,
"e": 1034,
"s": 789,
"text": "One of the design goals of cgroups is to provide a unified interface to many different use cases, from controlling single processes (by using nice, for example) to whole operating system-level virtualization. In simple words, cgroups provides: "
},
{
"code": null,
"e": 1155,
"s": 1034,
"text": "Resource limiting: Groups can be set to not exceed a configured memory limit, which also includes the file system cache."
},
{
"code": null,
"e": 1250,
"s": 1155,
"text": "Prioritization – Some groups may get a larger share of CPU utilization or disk I/O throughput."
},
{
"code": null,
"e": 1352,
"s": 1250,
"text": "Accounting – measures a group’s resource usage, which may be used, for example, for billing purposes."
},
{
"code": null,
"e": 1428,
"s": 1352,
"text": "Control – freezing groups of processes, their checkpointing and restarting."
},
{
"code": null,
"e": 1472,
"s": 1428,
"text": "How are they used, directly or indirectly? "
},
{
"code": null,
"e": 1519,
"s": 1472,
"text": "Control groups can be used in multiple ways: "
},
{
"code": null,
"e": 2017,
"s": 1519,
"text": "By accessing the cgroup virtual file system manually.By creating and managing groups on the fly using tools like cgcreate, cgexec, and cgclassify (from libcgroup).Through the “rules engine daemon” that can automatically move processes of certain users, groups, or commands to cgroups as specified in its configuration.Indirectly through other software that uses cgroups, such as Docker, Linux Containers (LXC) virtualization, libvirt, systemd, Open Grid Scheduler/Grid Engine, and Google’s lmctfy."
},
{
"code": null,
"e": 2071,
"s": 2017,
"text": "By accessing the cgroup virtual file system manually."
},
{
"code": null,
"e": 2182,
"s": 2071,
"text": "By creating and managing groups on the fly using tools like cgcreate, cgexec, and cgclassify (from libcgroup)."
},
{
"code": null,
"e": 2338,
"s": 2182,
"text": "Through the “rules engine daemon” that can automatically move processes of certain users, groups, or commands to cgroups as specified in its configuration."
},
{
"code": null,
"e": 2518,
"s": 2338,
"text": "Indirectly through other software that uses cgroups, such as Docker, Linux Containers (LXC) virtualization, libvirt, systemd, Open Grid Scheduler/Grid Engine, and Google’s lmctfy."
},
{
"code": null,
"e": 2754,
"s": 2518,
"text": "You might be surprised but this silent daemon makes up a substantial part of your online experience as quite a bunch of websites use containers/virtualization to host multiple servers or websites, including NetFlix, heruko and reddit. "
},
{
"code": null,
"e": 2898,
"s": 2754,
"text": "Installing cgroups: Some Linux versions come pre-installed with cgroups. To check if they are already installed/mounted, check the output of: "
},
{
"code": null,
"e": 2923,
"s": 2898,
"text": "$ mount | grep \"^cgroup\""
},
{
"code": null,
"e": 3268,
"s": 2923,
"text": "If you see files mounted on /sys/fs/cgroup/ then you can jump to the next topic directly to skip the installation part. The 2nd command installs the cgroup-tools which makes it easier to control and monitor control groups. We would be using the commands from the same in this tutorial. We will use the iotop utility to monitor disk I/O rates. "
},
{
"code": null,
"e": 3402,
"s": 3268,
"text": "$ sudo apt-get install cgroup-bin cgroup-lite libcgroup1 cgroup-lite\n$ sudo apt-get install cgroup-tools\n$ sudo apt-get install iotop"
},
{
"code": null,
"e": 3505,
"s": 3402,
"text": "If you installed the cgroups but cannot see them mounted at /sys/fs/cgroup, then use these commands, "
},
{
"code": null,
"e": 3631,
"s": 3505,
"text": "$ mount -t tmpfs cgroup_root /sys/fs/cgroup\n$ mkdir /sys/fs/cgroup/blkio\n$ mount -t cgroup -o blkio none /sys/fs/cgroup/blkio"
},
{
"code": null,
"e": 3850,
"s": 3631,
"text": "Example 1: We will create a disk-controlled group so that we may run any process with a finite amount of disk read/writes available. i.e. we want to throttle reads and writes done by a process or a group of processes. "
},
{
"code": null,
"e": 4167,
"s": 3850,
"text": "Step 1: To create a cgroup simply create a directory in /sys/fs/cgroup or if you have a cgroup-tools setup, then we can use them, in the appropriate directory for the subsystem. The kernel automatically fills the cgroup’s directory with the settings file nodes. Though, it’s recommended to use the cgroup-tools API, "
},
{
"code": null,
"e": 4307,
"s": 4167,
"text": "# Switch to root for the rest of the commands\n$ sudo su \n$ cgcreate -g blkio:myapp OR mkdir /sys/fs/cgroup/blkio/myapp"
},
{
"code": null,
"e": 4675,
"s": 4307,
"text": "This command will create a sub-group “myapp” under the “blkio” system. The Block I/O (blkio) subsystem controls and monitors access to I/O on block devices by tasks in cgroups. Writing values to these files provides controlled access to various resources. You can check if your group is created, by running the command, lscgroup, which lists all the control groups. "
},
{
"code": null,
"e": 4719,
"s": 4675,
"text": "$ lscgroup | grep blkio:/myapp\nblkio:/myapp"
},
{
"code": null,
"e": 4974,
"s": 4719,
"text": "Important: These files are not normal files on disk. These are pseudo files and are used directly by the kernel to read and modify the configuration. Do not open them in a text editor and try to save them. Always use the “echo” command to write to them. "
},
{
"code": null,
"e": 5228,
"s": 4974,
"text": "Before diving into easy stuff, let’s look at the directory structure of the newly created group. Here are some of the important files that we will need for this tutorial to understand how cgroup works. (Most important ones are highlighted in the image) "
},
{
"code": null,
"e": 5405,
"s": 5228,
"text": "Step 2: We create 2 terminal and place them one below the other. Become root user in both the terminals. In the top-terminal we run the iotop utility to monitor the disk I/O, "
},
{
"code": null,
"e": 5427,
"s": 5405,
"text": "$ sudo su\n$ iotop -o "
},
{
"code": null,
"e": 5518,
"s": 5427,
"text": "While on the below terminal, we create a temporary file of 512 MB using the “dd” command "
},
{
"code": null,
"e": 5576,
"s": 5518,
"text": "$ sudo su\n$ dd if=/dev/zero of=~/test_if bs=1M count=512 "
},
{
"code": null,
"e": 5857,
"s": 5576,
"text": "In the dd command, “if” represents the input file, “of” is the output file, “bs” is the block size and “count” is the no of times it writes the block. Once the command finishes, ~/temp_if is created with size 512 MB. You can see the realtime I/O rates on the top-terminal window. "
},
{
"code": null,
"e": 6049,
"s": 5857,
"text": "Step 3: Now for our next experiment, we need to make sure that we have flushed all the file system buffers to disk and dropped all the caches so that they do not interfere with our results. "
},
{
"code": null,
"e": 6113,
"s": 6049,
"text": "$ free -m\n$ sync\n$ echo 3 > /proc/sys/vm/drop_caches\n$ free -m "
},
{
"code": null,
"e": 6190,
"s": 6113,
"text": "Now, you should see a increase in the available RAM and reduced cache size. "
},
{
"code": null,
"e": 6476,
"s": 6190,
"text": "Step 3: Now to setup throttling limits, we use the following commands. Say, we would like to set a read/write limit of 5 MB for a process. From the kernel documentation, you’ll find that, blkio.throttle.read_bps_device and blkio.throttle.write_bps_device accept entries of the format, "
},
{
"code": null,
"e": 6512,
"s": 6476,
"text": "<major>:<minor> <rates_per_second> "
},
{
"code": null,
"e": 6693,
"s": 6512,
"text": "where, major and minor are the values for a particular device, which we want to rate limit. rates_per_second is the maximum rate that can be achieved by the process of that group. "
},
{
"code": null,
"e": 6873,
"s": 6693,
"text": "Getting the major and minor numbers is easy. The machine i am working on only has one disk /dev/sda so on running the command, ls -l /dev/sda* I can get the major, minor numbers. "
},
{
"code": null,
"e": 6951,
"s": 6873,
"text": "The highlighted values are the major and minor numbers for my /dev/sda disk. "
},
{
"code": null,
"e": 7023,
"s": 6951,
"text": "Now, we write the following values to limit the read rate to 5 Mb/sec "
},
{
"code": null,
"e": 7169,
"s": 7023,
"text": "$ echo \"8:0 5242880\" > /sys/fs/cgroup/blkio/myapp/blkio.throttle.read_bps_device\n$ cat /sys/fs/cgroup/blkip/myapp/blkio.throttle.read_bps_device "
},
{
"code": null,
"e": 7359,
"s": 7169,
"text": "Before running the controlled process, we must get an idea of the read speed without any throttling. Read the file that we created earlier, by running this command in the bottom-terminal. "
},
{
"code": null,
"e": 7391,
"s": 7359,
"text": "$ dd if=~/test_if of=/dev/null "
},
{
"code": null,
"e": 7666,
"s": 7391,
"text": "Step 5: You can see the real-time read rates in the top-terminal. After the file creation completes, you can also see the average rate, which is displayed by the dd command. Flush data to disk and drop all the caches, as shown earlier to avoid any ambiguity in the results. "
},
{
"code": null,
"e": 7724,
"s": 7666,
"text": "To run this command under the throttling, we use cgexec "
},
{
"code": null,
"e": 7779,
"s": 7724,
"text": "$ cgexec -g blkio:/myapp dd if=~/test_if of=/dev/null "
},
{
"code": null,
"e": 7930,
"s": 7779,
"text": "where we provide the : name to the -g argument, in this case it is “blkio:myapp” The rates in the top-terminal should look something similar to this. "
},
{
"code": null,
"e": 8071,
"s": 7930,
"text": "The interesting part of this is that we can take any application which does not have rate-limiting built-in, we can throttle it as needed. "
},
{
"code": null,
"e": 8438,
"s": 8071,
"text": "The above plot is plotted while reading 2 files, whose processes belong to the same cgroup, with a read throttle limit of 50 Mb/sec. As you can see initially, the read-rate jumps to maximum, but as soon as the 2nd read starts, it comes in equilibrium and a total of 50MB/s, as expected. Once the read for “file-abc” ends, the rate jumps to achieve the maxima again. "
},
{
"code": null,
"e": 8580,
"s": 8438,
"text": "You can change the rate in real time by echoing new values in the blkio.throttle files. Kernel will update the configurations automatically. "
},
{
"code": null,
"e": 8745,
"s": 8580,
"text": "Example 2: We follow similar steps to create a memory throttled application. I’ll skip the explanation since most of it is same, and directly jump to the commands. "
},
{
"code": null,
"e": 8893,
"s": 8745,
"text": "Step 1 : I have created a simple c-program that allocates 1MB in each iteration and run for a total of 50 iterations, allocating a total of 50 MB. "
},
{
"code": null,
"e": 9458,
"s": 8893,
"text": "// a simple c-program that allocates 1MB in each\n// iteration and run for a total of 50 iterations,\n// allocating a total of 50 MB\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nint main(void)\n{\n int i;\n char *p;\n for (i = 0; i < 50; ++i)\n {\n // Allocate 1 MB each time.\n if ((p = malloc(1<<20)) == NULL)\n {\n printf(\"Malloc failed at %d MB\\n\", i);\n return 0;\n }\n memset(p, 0, (1<<20));\n printf(\"Allocated %d to %d MB\\n\", i, i+1);\n }\n\n printf(\"Done!\\n\");\n return 0;\n}"
},
{
"code": null,
"e": 9702,
"s": 9458,
"text": "$ sudo su # Switch to root for the rest of the commands\n$ cgcreate -g memory:myapp_mem OR mkdir /sys/fs/cgroup/memory/myapp_mem\n$ cd /sys/fs/cgroup/memory/myapp_mem\n$ lscgroup # To check if the group was created successfully. "
},
{
"code": null,
"e": 9820,
"s": 9702,
"text": "Now, the format for throttling config for memory can be obtained from the kernel documentation.(Link in references) "
},
{
"code": null,
"e": 9862,
"s": 9820,
"text": "$ echo \"5242880\" > memory.limit_in_bytes "
},
{
"code": null,
"e": 10060,
"s": 9862,
"text": "Before running the code, we need to disable swap. If the program cannot obtain memory from RAM (since we have limited), it will try to allocate memory on swap, which is not desirable in our case. "
},
{
"code": null,
"e": 10094,
"s": 10060,
"text": "$ sudo swapoff -a # Disable swap "
},
{
"code": null,
"e": 10147,
"s": 10094,
"text": "Swap status must be similar to the one shown above. "
},
{
"code": null,
"e": 10179,
"s": 10147,
"text": "$ gcc mem_limit.c -o mem_limit "
},
{
"code": null,
"e": 10227,
"s": 10179,
"text": "First, run the code without any memory limits, "
},
{
"code": null,
"e": 10242,
"s": 10227,
"text": "$ ./mem_limit "
},
{
"code": null,
"e": 10311,
"s": 10242,
"text": "Now, compare its output when run from within the controlled cgroup, "
},
{
"code": null,
"e": 10357,
"s": 10311,
"text": "$ cgexec -g memory:myapp_mem /root/mem_limit "
},
{
"code": null,
"e": 10491,
"s": 10357,
"text": "You could check various resource accounting information like current memory usage, maximum memory used, limit of on memory etc from, "
},
{
"code": null,
"e": 10580,
"s": 10491,
"text": "$ cat memory.usage_in_bytes\n$ cat memory.max_usage_in_bytes\n$ cat memory.limit_in_bytes "
},
{
"code": null,
"e": 10765,
"s": 10580,
"text": "There are more parameters that you can explore such as, memory.failcnt, memory.kmem.* and memory.kmem.tcp.* The more you read the documentation, the better will be your understanding. "
},
{
"code": null,
"e": 11205,
"s": 10765,
"text": "We can extend this method and create throttled applications. This method was created a long time ago, but it is recently that it has been widely used in numerous applications. Virtual machines, containers etc use this to enforce resource limits. The purpose of understand cgroups was to understand how actually resource throttling is done in containers. Next topic to explore is containers. We’ll talk about it in details in next article. "
},
{
"code": null,
"e": 11219,
"s": 11205,
"text": "References: "
},
{
"code": null,
"e": 11271,
"s": 11219,
"text": "https://www.kernel.org/doc/Documentation/cgroup-v1/"
},
{
"code": null,
"e": 11343,
"s": 11271,
"text": "https://www.kernel.org/doc/Documentation/cgroup-v1/blkio-controller.txt"
},
{
"code": null,
"e": 11489,
"s": 11343,
"text": "https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/6/html/Resource_Management_Guide/ch-Subsystems_and_Tunable_Parameters.html"
},
{
"code": null,
"e": 11522,
"s": 11489,
"text": "https://lwn.net/Articles/604609/"
},
{
"code": null,
"e": 11575,
"s": 11522,
"text": "https://help.ubuntu.com/lts/serverguide/cgroups.html"
},
{
"code": null,
"e": 11862,
"s": 11575,
"text": "https://www.youtube.com/watch?v=sK5i-N34im8 A very good presentation by docker team. This video will act as the bridge between this article and the next article. I’ll refer to it once again at the beginning of the next article. It is quite handy in understanding namespaces and cgroups."
},
{
"code": null,
"e": 12125,
"s": 11862,
"text": "About the Author: Pinkesh Badjatiya hails from IIIT Hyderabad. He is a geek at heart with ample projects worth looking for. His project work can be seen here. If you also wish to showcase your blog here, please see GBlog for guest blog writing on GeeksforGeeks. "
},
{
"code": null,
"e": 12131,
"s": 12125,
"text": "mail1"
},
{
"code": null,
"e": 12140,
"s": 12131,
"text": "sweetyty"
},
{
"code": null,
"e": 12159,
"s": 12140,
"text": "surindertarika1234"
},
{
"code": null,
"e": 12174,
"s": 12159,
"text": "virtualization"
},
{
"code": null,
"e": 12180,
"s": 12174,
"text": "GBlog"
},
{
"code": null,
"e": 12278,
"s": 12180,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 12303,
"s": 12278,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 12358,
"s": 12303,
"text": "GEEK-O-LYMPICS 2022 - May The Geeks Force Be With You!"
},
{
"code": null,
"e": 12395,
"s": 12358,
"text": "Geek Streak - 24 Days POTD Challenge"
},
{
"code": null,
"e": 12433,
"s": 12395,
"text": "What is Hashing | A Complete Tutorial"
},
{
"code": null,
"e": 12499,
"s": 12433,
"text": "GeeksforGeeks Jobathon - Are You Ready For This Hiring Challenge?"
},
{
"code": null,
"e": 12570,
"s": 12499,
"text": "GeeksforGeeks Job-A-Thon Exclusive - Hiring Challenge For Amazon Alexa"
},
{
"code": null,
"e": 12612,
"s": 12570,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 12675,
"s": 12612,
"text": "How To Switch From A Service-Based To A Product-Based Company?"
},
{
"code": null,
"e": 12731,
"s": 12675,
"text": "What is the Role of Fuzzy Logic in Algorithmic Trading?"
}
] |
Puppet - SSL Sign Certificate Setup
|
When the Puppet agent software runs for the first time on any Puppet node, it generates a certificate and sends the certificate signing request to the Puppet master. Before the Puppet server is able to communicate and control the agent nodes, it must sign that particular agent node’s certificate. In the following sections, we will describe how to sign and check for the signing request.
On the Puppet master, run the following command to see all unsigned certificate requests.
$ sudo /opt/puppetlabs/bin/puppet cert list
As we have just set up a new agent node, we will see one request for approval. Following will be the output.
"Brcleprod004.brcl.com" (SHA259)
15:90:C2:FB:ED:69:A4:F7:B1:87:0B:BF:F7:ll:
B5:1C:33:F7:76:67:F3:F6:45:AE:07:4B:F 6:E3:ss:04:11:8d
It does not contain any + (sign) in the beginning, which indicates that the certificate is still not signed.
In order to sign the new certificate request which was generated when the Puppet agent run took place on the new node, the Puppet cert sign command would be used, with the host name of the certificate, which was generated by the newly configured node that needs to be signed. As we have Brcleprod004.brcl.com’s certificate, we will use the following command.
$ sudo /opt/puppetlabs/bin/puppet cert sign Brcleprod004.brcl.com
Following will be the output.
Notice: Signed certificate request for Brcle004.brcl.com
Notice: Removing file Puppet::SSL::CertificateRequest Brcle004.brcl.com at
'/etc/puppetlabs/puppet/ssl/ca/requests/Brcle004.brcl.com.pem'
The puppet sever can now communicate to the node, where the sign certificate belongs.
$ sudo /opt/puppetlabs/bin/puppet cert sign --all
There are conditions on configuration of kernel rebuild when it needs to removing the host from the setup and adding it again. These are those conditions which cannot be managed by the Puppet itself. It could be done using the following command.
$ sudo /opt/puppetlabs/bin/puppet cert clean hostname
The following command will generate a list of signed certificates with + (sign) which indicates that the request is approved.
$ sudo /opt/puppetlabs/bin/puppet cert list --all
Following will be its output.
+ "puppet" (SHA256) 5A:71:E6:06:D8:0F:44:4D:70:F0:
BE:51:72:15:97:68:D9:67:16:41:B0:38:9A:F2:B2:6C:B
B:33:7E:0F:D4:53 (alt names: "DNS:puppet", "DNS:Brcle004.nyc3.example.com")
+ "Brcle004.brcl.com" (SHA259) F5:DC:68:24:63:E6:F1:9E:C5:FE:F5:
1A:90:93:DF:19:F2:28:8B:D7:BD:D2:6A:83:07:BA:F E:24:11:24:54:6A
+ " Brcle004.brcl.com" (SHA259) CB:CB:CA:48:E0:DF:06:6A:7D:75:E6:CB:22:BE:35:5A:9A:B3
Once the above is done, we have our infrastructure ready in which the Puppet master is now capable of managing newly added nodes.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2562,
"s": 2173,
"text": "When the Puppet agent software runs for the first time on any Puppet node, it generates a certificate and sends the certificate signing request to the Puppet master. Before the Puppet server is able to communicate and control the agent nodes, it must sign that particular agent node’s certificate. In the following sections, we will describe how to sign and check for the signing request."
},
{
"code": null,
"e": 2652,
"s": 2562,
"text": "On the Puppet master, run the following command to see all unsigned certificate requests."
},
{
"code": null,
"e": 2697,
"s": 2652,
"text": "$ sudo /opt/puppetlabs/bin/puppet cert list\n"
},
{
"code": null,
"e": 2806,
"s": 2697,
"text": "As we have just set up a new agent node, we will see one request for approval. Following will be the output."
},
{
"code": null,
"e": 2940,
"s": 2806,
"text": "\"Brcleprod004.brcl.com\" (SHA259) \n15:90:C2:FB:ED:69:A4:F7:B1:87:0B:BF:F7:ll:\nB5:1C:33:F7:76:67:F3:F6:45:AE:07:4B:F 6:E3:ss:04:11:8d \n"
},
{
"code": null,
"e": 3049,
"s": 2940,
"text": "It does not contain any + (sign) in the beginning, which indicates that the certificate is still not signed."
},
{
"code": null,
"e": 3408,
"s": 3049,
"text": "In order to sign the new certificate request which was generated when the Puppet agent run took place on the new node, the Puppet cert sign command would be used, with the host name of the certificate, which was generated by the newly configured node that needs to be signed. As we have Brcleprod004.brcl.com’s certificate, we will use the following command."
},
{
"code": null,
"e": 3476,
"s": 3408,
"text": "$ sudo /opt/puppetlabs/bin/puppet cert sign Brcleprod004.brcl.com \n"
},
{
"code": null,
"e": 3506,
"s": 3476,
"text": "Following will be the output."
},
{
"code": null,
"e": 3705,
"s": 3506,
"text": "Notice: Signed certificate request for Brcle004.brcl.com \nNotice: Removing file Puppet::SSL::CertificateRequest Brcle004.brcl.com at \n'/etc/puppetlabs/puppet/ssl/ca/requests/Brcle004.brcl.com.pem' \n"
},
{
"code": null,
"e": 3791,
"s": 3705,
"text": "The puppet sever can now communicate to the node, where the sign certificate belongs."
},
{
"code": null,
"e": 3843,
"s": 3791,
"text": "$ sudo /opt/puppetlabs/bin/puppet cert sign --all \n"
},
{
"code": null,
"e": 4089,
"s": 3843,
"text": "There are conditions on configuration of kernel rebuild when it needs to removing the host from the setup and adding it again. These are those conditions which cannot be managed by the Puppet itself. It could be done using the following command."
},
{
"code": null,
"e": 4145,
"s": 4089,
"text": "$ sudo /opt/puppetlabs/bin/puppet cert clean hostname \n"
},
{
"code": null,
"e": 4271,
"s": 4145,
"text": "The following command will generate a list of signed certificates with + (sign) which indicates that the request is approved."
},
{
"code": null,
"e": 4322,
"s": 4271,
"text": "$ sudo /opt/puppetlabs/bin/puppet cert list --all\n"
},
{
"code": null,
"e": 4352,
"s": 4322,
"text": "Following will be its output."
},
{
"code": null,
"e": 4752,
"s": 4352,
"text": "+ \"puppet\" (SHA256) 5A:71:E6:06:D8:0F:44:4D:70:F0:\nBE:51:72:15:97:68:D9:67:16:41:B0:38:9A:F2:B2:6C:B \nB:33:7E:0F:D4:53 (alt names: \"DNS:puppet\", \"DNS:Brcle004.nyc3.example.com\") \n\n+ \"Brcle004.brcl.com\" (SHA259) F5:DC:68:24:63:E6:F1:9E:C5:FE:F5:\n1A:90:93:DF:19:F2:28:8B:D7:BD:D2:6A:83:07:BA:F E:24:11:24:54:6A \n\n+ \" Brcle004.brcl.com\" (SHA259) CB:CB:CA:48:E0:DF:06:6A:7D:75:E6:CB:22:BE:35:5A:9A:B3 \n"
},
{
"code": null,
"e": 4882,
"s": 4752,
"text": "Once the above is done, we have our infrastructure ready in which the Puppet master is now capable of managing newly added nodes."
},
{
"code": null,
"e": 4889,
"s": 4882,
"text": " Print"
},
{
"code": null,
"e": 4900,
"s": 4889,
"text": " Add Notes"
}
] |
JavaScript Quicksort recursive
|
We are required to write a JavaScript function that takes in an array of Numbers. The function should apply the algorithm of quicksort to sort the array either in increasing or decreasing order.
Quicksort follows the below steps −
Step 1 − Make any element as the pivot (preferably first or last, but any element can be the pivot)
Step 2 − Partition the array on the basis of pivot
Step 3 − Apply a quick sort on the left partition recursively
Step 4 − Apply a quick sort on the right partition recursively
The average and best case time complexity of QuickSort are O(nlogn) whereas in worst cases, it can slow up to O(n^2).
The code for this will be −
const arr = [5,3,7,6,2,9];
const swap = (arr, leftIndex, rightIndex) => {
let temp = arr[leftIndex];
arr[leftIndex] = arr[rightIndex];
arr[rightIndex] = temp;
};
const partition = (arr, left, right) => {
let pivot = arr[Math.floor((right + left) / 2)];
let i = left;
let j = right;
while (i <= j) {
while (arr[i] < pivot) {
i++;
};
while (arr[j] > pivot) {
j--;
};
if (i <= j) {
swap(arr, i, j); //sawpping two elements
i++;
j--;
};
};
return i;
}
const quickSort = (arr, left = 0, right = arr.length - 1) => {
let index;
if (arr.length > 1) {
index = partition(arr, left, right);
if (left < index - 1) {
quickSort(arr, left, index - 1);
};
if (index < right) {
quickSort(arr, index, right);
};
}
return arr;
}
let sortedArray = quickSort(arr);
console.log(sortedArray);
And the output in the console will be −
[ 2, 3, 5, 6, 7, 9 ]
|
[
{
"code": null,
"e": 1257,
"s": 1062,
"text": "We are required to write a JavaScript function that takes in an array of Numbers. The function should apply the algorithm of quicksort to sort the array either in increasing or decreasing order."
},
{
"code": null,
"e": 1293,
"s": 1257,
"text": "Quicksort follows the below steps −"
},
{
"code": null,
"e": 1393,
"s": 1293,
"text": "Step 1 − Make any element as the pivot (preferably first or last, but any element can be the pivot)"
},
{
"code": null,
"e": 1444,
"s": 1393,
"text": "Step 2 − Partition the array on the basis of pivot"
},
{
"code": null,
"e": 1506,
"s": 1444,
"text": "Step 3 − Apply a quick sort on the left partition recursively"
},
{
"code": null,
"e": 1569,
"s": 1506,
"text": "Step 4 − Apply a quick sort on the right partition recursively"
},
{
"code": null,
"e": 1687,
"s": 1569,
"text": "The average and best case time complexity of QuickSort are O(nlogn) whereas in worst cases, it can slow up to O(n^2)."
},
{
"code": null,
"e": 1715,
"s": 1687,
"text": "The code for this will be −"
},
{
"code": null,
"e": 2654,
"s": 1715,
"text": "const arr = [5,3,7,6,2,9];\nconst swap = (arr, leftIndex, rightIndex) => {\n let temp = arr[leftIndex];\n arr[leftIndex] = arr[rightIndex];\n arr[rightIndex] = temp;\n};\nconst partition = (arr, left, right) => {\n let pivot = arr[Math.floor((right + left) / 2)];\n let i = left;\n let j = right;\n while (i <= j) {\n while (arr[i] < pivot) {\n i++;\n };\n while (arr[j] > pivot) {\n j--;\n };\n if (i <= j) {\n swap(arr, i, j); //sawpping two elements\n i++;\n j--;\n };\n };\n return i;\n}\nconst quickSort = (arr, left = 0, right = arr.length - 1) => {\n let index;\n if (arr.length > 1) {\n index = partition(arr, left, right);\n if (left < index - 1) {\n quickSort(arr, left, index - 1);\n };\n if (index < right) {\n quickSort(arr, index, right);\n };\n }\n return arr;\n}\nlet sortedArray = quickSort(arr);\nconsole.log(sortedArray);"
},
{
"code": null,
"e": 2694,
"s": 2654,
"text": "And the output in the console will be −"
},
{
"code": null,
"e": 2715,
"s": 2694,
"text": "[ 2, 3, 5, 6, 7, 9 ]"
}
] |
How to load an ImageView by URL on Android using Picasso?
|
This example demonstrates about how do I load an ImageView on Android using Picasso.
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 − Gradle Scripts from Project → Click build.gradle (Module: app) → add dependency − Implementation ‘com.squareup.picasso−Picasso:2.5.2 and click “Sync now”.
Step 3 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="16dp"
android:orientation="vertical"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Load ImageView by URL"
android:textStyle="bold"
android:textColor="@color/colorPrimary"
android:textSize="20sp" />
<ImageView
android:id="@+id/image_view"
android:layout_width="fill_parent"
android:layout_height="300dp"
android:layout_marginTop="16dp" />
<TextView
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:textSize="24sp"
android:gravity="center|bottom"
android:textStyle="bold" />
</LinearLayout>
Step 4 − Add the following code to src/MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;
import com.squareup.picasso.Picasso;
public class MainActivity extends AppCompatActivity {
private ImageView imageView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView imageView = findViewById(R.id.image_view);
String url = "https://images.pexels.com/photos/814499/pexels-photo814499.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500";
Picasso.with(this).load(url).into(imageView);
}
}
Step 5 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher"
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": 1147,
"s": 1062,
"text": "This example demonstrates about how do I load an ImageView on Android using Picasso."
},
{
"code": null,
"e": 1276,
"s": 1147,
"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": 1440,
"s": 1276,
"text": "Step 2 − Gradle Scripts from Project → Click build.gradle (Module: app) → add dependency − Implementation ‘com.squareup.picasso−Picasso:2.5.2 and click “Sync now”."
},
{
"code": null,
"e": 1505,
"s": 1440,
"text": "Step 3 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2397,
"s": 1505,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:layout_margin=\"16dp\"\n android:orientation=\"vertical\"/>\n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Load ImageView by URL\"\n android:textStyle=\"bold\"\n android:textColor=\"@color/colorPrimary\"\n android:textSize=\"20sp\" />\n <ImageView\n android:id=\"@+id/image_view\"\n android:layout_width=\"fill_parent\"\n android:layout_height=\"300dp\"\n android:layout_marginTop=\"16dp\" />\n <TextView\n android:layout_width=\"fill_parent\"\n android:layout_height=\"match_parent\"\n android:textSize=\"24sp\"\n android:gravity=\"center|bottom\"\n android:textStyle=\"bold\" />\n</LinearLayout>"
},
{
"code": null,
"e": 2454,
"s": 2397,
"text": "Step 4 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 3081,
"s": 2454,
"text": "import android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.widget.ImageView;\nimport com.squareup.picasso.Picasso;\npublic class MainActivity extends AppCompatActivity {\n private ImageView imageView;\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n ImageView imageView = findViewById(R.id.image_view);\n String url = \"https://images.pexels.com/photos/814499/pexels-photo814499.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500\";\n Picasso.with(this).load(url).into(imageView);\n }\n}"
},
{
"code": null,
"e": 3136,
"s": 3081,
"text": "Step 5 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 3866,
"s": 3136,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.sample\">\n <uses-permission android:name=\"android.permission.INTERNET\" />\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher\"\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": 4213,
"s": 3866,
"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": 4254,
"s": 4213,
"text": "Click here to download the project code."
}
] |
Java Examples - Create a temporary File
|
How to create a temporary file ?
This example shows how to create a temporary file using createTempFile() method of File class.
import java.io.*;
public class Main {
public static void main(String[] args) throws Exception {
File temp = File.createTempFile ("pattern", ".suffix");
temp.deleteOnExit();
BufferedWriter out = new BufferedWriter (new FileWriter(temp));
out.write("aString");
System.out.println("temporary file created:");
out.close();
}
}
The above code sample will produce the following result.
temporary file created:
The following is another sample example of create a temporary file in java
import java.io.File;
import java.io.IOException;
public class CreateTempFileExample {
public static void main(String[] args) {
try {
File f1 = File.createTempFile("temp-file-name", ".tmp");
System.out.println("Temp file : " + f1.getAbsolutePath());
} catch(IOException e) {
e.printStackTrace();
}
}
}
The above code sample will produce the following result.
Temp file : C:\Users\TUTORI~1\AppData\Local\Temp\temp-file-name3671918809488333932.tmp
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2101,
"s": 2068,
"text": "How to create a temporary file ?"
},
{
"code": null,
"e": 2196,
"s": 2101,
"text": "This example shows how to create a temporary file using createTempFile() method of File class."
},
{
"code": null,
"e": 2563,
"s": 2196,
"text": "import java.io.*;\n\npublic class Main {\n public static void main(String[] args) throws Exception {\n File temp = File.createTempFile (\"pattern\", \".suffix\");\n temp.deleteOnExit(); \n BufferedWriter out = new BufferedWriter (new FileWriter(temp));\n out.write(\"aString\");\n System.out.println(\"temporary file created:\");\n out.close();\n }\n}"
},
{
"code": null,
"e": 2620,
"s": 2563,
"text": "The above code sample will produce the following result."
},
{
"code": null,
"e": 2645,
"s": 2620,
"text": "temporary file created:\n"
},
{
"code": null,
"e": 2720,
"s": 2645,
"text": "The following is another sample example of create a temporary file in java"
},
{
"code": null,
"e": 3077,
"s": 2720,
"text": "import java.io.File;\nimport java.io.IOException;\n\npublic class CreateTempFileExample { \n public static void main(String[] args) { \n try { \n File f1 = File.createTempFile(\"temp-file-name\", \".tmp\");\n \t System.out.println(\"Temp file : \" + f1.getAbsolutePath());\n } catch(IOException e) { \n e.printStackTrace();\n } \n }\n}"
},
{
"code": null,
"e": 3134,
"s": 3077,
"text": "The above code sample will produce the following result."
},
{
"code": null,
"e": 3222,
"s": 3134,
"text": "Temp file : C:\\Users\\TUTORI~1\\AppData\\Local\\Temp\\temp-file-name3671918809488333932.tmp\n"
},
{
"code": null,
"e": 3229,
"s": 3222,
"text": " Print"
},
{
"code": null,
"e": 3240,
"s": 3229,
"text": " Add Notes"
}
] |
Java program to implement linear search
|
Linear search is a very simple search algorithm. In this type of search, a sequential search is done for all items one by one. Every item is checked and if a match is found then that particular item is returned, otherwise the search continues till the end of the data collection.
1.Get the length of the array.
2.Get the element to be searched store it in a variable named value.
3.Compare each element of the array with the variable value.
4.In case of a match print a message saying element found.
5.else, print a message saying element not found
Live Demo
public class LinearSearch {
public static void main(String args[]){
int array[] = {10, 20, 25, 63, 96, 57};
int size = array.length;
int value = 63;
for (int i=0 ;i< size-1; i++){
if(array[i]==value){
System.out.println("Element found index is :"+ i);
}else{
System.out.println("Element not found");
}
}
}
}
Element found index is :3
|
[
{
"code": null,
"e": 1342,
"s": 1062,
"text": "Linear search is a very simple search algorithm. In this type of search, a sequential search is done for all items one by one. Every item is checked and if a match is found then that particular item is returned, otherwise the search continues till the end of the data collection."
},
{
"code": null,
"e": 1611,
"s": 1342,
"text": "1.Get the length of the array.\n2.Get the element to be searched store it in a variable named value.\n3.Compare each element of the array with the variable value.\n4.In case of a match print a message saying element found.\n5.else, print a message saying element not found"
},
{
"code": null,
"e": 1621,
"s": 1611,
"text": "Live Demo"
},
{
"code": null,
"e": 2017,
"s": 1621,
"text": "public class LinearSearch {\n public static void main(String args[]){\n int array[] = {10, 20, 25, 63, 96, 57};\n int size = array.length;\n int value = 63;\n\n for (int i=0 ;i< size-1; i++){\n if(array[i]==value){\n System.out.println(\"Element found index is :\"+ i);\n }else{\n System.out.println(\"Element not found\");\n }\n }\n }\n}"
},
{
"code": null,
"e": 2043,
"s": 2017,
"text": "Element found index is :3"
}
] |
\widehat - Tex Command
|
\widehat - Used to create widehat symbol.
{ \widehat}
\widehat command draws widehat symbol.
\widehat a
a^
\widehat A
A^
\widehat AB
A^B
\widehat{AB}
AB^
\widehat a
a^
\widehat a
\widehat A
A^
\widehat A
\widehat AB
A^B
\widehat AB
\widehat{AB}
AB^
\widehat{AB}
14 Lectures
52 mins
Ashraf Said
11 Lectures
1 hours
Ashraf Said
9 Lectures
1 hours
Emenwa Global, Ejike IfeanyiChukwu
29 Lectures
2.5 hours
Mohammad Nauman
14 Lectures
1 hours
Daniel Stern
15 Lectures
47 mins
Nishant Kumar
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 8028,
"s": 7986,
"text": "\\widehat - Used to create widehat symbol."
},
{
"code": null,
"e": 8040,
"s": 8028,
"text": "{ \\widehat}"
},
{
"code": null,
"e": 8079,
"s": 8040,
"text": "\\widehat command draws widehat symbol."
},
{
"code": null,
"e": 8154,
"s": 8079,
"text": "\n\\widehat a\n\na^\n\n\n\\widehat A\n\nA^\n\n\n\\widehat AB\n\nA^B\n\n\n\\widehat{AB}\n\nAB^\n\n\n"
},
{
"code": null,
"e": 8171,
"s": 8154,
"text": "\\widehat a\n\na^\n\n"
},
{
"code": null,
"e": 8182,
"s": 8171,
"text": "\\widehat a"
},
{
"code": null,
"e": 8199,
"s": 8182,
"text": "\\widehat A\n\nA^\n\n"
},
{
"code": null,
"e": 8210,
"s": 8199,
"text": "\\widehat A"
},
{
"code": null,
"e": 8229,
"s": 8210,
"text": "\\widehat AB\n\nA^B\n\n"
},
{
"code": null,
"e": 8241,
"s": 8229,
"text": "\\widehat AB"
},
{
"code": null,
"e": 8261,
"s": 8241,
"text": "\\widehat{AB}\n\nAB^\n\n"
},
{
"code": null,
"e": 8274,
"s": 8261,
"text": "\\widehat{AB}"
},
{
"code": null,
"e": 8306,
"s": 8274,
"text": "\n 14 Lectures \n 52 mins\n"
},
{
"code": null,
"e": 8319,
"s": 8306,
"text": " Ashraf Said"
},
{
"code": null,
"e": 8352,
"s": 8319,
"text": "\n 11 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8365,
"s": 8352,
"text": " Ashraf Said"
},
{
"code": null,
"e": 8397,
"s": 8365,
"text": "\n 9 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8433,
"s": 8397,
"text": " Emenwa Global, Ejike IfeanyiChukwu"
},
{
"code": null,
"e": 8468,
"s": 8433,
"text": "\n 29 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 8485,
"s": 8468,
"text": " Mohammad Nauman"
},
{
"code": null,
"e": 8518,
"s": 8485,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8532,
"s": 8518,
"text": " Daniel Stern"
},
{
"code": null,
"e": 8564,
"s": 8532,
"text": "\n 15 Lectures \n 47 mins\n"
},
{
"code": null,
"e": 8579,
"s": 8564,
"text": " Nishant Kumar"
},
{
"code": null,
"e": 8586,
"s": 8579,
"text": " Print"
},
{
"code": null,
"e": 8597,
"s": 8586,
"text": " Add Notes"
}
] |
DAX Date & Time - DATEDIFF function
|
Returns the count of interval boundaries crossed between two dates.
DAX DATEDIFF function is new in Excel 2016.
DATEDIFF (<start_date>, <end_date>, <interval>)
start_date
A scalar datetime value.
end_date
A scalar datetime value.
interval
The interval to use when comparing the dates. The value can be one of the following −
SECOND
MINUTE
HOUR
DAY
WEEK
MONTH
QUARTER
YEAR
A whole number.
If start_date is larger than end_date, an error value is returned.
The values given to the parameter interval are constants and not strings. Hence, they should not be enclosed in double quotation marks.
= DATEDIFF (DATE (2016,1,1), DATE (2016,3,31), MONTH) returns 2.
= DATEDIFF (DATE (2016,1,1), DATE (2016,4,1), MONTH) returns 3.
= DATEDIFF (DATE (2016,1,1), DATE (2016,3,31), DAY) returns 90.
= DATEDIFF (DATE (2016,1,1), DATE (2016,3,31), HOUR) returns 2160.
= DATEDIFF (DATE (2016,1,1), DATE (2016,3,31), SECOND) returns 7776000.
53 Lectures
5.5 hours
Abhay Gadiya
24 Lectures
2 hours
Randy Minder
26 Lectures
4.5 hours
Randy Minder
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2069,
"s": 2001,
"text": "Returns the count of interval boundaries crossed between two dates."
},
{
"code": null,
"e": 2113,
"s": 2069,
"text": "DAX DATEDIFF function is new in Excel 2016."
},
{
"code": null,
"e": 2163,
"s": 2113,
"text": "DATEDIFF (<start_date>, <end_date>, <interval>) \n"
},
{
"code": null,
"e": 2174,
"s": 2163,
"text": "start_date"
},
{
"code": null,
"e": 2199,
"s": 2174,
"text": "A scalar datetime value."
},
{
"code": null,
"e": 2208,
"s": 2199,
"text": "end_date"
},
{
"code": null,
"e": 2233,
"s": 2208,
"text": "A scalar datetime value."
},
{
"code": null,
"e": 2242,
"s": 2233,
"text": "interval"
},
{
"code": null,
"e": 2328,
"s": 2242,
"text": "The interval to use when comparing the dates. The value can be one of the following −"
},
{
"code": null,
"e": 2335,
"s": 2328,
"text": "SECOND"
},
{
"code": null,
"e": 2342,
"s": 2335,
"text": "MINUTE"
},
{
"code": null,
"e": 2347,
"s": 2342,
"text": "HOUR"
},
{
"code": null,
"e": 2351,
"s": 2347,
"text": "DAY"
},
{
"code": null,
"e": 2356,
"s": 2351,
"text": "WEEK"
},
{
"code": null,
"e": 2362,
"s": 2356,
"text": "MONTH"
},
{
"code": null,
"e": 2370,
"s": 2362,
"text": "QUARTER"
},
{
"code": null,
"e": 2375,
"s": 2370,
"text": "YEAR"
},
{
"code": null,
"e": 2391,
"s": 2375,
"text": "A whole number."
},
{
"code": null,
"e": 2458,
"s": 2391,
"text": "If start_date is larger than end_date, an error value is returned."
},
{
"code": null,
"e": 2594,
"s": 2458,
"text": "The values given to the parameter interval are constants and not strings. Hence, they should not be enclosed in double quotation marks."
},
{
"code": null,
"e": 2931,
"s": 2594,
"text": "= DATEDIFF (DATE (2016,1,1), DATE (2016,3,31), MONTH) returns 2. \n= DATEDIFF (DATE (2016,1,1), DATE (2016,4,1), MONTH) returns 3. \n= DATEDIFF (DATE (2016,1,1), DATE (2016,3,31), DAY) returns 90. \n= DATEDIFF (DATE (2016,1,1), DATE (2016,3,31), HOUR) returns 2160. \n= DATEDIFF (DATE (2016,1,1), DATE (2016,3,31), SECOND) returns 7776000. "
},
{
"code": null,
"e": 2966,
"s": 2931,
"text": "\n 53 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 2980,
"s": 2966,
"text": " Abhay Gadiya"
},
{
"code": null,
"e": 3013,
"s": 2980,
"text": "\n 24 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3027,
"s": 3013,
"text": " Randy Minder"
},
{
"code": null,
"e": 3062,
"s": 3027,
"text": "\n 26 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3076,
"s": 3062,
"text": " Randy Minder"
},
{
"code": null,
"e": 3083,
"s": 3076,
"text": " Print"
},
{
"code": null,
"e": 3094,
"s": 3083,
"text": " Add Notes"
}
] |
Check if a graph is strongly connected | Set 1 (Kosaraju using DFS) - GeeksforGeeks
|
18 Jan, 2022
Given a directed graph, find out whether the graph is strongly connected or not. A directed graph is strongly connected if there is a path between any two pair of vertices. For example, following is a strongly connected graph.
It is easy for undirected graph, we can just do a BFS and DFS starting from any vertex. If BFS or DFS visits all vertices, then the given undirected graph is connected. This approach won’t work for a directed graph. For example, consider the following graph which is not strongly connected. If we start DFS (or BFS) from vertex 0, we can reach all vertices, but if we start from any other vertex, we cannot reach all vertices.
How to do for directed graph?
A simple idea is to use a all pair shortest path algorithm like Floyd Warshall or find Transitive Closure of graph. Time complexity of this method would be O(v3).We can also do DFS V times starting from every vertex. If any DFS, doesn’t visit all vertices, then graph is not strongly connected. This algorithm takes O(V*(V+E)) time which can be same as transitive closure for a dense graph.A better idea can be Strongly Connected Components (SCC) algorithm. We can find all SCCs in O(V+E) time. If number of SCCs is one, then graph is strongly connected. The algorithm for SCC does extra work as it finds all SCCs. Following is Kosaraju’s DFS based simple algorithm that does two DFS traversals of graph: 1) Initialize all vertices as not visited.2) Do a DFS traversal of graph starting from any arbitrary vertex v. If DFS traversal doesn’t visit all vertices, then return false.3) Reverse all arcs (or find transpose or reverse of graph) 4) Mark all vertices as not-visited in reversed graph.5) Do a DFS traversal of reversed graph starting from same vertex v (Same as step 2). If DFS traversal doesn’t visit all vertices, then return false. Otherwise return true.The idea is, if every node can be reached from a vertex v, and every node can reach v, then the graph is strongly connected. In step 2, we check if all vertices are reachable from v. In step 4, we check if all vertices can reach v (In reversed graph, if all vertices are reachable from v, then all vertices can reach v in original graph). Following is the implementation of above algorithm.
C++
Java
Python3
Javascript
// C++ program to check if a given directed graph is strongly// connected or not#include <iostream>#include <list>#include <stack>using namespace std; class Graph{ int V; // No. of vertices list<int> *adj; // An array of adjacency lists // A recursive function to print DFS starting from v void DFSUtil(int v, bool visited[]);public: // Constructor and Destructor Graph(int V) { this->V = V; adj = new list<int>[V];} ~Graph() { delete [] adj; } // Method to add an edge void addEdge(int v, int w); // The main function that returns true if the graph is strongly // connected, otherwise false bool isSC(); // Function that returns reverse (or transpose) of this graph Graph getTranspose();}; // A recursive function to print DFS starting from vvoid Graph::DFSUtil(int v, bool visited[]){ // Mark the current node as visited and print it visited[v] = true; // Recur for all the vertices adjacent to this vertex list<int>::iterator i; for (i = adj[v].begin(); i != adj[v].end(); ++i) if (!visited[*i]) DFSUtil(*i, visited);} // Function that returns reverse (or transpose) of this graphGraph Graph::getTranspose(){ Graph g(V); for (int v = 0; v < V; v++) { // Recur for all the vertices adjacent to this vertex list<int>::iterator i; for(i = adj[v].begin(); i != adj[v].end(); ++i) { g.adj[*i].push_back(v); } } return g;} void Graph::addEdge(int v, int w){ adj[v].push_back(w); // Add w to v’s list.} // The main function that returns true if graph is strongly connectedbool Graph::isSC(){ // St1p 1: Mark all the vertices as not visited (For first DFS) bool visited[V]; for (int i = 0; i < V; i++) visited[i] = false; // Step 2: Do DFS traversal starting from first vertex. DFSUtil(0, visited); // If DFS traversal doesn’t visit all vertices, then return false. for (int i = 0; i < V; i++) if (visited[i] == false) return false; // Step 3: Create a reversed graph Graph gr = getTranspose(); // Step 4: Mark all the vertices as not visited (For second DFS) for(int i = 0; i < V; i++) visited[i] = false; // Step 5: Do DFS for reversed graph starting from first vertex. // Starting Vertex must be same starting point of first DFS gr.DFSUtil(0, visited); // If all vertices are not visited in second DFS, then // return false for (int i = 0; i < V; i++) if (visited[i] == false) return false; return true;} // Driver program to test above functionsint main(){ // Create graphs given in the above diagrams Graph g1(5); g1.addEdge(0, 1); g1.addEdge(1, 2); g1.addEdge(2, 3); g1.addEdge(3, 0); g1.addEdge(2, 4); g1.addEdge(4, 2); g1.isSC()? cout << "Yes\n" : cout << "No\n"; Graph g2(4); g2.addEdge(0, 1); g2.addEdge(1, 2); g2.addEdge(2, 3); g2.isSC()? cout << "Yes\n" : cout << "No\n"; return 0;}
// Java program to check if a given directed graph is strongly// connected or notimport java.io.*;import java.util.*;import java.util.LinkedList; // This class represents a directed graph using adjacency// list representationclass Graph{ private int V; // No. of vertices private LinkedList<Integer> adj[]; //Adjacency List //Constructor Graph(int v) { V = v; adj = new LinkedList[v]; for (int i=0; i<v; ++i) adj[i] = new LinkedList(); } //Function to add an edge into the graph void addEdge(int v,int w) { adj[v].add(w); } // A recursive function to print DFS starting from v void DFSUtil(int v,Boolean visited[]) { // Mark the current node as visited and print it visited[v] = true; int n; // Recur for all the vertices adjacent to this vertex Iterator<Integer> i = adj[v].iterator(); while (i.hasNext()) { n = i.next(); if (!visited[n]) DFSUtil(n,visited); } } // Function that returns transpose of this graph Graph getTranspose() { Graph g = new Graph(V); for (int v = 0; v < V; v++) { // Recur for all the vertices adjacent to this vertex Iterator<Integer> i = adj[v].listIterator(); while (i.hasNext()) g.adj[i.next()].add(v); } return g; } // The main function that returns true if graph is strongly // connected Boolean isSC() { // Step 1: Mark all the vertices as not visited // (For first DFS) Boolean visited[] = new Boolean[V]; for (int i = 0; i < V; i++) visited[i] = false; // Step 2: Do DFS traversal starting from first vertex. DFSUtil(0, visited); // If DFS traversal doesn't visit all vertices, then // return false. for (int i = 0; i < V; i++) if (visited[i] == false) return false; // Step 3: Create a reversed graph Graph gr = getTranspose(); // Step 4: Mark all the vertices as not visited (For // second DFS) for (int i = 0; i < V; i++) visited[i] = false; // Step 5: Do DFS for reversed graph starting from // first vertex. Starting Vertex must be same starting // point of first DFS gr.DFSUtil(0, visited); // If all vertices are not visited in second DFS, then // return false for (int i = 0; i < V; i++) if (visited[i] == false) return false; return true; } public static void main(String args[]) { // Create graphs given in the above diagrams Graph g1 = new Graph(5); g1.addEdge(0, 1); g1.addEdge(1, 2); g1.addEdge(2, 3); g1.addEdge(3, 0); g1.addEdge(2, 4); g1.addEdge(4, 2); if (g1.isSC()) System.out.println("Yes"); else System.out.println("No"); Graph g2 = new Graph(4); g2.addEdge(0, 1); g2.addEdge(1, 2); g2.addEdge(2, 3); if (g2.isSC()) System.out.println("Yes"); else System.out.println("No"); }}// This code is contributed by Aakash Hasija
# Python program to check if a given directed graph is strongly# connected or not from collections import defaultdict # This class represents a directed graph using adjacency list representation class Graph: def __init__(self, vertices): self.V = vertices # No. of vertices self.graph = defaultdict(list) # default dictionary to store graph # function to add an edge to graph def addEdge(self, u, v): self.graph[u].append(v) # A function used by isSC() to perform DFS def DFSUtil(self, v, visited): # Mark the current node as visited visited[v] = True # Recur for all the vertices adjacent to this vertex for i in self.graph[v]: if visited[i] == False: self.DFSUtil(i, visited) # Function that returns reverse (or transpose) of this graph def getTranspose(self): g = Graph(self.V) # Recur for all the vertices adjacent to this vertex for i in self.graph: for j in self.graph[i]: g.addEdge(j, i) return g # The main function that returns true if graph is strongly connected def isSC(self): # Step 1: Mark all the vertices as not visited (For first DFS) visited =[False]*(self.V) # Step 2: Do DFS traversal starting from first vertex. self.DFSUtil(0,visited) # If DFS traversal doesnt visit all vertices, then return false if any(i == False for i in visited): return False # Step 3: Create a reversed graph gr = self.getTranspose() # Step 4: Mark all the vertices as not visited (For second DFS) visited =[False]*(self.V) # Step 5: Do DFS for reversed graph starting from first vertex. # Starting Vertex must be same starting point of first DFS gr.DFSUtil(0,visited) # If all vertices are not visited in second DFS, then # return false if any(i == False for i in visited): return False return True # Create a graph given in the above diagramg1 = Graph(5)g1.addEdge(0, 1)g1.addEdge(1, 2)g1.addEdge(2, 3)g1.addEdge(3, 0)g1.addEdge(2, 4)g1.addEdge(4, 2)print ("Yes" if g1.isSC() else "No") g2 = Graph(4)g2.addEdge(0, 1)g2.addEdge(1, 2)g2.addEdge(2, 3)print ("Yes" if g2.isSC() else "No") # This code is contributed by Neelam Yadav
<script>// Javascript program to check if a given directed graph is strongly// connected or not // This class represents a directed graph using adjacency// list representationclass Graph{ // Constructor constructor(v) { this.V = v; this.adj = new Array(v); for (let i = 0; i < v; ++i) this.adj[i] = []; } // Function to add an edge into the graph addEdge(v,w) { this.adj[v].push(w); } // A recursive function to print DFS starting from v DFSUtil(v,visited) { // Mark the current node as visited and print it visited[v] = true; let n; // Recur for all the vertices adjacent to this vertex for(let i of this.adj[v].values()) { n = i; if (!visited[n]) this.DFSUtil(n,visited); } } // Function that returns transpose of this graph getTranspose() { let g = new Graph(this.V); for (let v = 0; v < this.V; v++) { // Recur for all the vertices adjacent to this vertex for(let i of this.adj[v].values()) g.adj[i].push(v); } return g; } // The main function that returns true if graph is strongly // connected isSC() { // Step 1: Mark all the vertices as not visited // (For first DFS) let visited = new Array(this.V); for (let i = 0; i < this.V; i++) visited[i] = false; // Step 2: Do DFS traversal starting from first vertex. this.DFSUtil(0, visited); // If DFS traversal doesn't visit all vertices, then // return false. for (let i = 0; i < this.V; i++) if (visited[i] == false) return false; // Step 3: Create a reversed graph let gr = this.getTranspose(); // Step 4: Mark all the vertices as not visited (For // second DFS) for (let i = 0; i < this.V; i++) visited[i] = false; // Step 5: Do DFS for reversed graph starting from // first vertex. Starting Vertex must be same starting // point of first DFS gr.DFSUtil(0, visited); // If all vertices are not visited in second DFS, then // return false for (let i = 0; i < this.V; i++) if (visited[i] == false) return false; return true; }} // Create graphs given in the above diagramslet g1 = new Graph(5);g1.addEdge(0, 1);g1.addEdge(1, 2);g1.addEdge(2, 3);g1.addEdge(3, 0);g1.addEdge(2, 4);g1.addEdge(4, 2);if (g1.isSC()) document.write("Yes<br>");else document.write("No<br>"); let g2 = new Graph(4);g2.addEdge(0, 1);g2.addEdge(1, 2);g2.addEdge(2, 3);if (g2.isSC()) document.write("Yes");else document.write("No"); // This code is contributed by avanitrachhadiya2155</script>
Output:
Yes
No
Time Complexity: Time complexity of above implementation is same as Depth First Search which is O(V+E) if the graph is represented using adjacency list representation.Can we improve further? The above approach requires two traversals of graph. We can find whether a graph is strongly connected or not in one traversal using Tarjan’s Algorithm to find Strongly Connected Components.Exercise: Can we use BFS instead of DFS in above algorithm? See this.References: http://www.ieor.berkeley.edu/~hochbaum/files/ieor266-2012.pdfPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above
ashishskkumar321
avanitrachhadiya2155
anikaseth98
amartyaghoshgfg
BFS
DFS
graph-connectivity
Graph
DFS
Graph
BFS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Topological Sorting
Detect Cycle in a Directed Graph
Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph)
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Ford-Fulkerson Algorithm for Maximum Flow Problem
Traveling Salesman Problem (TSP) Implementation
Detect cycle in an undirected graph
Shortest path in an unweighted graph
Union-Find Algorithm | Set 2 (Union By Rank and Path Compression)
Check whether a given graph is Bipartite or not
|
[
{
"code": null,
"e": 25228,
"s": 25200,
"text": "\n18 Jan, 2022"
},
{
"code": null,
"e": 25456,
"s": 25228,
"text": "Given a directed graph, find out whether the graph is strongly connected or not. A directed graph is strongly connected if there is a path between any two pair of vertices. For example, following is a strongly connected graph. "
},
{
"code": null,
"e": 25884,
"s": 25456,
"text": "It is easy for undirected graph, we can just do a BFS and DFS starting from any vertex. If BFS or DFS visits all vertices, then the given undirected graph is connected. This approach won’t work for a directed graph. For example, consider the following graph which is not strongly connected. If we start DFS (or BFS) from vertex 0, we can reach all vertices, but if we start from any other vertex, we cannot reach all vertices. "
},
{
"code": null,
"e": 25915,
"s": 25884,
"text": "How to do for directed graph? "
},
{
"code": null,
"e": 27472,
"s": 25915,
"text": "A simple idea is to use a all pair shortest path algorithm like Floyd Warshall or find Transitive Closure of graph. Time complexity of this method would be O(v3).We can also do DFS V times starting from every vertex. If any DFS, doesn’t visit all vertices, then graph is not strongly connected. This algorithm takes O(V*(V+E)) time which can be same as transitive closure for a dense graph.A better idea can be Strongly Connected Components (SCC) algorithm. We can find all SCCs in O(V+E) time. If number of SCCs is one, then graph is strongly connected. The algorithm for SCC does extra work as it finds all SCCs. Following is Kosaraju’s DFS based simple algorithm that does two DFS traversals of graph: 1) Initialize all vertices as not visited.2) Do a DFS traversal of graph starting from any arbitrary vertex v. If DFS traversal doesn’t visit all vertices, then return false.3) Reverse all arcs (or find transpose or reverse of graph) 4) Mark all vertices as not-visited in reversed graph.5) Do a DFS traversal of reversed graph starting from same vertex v (Same as step 2). If DFS traversal doesn’t visit all vertices, then return false. Otherwise return true.The idea is, if every node can be reached from a vertex v, and every node can reach v, then the graph is strongly connected. In step 2, we check if all vertices are reachable from v. In step 4, we check if all vertices can reach v (In reversed graph, if all vertices are reachable from v, then all vertices can reach v in original graph). Following is the implementation of above algorithm. "
},
{
"code": null,
"e": 27476,
"s": 27472,
"text": "C++"
},
{
"code": null,
"e": 27481,
"s": 27476,
"text": "Java"
},
{
"code": null,
"e": 27489,
"s": 27481,
"text": "Python3"
},
{
"code": null,
"e": 27500,
"s": 27489,
"text": "Javascript"
},
{
"code": "// C++ program to check if a given directed graph is strongly// connected or not#include <iostream>#include <list>#include <stack>using namespace std; class Graph{ int V; // No. of vertices list<int> *adj; // An array of adjacency lists // A recursive function to print DFS starting from v void DFSUtil(int v, bool visited[]);public: // Constructor and Destructor Graph(int V) { this->V = V; adj = new list<int>[V];} ~Graph() { delete [] adj; } // Method to add an edge void addEdge(int v, int w); // The main function that returns true if the graph is strongly // connected, otherwise false bool isSC(); // Function that returns reverse (or transpose) of this graph Graph getTranspose();}; // A recursive function to print DFS starting from vvoid Graph::DFSUtil(int v, bool visited[]){ // Mark the current node as visited and print it visited[v] = true; // Recur for all the vertices adjacent to this vertex list<int>::iterator i; for (i = adj[v].begin(); i != adj[v].end(); ++i) if (!visited[*i]) DFSUtil(*i, visited);} // Function that returns reverse (or transpose) of this graphGraph Graph::getTranspose(){ Graph g(V); for (int v = 0; v < V; v++) { // Recur for all the vertices adjacent to this vertex list<int>::iterator i; for(i = adj[v].begin(); i != adj[v].end(); ++i) { g.adj[*i].push_back(v); } } return g;} void Graph::addEdge(int v, int w){ adj[v].push_back(w); // Add w to v’s list.} // The main function that returns true if graph is strongly connectedbool Graph::isSC(){ // St1p 1: Mark all the vertices as not visited (For first DFS) bool visited[V]; for (int i = 0; i < V; i++) visited[i] = false; // Step 2: Do DFS traversal starting from first vertex. DFSUtil(0, visited); // If DFS traversal doesn’t visit all vertices, then return false. for (int i = 0; i < V; i++) if (visited[i] == false) return false; // Step 3: Create a reversed graph Graph gr = getTranspose(); // Step 4: Mark all the vertices as not visited (For second DFS) for(int i = 0; i < V; i++) visited[i] = false; // Step 5: Do DFS for reversed graph starting from first vertex. // Starting Vertex must be same starting point of first DFS gr.DFSUtil(0, visited); // If all vertices are not visited in second DFS, then // return false for (int i = 0; i < V; i++) if (visited[i] == false) return false; return true;} // Driver program to test above functionsint main(){ // Create graphs given in the above diagrams Graph g1(5); g1.addEdge(0, 1); g1.addEdge(1, 2); g1.addEdge(2, 3); g1.addEdge(3, 0); g1.addEdge(2, 4); g1.addEdge(4, 2); g1.isSC()? cout << \"Yes\\n\" : cout << \"No\\n\"; Graph g2(4); g2.addEdge(0, 1); g2.addEdge(1, 2); g2.addEdge(2, 3); g2.isSC()? cout << \"Yes\\n\" : cout << \"No\\n\"; return 0;}",
"e": 30502,
"s": 27500,
"text": null
},
{
"code": "// Java program to check if a given directed graph is strongly// connected or notimport java.io.*;import java.util.*;import java.util.LinkedList; // This class represents a directed graph using adjacency// list representationclass Graph{ private int V; // No. of vertices private LinkedList<Integer> adj[]; //Adjacency List //Constructor Graph(int v) { V = v; adj = new LinkedList[v]; for (int i=0; i<v; ++i) adj[i] = new LinkedList(); } //Function to add an edge into the graph void addEdge(int v,int w) { adj[v].add(w); } // A recursive function to print DFS starting from v void DFSUtil(int v,Boolean visited[]) { // Mark the current node as visited and print it visited[v] = true; int n; // Recur for all the vertices adjacent to this vertex Iterator<Integer> i = adj[v].iterator(); while (i.hasNext()) { n = i.next(); if (!visited[n]) DFSUtil(n,visited); } } // Function that returns transpose of this graph Graph getTranspose() { Graph g = new Graph(V); for (int v = 0; v < V; v++) { // Recur for all the vertices adjacent to this vertex Iterator<Integer> i = adj[v].listIterator(); while (i.hasNext()) g.adj[i.next()].add(v); } return g; } // The main function that returns true if graph is strongly // connected Boolean isSC() { // Step 1: Mark all the vertices as not visited // (For first DFS) Boolean visited[] = new Boolean[V]; for (int i = 0; i < V; i++) visited[i] = false; // Step 2: Do DFS traversal starting from first vertex. DFSUtil(0, visited); // If DFS traversal doesn't visit all vertices, then // return false. for (int i = 0; i < V; i++) if (visited[i] == false) return false; // Step 3: Create a reversed graph Graph gr = getTranspose(); // Step 4: Mark all the vertices as not visited (For // second DFS) for (int i = 0; i < V; i++) visited[i] = false; // Step 5: Do DFS for reversed graph starting from // first vertex. Starting Vertex must be same starting // point of first DFS gr.DFSUtil(0, visited); // If all vertices are not visited in second DFS, then // return false for (int i = 0; i < V; i++) if (visited[i] == false) return false; return true; } public static void main(String args[]) { // Create graphs given in the above diagrams Graph g1 = new Graph(5); g1.addEdge(0, 1); g1.addEdge(1, 2); g1.addEdge(2, 3); g1.addEdge(3, 0); g1.addEdge(2, 4); g1.addEdge(4, 2); if (g1.isSC()) System.out.println(\"Yes\"); else System.out.println(\"No\"); Graph g2 = new Graph(4); g2.addEdge(0, 1); g2.addEdge(1, 2); g2.addEdge(2, 3); if (g2.isSC()) System.out.println(\"Yes\"); else System.out.println(\"No\"); }}// This code is contributed by Aakash Hasija",
"e": 33761,
"s": 30502,
"text": null
},
{
"code": "# Python program to check if a given directed graph is strongly# connected or not from collections import defaultdict # This class represents a directed graph using adjacency list representation class Graph: def __init__(self, vertices): self.V = vertices # No. of vertices self.graph = defaultdict(list) # default dictionary to store graph # function to add an edge to graph def addEdge(self, u, v): self.graph[u].append(v) # A function used by isSC() to perform DFS def DFSUtil(self, v, visited): # Mark the current node as visited visited[v] = True # Recur for all the vertices adjacent to this vertex for i in self.graph[v]: if visited[i] == False: self.DFSUtil(i, visited) # Function that returns reverse (or transpose) of this graph def getTranspose(self): g = Graph(self.V) # Recur for all the vertices adjacent to this vertex for i in self.graph: for j in self.graph[i]: g.addEdge(j, i) return g # The main function that returns true if graph is strongly connected def isSC(self): # Step 1: Mark all the vertices as not visited (For first DFS) visited =[False]*(self.V) # Step 2: Do DFS traversal starting from first vertex. self.DFSUtil(0,visited) # If DFS traversal doesnt visit all vertices, then return false if any(i == False for i in visited): return False # Step 3: Create a reversed graph gr = self.getTranspose() # Step 4: Mark all the vertices as not visited (For second DFS) visited =[False]*(self.V) # Step 5: Do DFS for reversed graph starting from first vertex. # Starting Vertex must be same starting point of first DFS gr.DFSUtil(0,visited) # If all vertices are not visited in second DFS, then # return false if any(i == False for i in visited): return False return True # Create a graph given in the above diagramg1 = Graph(5)g1.addEdge(0, 1)g1.addEdge(1, 2)g1.addEdge(2, 3)g1.addEdge(3, 0)g1.addEdge(2, 4)g1.addEdge(4, 2)print (\"Yes\" if g1.isSC() else \"No\") g2 = Graph(4)g2.addEdge(0, 1)g2.addEdge(1, 2)g2.addEdge(2, 3)print (\"Yes\" if g2.isSC() else \"No\") # This code is contributed by Neelam Yadav",
"e": 36124,
"s": 33761,
"text": null
},
{
"code": "<script>// Javascript program to check if a given directed graph is strongly// connected or not // This class represents a directed graph using adjacency// list representationclass Graph{ // Constructor constructor(v) { this.V = v; this.adj = new Array(v); for (let i = 0; i < v; ++i) this.adj[i] = []; } // Function to add an edge into the graph addEdge(v,w) { this.adj[v].push(w); } // A recursive function to print DFS starting from v DFSUtil(v,visited) { // Mark the current node as visited and print it visited[v] = true; let n; // Recur for all the vertices adjacent to this vertex for(let i of this.adj[v].values()) { n = i; if (!visited[n]) this.DFSUtil(n,visited); } } // Function that returns transpose of this graph getTranspose() { let g = new Graph(this.V); for (let v = 0; v < this.V; v++) { // Recur for all the vertices adjacent to this vertex for(let i of this.adj[v].values()) g.adj[i].push(v); } return g; } // The main function that returns true if graph is strongly // connected isSC() { // Step 1: Mark all the vertices as not visited // (For first DFS) let visited = new Array(this.V); for (let i = 0; i < this.V; i++) visited[i] = false; // Step 2: Do DFS traversal starting from first vertex. this.DFSUtil(0, visited); // If DFS traversal doesn't visit all vertices, then // return false. for (let i = 0; i < this.V; i++) if (visited[i] == false) return false; // Step 3: Create a reversed graph let gr = this.getTranspose(); // Step 4: Mark all the vertices as not visited (For // second DFS) for (let i = 0; i < this.V; i++) visited[i] = false; // Step 5: Do DFS for reversed graph starting from // first vertex. Starting Vertex must be same starting // point of first DFS gr.DFSUtil(0, visited); // If all vertices are not visited in second DFS, then // return false for (let i = 0; i < this.V; i++) if (visited[i] == false) return false; return true; }} // Create graphs given in the above diagramslet g1 = new Graph(5);g1.addEdge(0, 1);g1.addEdge(1, 2);g1.addEdge(2, 3);g1.addEdge(3, 0);g1.addEdge(2, 4);g1.addEdge(4, 2);if (g1.isSC()) document.write(\"Yes<br>\");else document.write(\"No<br>\"); let g2 = new Graph(4);g2.addEdge(0, 1);g2.addEdge(1, 2);g2.addEdge(2, 3);if (g2.isSC()) document.write(\"Yes\");else document.write(\"No\"); // This code is contributed by avanitrachhadiya2155</script>",
"e": 39023,
"s": 36124,
"text": null
},
{
"code": null,
"e": 39031,
"s": 39023,
"text": "Output:"
},
{
"code": null,
"e": 39038,
"s": 39031,
"text": "Yes\nNo"
},
{
"code": null,
"e": 39686,
"s": 39038,
"text": "Time Complexity: Time complexity of above implementation is same as Depth First Search which is O(V+E) if the graph is represented using adjacency list representation.Can we improve further? The above approach requires two traversals of graph. We can find whether a graph is strongly connected or not in one traversal using Tarjan’s Algorithm to find Strongly Connected Components.Exercise: Can we use BFS instead of DFS in above algorithm? See this.References: http://www.ieor.berkeley.edu/~hochbaum/files/ieor266-2012.pdfPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 39703,
"s": 39686,
"text": "ashishskkumar321"
},
{
"code": null,
"e": 39724,
"s": 39703,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 39736,
"s": 39724,
"text": "anikaseth98"
},
{
"code": null,
"e": 39752,
"s": 39736,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 39756,
"s": 39752,
"text": "BFS"
},
{
"code": null,
"e": 39760,
"s": 39756,
"text": "DFS"
},
{
"code": null,
"e": 39779,
"s": 39760,
"text": "graph-connectivity"
},
{
"code": null,
"e": 39785,
"s": 39779,
"text": "Graph"
},
{
"code": null,
"e": 39789,
"s": 39785,
"text": "DFS"
},
{
"code": null,
"e": 39795,
"s": 39789,
"text": "Graph"
},
{
"code": null,
"e": 39799,
"s": 39795,
"text": "BFS"
},
{
"code": null,
"e": 39897,
"s": 39799,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 39917,
"s": 39897,
"text": "Topological Sorting"
},
{
"code": null,
"e": 39950,
"s": 39917,
"text": "Detect Cycle in a Directed Graph"
},
{
"code": null,
"e": 40025,
"s": 39950,
"text": "Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph)"
},
{
"code": null,
"e": 40093,
"s": 40025,
"text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)"
},
{
"code": null,
"e": 40143,
"s": 40093,
"text": "Ford-Fulkerson Algorithm for Maximum Flow Problem"
},
{
"code": null,
"e": 40191,
"s": 40143,
"text": "Traveling Salesman Problem (TSP) Implementation"
},
{
"code": null,
"e": 40227,
"s": 40191,
"text": "Detect cycle in an undirected graph"
},
{
"code": null,
"e": 40264,
"s": 40227,
"text": "Shortest path in an unweighted graph"
},
{
"code": null,
"e": 40330,
"s": 40264,
"text": "Union-Find Algorithm | Set 2 (Union By Rank and Path Compression)"
}
] |
Continuous Tree - GeeksforGeeks
|
06 Jul, 2021
A tree is a Continuous tree if in each root to leaf path, the absolute difference between keys of two adjacent is 1. We are given a binary tree, we need to check if the tree is continuous or not.
Examples:
Input : 3
/ \
2 4
/ \ \
1 3 5
Output: "Yes"
// 3->2->1 every two adjacent node's absolute difference is 1
// 3->2->3 every two adjacent node's absolute difference is 1
// 3->4->5 every two adjacent node's absolute difference is 1
Input : 7
/ \
5 8
/ \ \
6 4 10
Output: "No"
// 7->5->6 here absolute difference of 7 and 5 is not 1.
// 7->5->4 here absolute difference of 7 and 5 is not 1.
// 7->8->10 here absolute difference of 8 and 10 is not 1.
The solution requires a traversal of the tree. The important things to check are to make sure that all corner cases are handled. The corner cases include an empty tree, single-node tree, a node with only the left child and a node with the only right child.In tree traversal, we recursively check if left and right subtree are continuous. We also check if the difference between the keys of the current node’s key and its children keys is 1. Below is the implementation of the idea.
C++
Java
C#
Javascript
// C++ program to check if a tree is continuous or not#include<bits/stdc++.h>using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */struct Node{ int data; struct Node* left, * right;}; /* Helper function that allocates a new node with the given data and NULL left and right pointers. */struct Node* newNode(int data){ struct Node* node = new Node; node->data = data; node->left = node->right = NULL; return(node);} // Function to check tree is continuous or notbool treeContinuous(struct Node *ptr){ // if next node is empty then return true if (ptr == NULL) return true; // if current node is leaf node then return true // because it is end of root to leaf path if (ptr->left == NULL && ptr->right == NULL) return true; // If left subtree is empty, then only check right if (ptr->left == NULL) return (abs(ptr->data - ptr->right->data) == 1) && treeContinuous(ptr->right); // If right subtree is empty, then only check left if (ptr->right == NULL) return (abs(ptr->data - ptr->left->data) == 1) && treeContinuous(ptr->left); // If both left and right subtrees are not empty, check // everything return abs(ptr->data - ptr->left->data)==1 && abs(ptr->data - ptr->right->data)==1 && treeContinuous(ptr->left) && treeContinuous(ptr->right);} /* Driver program to test mirror() */int main(){ struct Node *root = newNode(3); root->left = newNode(2); root->right = newNode(4); root->left->left = newNode(1); root->left->right = newNode(3); root->right->right = newNode(5); treeContinuous(root)? cout << "Yes" : cout << "No"; return 0;}
// Java program to check if a tree is continuous or notimport java.util.*; class solution{ /* A binary tree node has data, pointer to left childand a pointer to right child */static class Node{ int data; Node left, right;}; /* Helper function that allocates a new node with thegiven data and null left and right pointers. */ static Node newNode(int data){ Node node = new Node(); node.data = data; node.left = node.right = null; return(node);} // Function to check tree is continuous or not static boolean treeContinuous( Node ptr){ // if next node is empty then return true if (ptr == null) return true; // if current node is leaf node then return true // because it is end of root to leaf path if (ptr.left == null && ptr.right == null) return true; // If left subtree is empty, then only check right if (ptr.left == null) return (Math.abs(ptr.data - ptr.right.data) == 1) && treeContinuous(ptr.right); // If right subtree is empty, then only check left if (ptr.right == null) return (Math.abs(ptr.data - ptr.left.data) == 1) && treeContinuous(ptr.left); // If both left and right subtrees are not empty, check // everything return Math.abs(ptr.data - ptr.left.data)==1 && Math.abs(ptr.data - ptr.right.data)==1 && treeContinuous(ptr.left) && treeContinuous(ptr.right);} /* Driver program to test mirror() */public static void main(String args[]){ Node root = newNode(3); root.left = newNode(2); root.right = newNode(4); root.left.left = newNode(1); root.left.right = newNode(3); root.right.right = newNode(5); if(treeContinuous(root)) System.out.println( "Yes") ; else System.out.println( "No");}}//contributed by Arnab Kundu
// C# program to check if a tree is continuous or notusing System; class solution{ /* A binary tree node has data, pointer to left childand a pointer to right child */class Node{ public int data; public Node left, right;}; /* Helper function that allocates a new node with thegiven data and null left and right pointers. */ static Node newNode(int data){ Node node = new Node(); node.data = data; node.left = node.right = null; return(node);} // Function to check tree is continuous or not static Boolean treeContinuous( Node ptr){ // if next node is empty then return true if (ptr == null) return true; // if current node is leaf node then return true // because it is end of root to leaf path if (ptr.left == null && ptr.right == null) return true; // If left subtree is empty, then only check right if (ptr.left == null) return (Math.Abs(ptr.data - ptr.right.data) == 1) && treeContinuous(ptr.right); // If right subtree is empty, then only check left if (ptr.right == null) return (Math.Abs(ptr.data - ptr.left.data) == 1) && treeContinuous(ptr.left); // If both left and right subtrees are not empty, check // everything return Math.Abs(ptr.data - ptr.left.data)==1 && Math.Abs(ptr.data - ptr.right.data)==1 && treeContinuous(ptr.left) && treeContinuous(ptr.right);} /* Driver program to test mirror() */static public void Main(String []args){ Node root = newNode(3); root.left = newNode(2); root.right = newNode(4); root.left.left = newNode(1); root.left.right = newNode(3); root.right.right = newNode(5); if(treeContinuous(root)) Console.WriteLine( "Yes") ; else Console.WriteLine( "No");}}//contributed by Arnab Kundu
<script> // JavaScript program to check if a tree is continuous or not /* A binary tree node has data, pointer to left childand a pointer to right child */class Node{ constructor() { this.data=0; this.left = null; this.right = null; }}; /* Helper function that allocates a new node with thegiven data and null left and right pointers. */ function newNode(data){ var node = new Node(); node.data = data; node.left = node.right = null; return(node);} // Function to check tree is continuous or notfunction treeContinuous( ptr){ // if next node is empty then return true if (ptr == null) return true; // if current node is leaf node then return true // because it is end of root to leaf path if (ptr.left == null && ptr.right == null) return true; // If left subtree is empty, then only check right if (ptr.left == null) return (Math.abs(ptr.data - ptr.right.data) == 1) && treeContinuous(ptr.right); // If right subtree is empty, then only check left if (ptr.right == null) return (Math.abs(ptr.data - ptr.left.data) == 1) && treeContinuous(ptr.left); // If both left and right subtrees are not empty, check // everything return Math.abs(ptr.data - ptr.left.data)==1 && Math.abs(ptr.data - ptr.right.data)==1 && treeContinuous(ptr.left) && treeContinuous(ptr.right);} /* Driver program to test mirror() */var root = newNode(3);root.left = newNode(2);root.right = newNode(4);root.left.left = newNode(1);root.left.right = newNode(3);root.right.right = newNode(5);if(treeContinuous(root)) document.write( "Yes") ;else document.write( "No"); </script>
Output:
Yes
This article is contributed by Shashank Mishra ( Gullu ).
Another approach (using BFS(Queue))
Explanation:
We will simply traverse each node level by level and check if the difference between parent and child is 1, if it is true for all nodes then we will return true else we will return false.
C++14
Java
C#
Javascript
// CPP Code to check if the tree is continuous or not#include <bits/stdc++.h>using namespace std; // Node structurestruct node { int val; node* left; node* right; node() : val(0) , left(nullptr) , right(nullptr) { } node(int x) : val(x) , left(nullptr) , right(nullptr) { } node(int x, node* left, node* right) : val(x) , left(left) , right(right) { }}; // Function to check if the tree is continuous or notbool continuous(struct node* root){ // If root is Null then tree isn't Continuous if (root == NULL) return false; int flag = 1; queue<struct node*> Q; Q.push(root); node* temp; // BFS Traversal while (!Q.empty()) { temp = Q.front(); Q.pop(); // Move to left child if (temp->left) { // if difference between parent and child is // equal to 1 then do continue otherwise make // flag = 0 and break if (abs(temp->left->val - temp->val) == 1) Q.push(temp->left); else { flag = 0; break; } } // Move to right child if (temp->right) { // if difference between parent and child is // equal to 1 then do continue otherwise make // flag = 0 and break if (abs(temp->right->val - temp->val) == 1) Q.push(temp->right); else { flag = 0; break; } } } if (flag) return true; else return false;} // Driver Codeint main(){ // Constructing the Tree struct node* root = new node(3); root->left = new node(2); root->right = new node(4); root->left->left = new node(1); root->left->right = new node(3); root->right->right = new node(5); // Function Call if (continuous(root)) cout << "True\n"; else cout << "False\n"; return 0;} // This code is contributed by Sanjeev Yadav.
// JAVA Code to check if the tree is continuous or notimport java.util.*;class GFG{ // Node structurestatic class node{ int val; node left; node right; node() { this.val = 0; this.left = null; this.right= null; } node(int x) { this.val = x; this.left = null; this.right= null; } node(int x, node left, node right) { this.val = x; this.left = left; this.right= right; }}; // Function to check if the tree is continuous or notstatic boolean continuous(node root){ // If root is Null then tree isn't Continuous if (root == null) return false; int flag = 1; Queue<node> Q = new LinkedList<>(); Q.add(root); node temp; // BFS Traversal while (!Q.isEmpty()) { temp = Q.peek(); Q.remove(); // Move to left child if (temp.left != null) { // if difference between parent and child is // equal to 1 then do continue otherwise make // flag = 0 and break if (Math.abs(temp.left.val - temp.val) == 1) Q.add(temp.left); else { flag = 0; break; } } // Move to right child if (temp.right != null) { // if difference between parent and child is // equal to 1 then do continue otherwise make // flag = 0 and break if (Math.abs(temp.right.val - temp.val) == 1) Q.add(temp.right); else { flag = 0; break; } } } if (flag != 0) return true; else return false;} // Driver Codepublic static void main(String[] args){ // Constructing the Tree node root = new node(3); root.left = new node(2); root.right = new node(4); root.left.left = new node(1); root.left.right = new node(3); root.right.right = new node(5); // Function Call if (continuous(root)) System.out.print("True\n"); else System.out.print("False\n");}} // This code is contributed by Rajput-Ji
// C# Code to check if the tree is continuous or notusing System;using System.Collections.Generic;class GFG{ // Node structure public class node { public int val; public node left; public node right; public node() { this.val = 0; this.left = null; this.right = null; } public node(int x) { this.val = x; this.left = null; this.right = null; } public node(int x, node left, node right) { this.val = x; this.left = left; this.right = right; } }; // Function to check if the tree is continuous or not static bool continuous(node root) { // If root is Null then tree isn't Continuous if (root == null) return false; int flag = 1; Queue<node> Q = new Queue<node>(); Q.Enqueue(root); node temp; // BFS Traversal while (Q.Count != 0) { temp = Q.Peek(); Q.Dequeue(); // Move to left child if (temp.left != null) { // if difference between parent and child is // equal to 1 then do continue otherwise make // flag = 0 and break if (Math.Abs(temp.left.val - temp.val) == 1) Q.Enqueue(temp.left); else { flag = 0; break; } } // Move to right child if (temp.right != null) { // if difference between parent and child is // equal to 1 then do continue otherwise make // flag = 0 and break if (Math.Abs(temp.right.val - temp.val) == 1) Q.Enqueue(temp.right); else { flag = 0; break; } } } if (flag != 0) return true; else return false; } // Driver Code public static void Main(String[] args) { // Constructing the Tree node root = new node(3); root.left = new node(2); root.right = new node(4); root.left.left = new node(1); root.left.right = new node(3); root.right.right = new node(5); // Function Call if (continuous(root)) Console.Write("True\n"); else Console.Write("False\n"); }} // This code is contributed by Rajput-Ji
<script>// Javascript Code to check if the tree is continuous or not // Node structureclass Node{ constructor(x) { this.val = x; this.left = null; this.right= null; }} // Function to check if the tree is continuous or notfunction continuous(root){ // If root is Null then tree isn't Continuous if (root == null) return false; let flag = 1; let Q = []; Q.push(root); let temp; // BFS Traversal while (Q.length!=0) { temp = Q.shift(); // Move to left child if (temp.left != null) { // if difference between parent and child is // equal to 1 then do continue otherwise make // flag = 0 and break if (Math.abs(temp.left.val - temp.val) == 1) Q.push(temp.left); else { flag = 0; break; } } // Move to right child if (temp.right != null) { // if difference between parent and child is // equal to 1 then do continue otherwise make // flag = 0 and break if (Math.abs(temp.right.val - temp.val) == 1) Q.push(temp.right); else { flag = 0; break; } } } if (flag != 0) return true; else return false;} // Driver Code// Constructing the Treelet root = new Node(3);root.left = new Node(2);root.right = new Node(4);root.left.left = new Node(1);root.left.right = new Node(3);root.right.right = new Node(5); // Function Callif (continuous(root)) document.write("True<br>");else document.write("False<br>"); // This code is contributed by avanitrachhadiya2155</script>
True
Time Complexity: O(n)
If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
andrew1234
veejnas7
Rajput-Ji
clintra
itsok
surindertarika1234
avanitrachhadiya2155
Tree
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Tree Traversals (Inorder, Preorder and Postorder)
Binary Tree | Set 1 (Introduction)
Level Order Binary Tree Traversal
AVL Tree | Set 1 (Insertion)
Inorder Tree Traversal without Recursion
Write a Program to Find the Maximum Depth or Height of a Tree
Binary Tree | Set 3 (Types of Binary Tree)
Binary Tree | Set 2 (Properties)
A program to check if a binary tree is BST or not
|
[
{
"code": null,
"e": 35846,
"s": 35818,
"text": "\n06 Jul, 2021"
},
{
"code": null,
"e": 36042,
"s": 35846,
"text": "A tree is a Continuous tree if in each root to leaf path, the absolute difference between keys of two adjacent is 1. We are given a binary tree, we need to check if the tree is continuous or not."
},
{
"code": null,
"e": 36053,
"s": 36042,
"text": "Examples: "
},
{
"code": null,
"e": 36693,
"s": 36053,
"text": "Input : 3\n / \\\n 2 4\n / \\ \\\n 1 3 5\nOutput: \"Yes\"\n\n// 3->2->1 every two adjacent node's absolute difference is 1\n// 3->2->3 every two adjacent node's absolute difference is 1\n// 3->4->5 every two adjacent node's absolute difference is 1\n\nInput : 7\n / \\\n 5 8\n / \\ \\\n 6 4 10\nOutput: \"No\"\n\n// 7->5->6 here absolute difference of 7 and 5 is not 1.\n// 7->5->4 here absolute difference of 7 and 5 is not 1.\n// 7->8->10 here absolute difference of 8 and 10 is not 1."
},
{
"code": null,
"e": 37177,
"s": 36693,
"text": "The solution requires a traversal of the tree. The important things to check are to make sure that all corner cases are handled. The corner cases include an empty tree, single-node tree, a node with only the left child and a node with the only right child.In tree traversal, we recursively check if left and right subtree are continuous. We also check if the difference between the keys of the current node’s key and its children keys is 1. Below is the implementation of the idea. "
},
{
"code": null,
"e": 37181,
"s": 37177,
"text": "C++"
},
{
"code": null,
"e": 37186,
"s": 37181,
"text": "Java"
},
{
"code": null,
"e": 37189,
"s": 37186,
"text": "C#"
},
{
"code": null,
"e": 37200,
"s": 37189,
"text": "Javascript"
},
{
"code": "// C++ program to check if a tree is continuous or not#include<bits/stdc++.h>using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */struct Node{ int data; struct Node* left, * right;}; /* Helper function that allocates a new node with the given data and NULL left and right pointers. */struct Node* newNode(int data){ struct Node* node = new Node; node->data = data; node->left = node->right = NULL; return(node);} // Function to check tree is continuous or notbool treeContinuous(struct Node *ptr){ // if next node is empty then return true if (ptr == NULL) return true; // if current node is leaf node then return true // because it is end of root to leaf path if (ptr->left == NULL && ptr->right == NULL) return true; // If left subtree is empty, then only check right if (ptr->left == NULL) return (abs(ptr->data - ptr->right->data) == 1) && treeContinuous(ptr->right); // If right subtree is empty, then only check left if (ptr->right == NULL) return (abs(ptr->data - ptr->left->data) == 1) && treeContinuous(ptr->left); // If both left and right subtrees are not empty, check // everything return abs(ptr->data - ptr->left->data)==1 && abs(ptr->data - ptr->right->data)==1 && treeContinuous(ptr->left) && treeContinuous(ptr->right);} /* Driver program to test mirror() */int main(){ struct Node *root = newNode(3); root->left = newNode(2); root->right = newNode(4); root->left->left = newNode(1); root->left->right = newNode(3); root->right->right = newNode(5); treeContinuous(root)? cout << \"Yes\" : cout << \"No\"; return 0;}",
"e": 38969,
"s": 37200,
"text": null
},
{
"code": "// Java program to check if a tree is continuous or notimport java.util.*; class solution{ /* A binary tree node has data, pointer to left childand a pointer to right child */static class Node{ int data; Node left, right;}; /* Helper function that allocates a new node with thegiven data and null left and right pointers. */ static Node newNode(int data){ Node node = new Node(); node.data = data; node.left = node.right = null; return(node);} // Function to check tree is continuous or not static boolean treeContinuous( Node ptr){ // if next node is empty then return true if (ptr == null) return true; // if current node is leaf node then return true // because it is end of root to leaf path if (ptr.left == null && ptr.right == null) return true; // If left subtree is empty, then only check right if (ptr.left == null) return (Math.abs(ptr.data - ptr.right.data) == 1) && treeContinuous(ptr.right); // If right subtree is empty, then only check left if (ptr.right == null) return (Math.abs(ptr.data - ptr.left.data) == 1) && treeContinuous(ptr.left); // If both left and right subtrees are not empty, check // everything return Math.abs(ptr.data - ptr.left.data)==1 && Math.abs(ptr.data - ptr.right.data)==1 && treeContinuous(ptr.left) && treeContinuous(ptr.right);} /* Driver program to test mirror() */public static void main(String args[]){ Node root = newNode(3); root.left = newNode(2); root.right = newNode(4); root.left.left = newNode(1); root.left.right = newNode(3); root.right.right = newNode(5); if(treeContinuous(root)) System.out.println( \"Yes\") ; else System.out.println( \"No\");}}//contributed by Arnab Kundu",
"e": 40769,
"s": 38969,
"text": null
},
{
"code": "// C# program to check if a tree is continuous or notusing System; class solution{ /* A binary tree node has data, pointer to left childand a pointer to right child */class Node{ public int data; public Node left, right;}; /* Helper function that allocates a new node with thegiven data and null left and right pointers. */ static Node newNode(int data){ Node node = new Node(); node.data = data; node.left = node.right = null; return(node);} // Function to check tree is continuous or not static Boolean treeContinuous( Node ptr){ // if next node is empty then return true if (ptr == null) return true; // if current node is leaf node then return true // because it is end of root to leaf path if (ptr.left == null && ptr.right == null) return true; // If left subtree is empty, then only check right if (ptr.left == null) return (Math.Abs(ptr.data - ptr.right.data) == 1) && treeContinuous(ptr.right); // If right subtree is empty, then only check left if (ptr.right == null) return (Math.Abs(ptr.data - ptr.left.data) == 1) && treeContinuous(ptr.left); // If both left and right subtrees are not empty, check // everything return Math.Abs(ptr.data - ptr.left.data)==1 && Math.Abs(ptr.data - ptr.right.data)==1 && treeContinuous(ptr.left) && treeContinuous(ptr.right);} /* Driver program to test mirror() */static public void Main(String []args){ Node root = newNode(3); root.left = newNode(2); root.right = newNode(4); root.left.left = newNode(1); root.left.right = newNode(3); root.right.right = newNode(5); if(treeContinuous(root)) Console.WriteLine( \"Yes\") ; else Console.WriteLine( \"No\");}}//contributed by Arnab Kundu",
"e": 42566,
"s": 40769,
"text": null
},
{
"code": "<script> // JavaScript program to check if a tree is continuous or not /* A binary tree node has data, pointer to left childand a pointer to right child */class Node{ constructor() { this.data=0; this.left = null; this.right = null; }}; /* Helper function that allocates a new node with thegiven data and null left and right pointers. */ function newNode(data){ var node = new Node(); node.data = data; node.left = node.right = null; return(node);} // Function to check tree is continuous or notfunction treeContinuous( ptr){ // if next node is empty then return true if (ptr == null) return true; // if current node is leaf node then return true // because it is end of root to leaf path if (ptr.left == null && ptr.right == null) return true; // If left subtree is empty, then only check right if (ptr.left == null) return (Math.abs(ptr.data - ptr.right.data) == 1) && treeContinuous(ptr.right); // If right subtree is empty, then only check left if (ptr.right == null) return (Math.abs(ptr.data - ptr.left.data) == 1) && treeContinuous(ptr.left); // If both left and right subtrees are not empty, check // everything return Math.abs(ptr.data - ptr.left.data)==1 && Math.abs(ptr.data - ptr.right.data)==1 && treeContinuous(ptr.left) && treeContinuous(ptr.right);} /* Driver program to test mirror() */var root = newNode(3);root.left = newNode(2);root.right = newNode(4);root.left.left = newNode(1);root.left.right = newNode(3);root.right.right = newNode(5);if(treeContinuous(root)) document.write( \"Yes\") ;else document.write( \"No\"); </script>",
"e": 44284,
"s": 42566,
"text": null
},
{
"code": null,
"e": 44293,
"s": 44284,
"text": "Output: "
},
{
"code": null,
"e": 44297,
"s": 44293,
"text": "Yes"
},
{
"code": null,
"e": 44356,
"s": 44297,
"text": "This article is contributed by Shashank Mishra ( Gullu ). "
},
{
"code": null,
"e": 44392,
"s": 44356,
"text": "Another approach (using BFS(Queue))"
},
{
"code": null,
"e": 44406,
"s": 44392,
"text": "Explanation: "
},
{
"code": null,
"e": 44594,
"s": 44406,
"text": "We will simply traverse each node level by level and check if the difference between parent and child is 1, if it is true for all nodes then we will return true else we will return false."
},
{
"code": null,
"e": 44600,
"s": 44594,
"text": "C++14"
},
{
"code": null,
"e": 44605,
"s": 44600,
"text": "Java"
},
{
"code": null,
"e": 44608,
"s": 44605,
"text": "C#"
},
{
"code": null,
"e": 44619,
"s": 44608,
"text": "Javascript"
},
{
"code": "// CPP Code to check if the tree is continuous or not#include <bits/stdc++.h>using namespace std; // Node structurestruct node { int val; node* left; node* right; node() : val(0) , left(nullptr) , right(nullptr) { } node(int x) : val(x) , left(nullptr) , right(nullptr) { } node(int x, node* left, node* right) : val(x) , left(left) , right(right) { }}; // Function to check if the tree is continuous or notbool continuous(struct node* root){ // If root is Null then tree isn't Continuous if (root == NULL) return false; int flag = 1; queue<struct node*> Q; Q.push(root); node* temp; // BFS Traversal while (!Q.empty()) { temp = Q.front(); Q.pop(); // Move to left child if (temp->left) { // if difference between parent and child is // equal to 1 then do continue otherwise make // flag = 0 and break if (abs(temp->left->val - temp->val) == 1) Q.push(temp->left); else { flag = 0; break; } } // Move to right child if (temp->right) { // if difference between parent and child is // equal to 1 then do continue otherwise make // flag = 0 and break if (abs(temp->right->val - temp->val) == 1) Q.push(temp->right); else { flag = 0; break; } } } if (flag) return true; else return false;} // Driver Codeint main(){ // Constructing the Tree struct node* root = new node(3); root->left = new node(2); root->right = new node(4); root->left->left = new node(1); root->left->right = new node(3); root->right->right = new node(5); // Function Call if (continuous(root)) cout << \"True\\n\"; else cout << \"False\\n\"; return 0;} // This code is contributed by Sanjeev Yadav.",
"e": 46666,
"s": 44619,
"text": null
},
{
"code": "// JAVA Code to check if the tree is continuous or notimport java.util.*;class GFG{ // Node structurestatic class node{ int val; node left; node right; node() { this.val = 0; this.left = null; this.right= null; } node(int x) { this.val = x; this.left = null; this.right= null; } node(int x, node left, node right) { this.val = x; this.left = left; this.right= right; }}; // Function to check if the tree is continuous or notstatic boolean continuous(node root){ // If root is Null then tree isn't Continuous if (root == null) return false; int flag = 1; Queue<node> Q = new LinkedList<>(); Q.add(root); node temp; // BFS Traversal while (!Q.isEmpty()) { temp = Q.peek(); Q.remove(); // Move to left child if (temp.left != null) { // if difference between parent and child is // equal to 1 then do continue otherwise make // flag = 0 and break if (Math.abs(temp.left.val - temp.val) == 1) Q.add(temp.left); else { flag = 0; break; } } // Move to right child if (temp.right != null) { // if difference between parent and child is // equal to 1 then do continue otherwise make // flag = 0 and break if (Math.abs(temp.right.val - temp.val) == 1) Q.add(temp.right); else { flag = 0; break; } } } if (flag != 0) return true; else return false;} // Driver Codepublic static void main(String[] args){ // Constructing the Tree node root = new node(3); root.left = new node(2); root.right = new node(4); root.left.left = new node(1); root.left.right = new node(3); root.right.right = new node(5); // Function Call if (continuous(root)) System.out.print(\"True\\n\"); else System.out.print(\"False\\n\");}} // This code is contributed by Rajput-Ji",
"e": 48846,
"s": 46666,
"text": null
},
{
"code": "// C# Code to check if the tree is continuous or notusing System;using System.Collections.Generic;class GFG{ // Node structure public class node { public int val; public node left; public node right; public node() { this.val = 0; this.left = null; this.right = null; } public node(int x) { this.val = x; this.left = null; this.right = null; } public node(int x, node left, node right) { this.val = x; this.left = left; this.right = right; } }; // Function to check if the tree is continuous or not static bool continuous(node root) { // If root is Null then tree isn't Continuous if (root == null) return false; int flag = 1; Queue<node> Q = new Queue<node>(); Q.Enqueue(root); node temp; // BFS Traversal while (Q.Count != 0) { temp = Q.Peek(); Q.Dequeue(); // Move to left child if (temp.left != null) { // if difference between parent and child is // equal to 1 then do continue otherwise make // flag = 0 and break if (Math.Abs(temp.left.val - temp.val) == 1) Q.Enqueue(temp.left); else { flag = 0; break; } } // Move to right child if (temp.right != null) { // if difference between parent and child is // equal to 1 then do continue otherwise make // flag = 0 and break if (Math.Abs(temp.right.val - temp.val) == 1) Q.Enqueue(temp.right); else { flag = 0; break; } } } if (flag != 0) return true; else return false; } // Driver Code public static void Main(String[] args) { // Constructing the Tree node root = new node(3); root.left = new node(2); root.right = new node(4); root.left.left = new node(1); root.left.right = new node(3); root.right.right = new node(5); // Function Call if (continuous(root)) Console.Write(\"True\\n\"); else Console.Write(\"False\\n\"); }} // This code is contributed by Rajput-Ji",
"e": 51042,
"s": 48846,
"text": null
},
{
"code": "<script>// Javascript Code to check if the tree is continuous or not // Node structureclass Node{ constructor(x) { this.val = x; this.left = null; this.right= null; }} // Function to check if the tree is continuous or notfunction continuous(root){ // If root is Null then tree isn't Continuous if (root == null) return false; let flag = 1; let Q = []; Q.push(root); let temp; // BFS Traversal while (Q.length!=0) { temp = Q.shift(); // Move to left child if (temp.left != null) { // if difference between parent and child is // equal to 1 then do continue otherwise make // flag = 0 and break if (Math.abs(temp.left.val - temp.val) == 1) Q.push(temp.left); else { flag = 0; break; } } // Move to right child if (temp.right != null) { // if difference between parent and child is // equal to 1 then do continue otherwise make // flag = 0 and break if (Math.abs(temp.right.val - temp.val) == 1) Q.push(temp.right); else { flag = 0; break; } } } if (flag != 0) return true; else return false;} // Driver Code// Constructing the Treelet root = new Node(3);root.left = new Node(2);root.right = new Node(4);root.left.left = new Node(1);root.left.right = new Node(3);root.right.right = new Node(5); // Function Callif (continuous(root)) document.write(\"True<br>\");else document.write(\"False<br>\"); // This code is contributed by avanitrachhadiya2155</script>",
"e": 52827,
"s": 51042,
"text": null
},
{
"code": null,
"e": 52832,
"s": 52827,
"text": "True"
},
{
"code": null,
"e": 52854,
"s": 52832,
"text": "Time Complexity: O(n)"
},
{
"code": null,
"e": 53230,
"s": 52854,
"text": "If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 53241,
"s": 53230,
"text": "andrew1234"
},
{
"code": null,
"e": 53250,
"s": 53241,
"text": "veejnas7"
},
{
"code": null,
"e": 53260,
"s": 53250,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 53268,
"s": 53260,
"text": "clintra"
},
{
"code": null,
"e": 53274,
"s": 53268,
"text": "itsok"
},
{
"code": null,
"e": 53293,
"s": 53274,
"text": "surindertarika1234"
},
{
"code": null,
"e": 53314,
"s": 53293,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 53319,
"s": 53314,
"text": "Tree"
},
{
"code": null,
"e": 53324,
"s": 53319,
"text": "Tree"
},
{
"code": null,
"e": 53422,
"s": 53324,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 53472,
"s": 53422,
"text": "Tree Traversals (Inorder, Preorder and Postorder)"
},
{
"code": null,
"e": 53507,
"s": 53472,
"text": "Binary Tree | Set 1 (Introduction)"
},
{
"code": null,
"e": 53541,
"s": 53507,
"text": "Level Order Binary Tree Traversal"
},
{
"code": null,
"e": 53570,
"s": 53541,
"text": "AVL Tree | Set 1 (Insertion)"
},
{
"code": null,
"e": 53611,
"s": 53570,
"text": "Inorder Tree Traversal without Recursion"
},
{
"code": null,
"e": 53673,
"s": 53611,
"text": "Write a Program to Find the Maximum Depth or Height of a Tree"
},
{
"code": null,
"e": 53716,
"s": 53673,
"text": "Binary Tree | Set 3 (Types of Binary Tree)"
},
{
"code": null,
"e": 53749,
"s": 53716,
"text": "Binary Tree | Set 2 (Properties)"
}
] |
Count pairs with given sum | Practice | GeeksforGeeks
|
Given an array of N integers, and an integer K, find the number of pairs of elements in the array whose sum is equal to K.
Example 1:
Input:
N = 4, K = 6
arr[] = {1, 5, 7, 1}
Output: 2
Explanation:
arr[0] + arr[1] = 1 + 5 = 6
and arr[1] + arr[3] = 5 + 1 = 6.
Example 2:
Input:
N = 4, K = 2
arr[] = {1, 1, 1, 1}
Output: 6
Explanation:
Each 1 will produce sum 2 with any 1.
Your Task:
You don't need to read input or print anything. Your task is to complete the function getPairsCount() which takes arr[], n and k as input parameters and returns the number of pairs that have sum K.
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(N)
Constraints:
1 <= N <= 105
1 <= K <= 108
1 <= Arr[i] <= 106
0
satan3 days ago
Easiest C++ solution
int getPairsCount(int a[], int n, int k) { // code here unordered_map<int,int> m; int c=0; for(int i=0;i<n;i++) { c+=m[k-a[i]]; m[a[i]]++; } return c; }
0
ohyeahpiet1 week ago
class Solution{ public: int getPairsCount(int arr[], int n, int k) { unordered_map<int,int> m; int ans=0; for(int i = 0 ; i < n ; i++){ int val = k - arr[i]; if(m[val]){ ans += m[val]; } m[arr[i]]++; } return ans; }};
0
tanishabhadanianve2 weeks ago
// JAVA SOLUTION
int getPairsCount(int[] arr, int n, int k) { HashMap<Integer,Integer> map = new HashMap<>(); int count=0; for(int i=0;i<n;i++) { if(map.containsKey(k-arr[i])) { count += map.get(k-arr[i]); } if(!map.containsKey(arr[i])) map.put(arr[i],1); else map.put(arr[i],map.get(arr[i])+1); } return count; }
+1
bijeshkumarch2 weeks ago
#Python
dct=dict() for i in arr: dct[i]=0 for i in arr: dct[i]+=1 cnt=0 for i in dct.keys(): if 2*i==k and dct[i]>1: cnt+=(dct[i]*(dct[i]-1))//2 dct[i]=0 else: if k-i in dct.keys(): if i==k-i: continue cnt+=(dct[i]*dct[k-i]) dct[i],dct[k-i]=0,0 return cnt
0
kousikbarik20002 weeks ago
def findPairs(arr,target): for i in range(len(arr)): for j in range(i+1,len(arr)): if arr[i] == arr[j]: continue elif arr[i] + arr[j] == target: print(i,j)arr = [1,5,7,1]findPairs(arr,6)
0
rajivkumawat280120022 weeks ago
simple and easy solution in c++........i solve it after 31 attempts...............
int getPairsCount(int arr[], int n, int k) { // code here sort(arr,arr+n);int flag=0;int count=0;int low=0;int high=n-1;int temp;
while(low<high){ if(arr[low]+arr[high]==k) { flag=1; count++; temp=high; while(low<high-1) { if(arr[low]+arr[high-1]==k) { count++; } high--; } high=temp; low++; }
else if(arr[low]+arr[high]>k) { high--; }
else low++;
}
if(flag==0){ return {0};}
else{ return count;}
}
+1
rajivkumawat28012002
This comment was deleted.
0
gautambaddy2 weeks ago
//optimize the solution
class Solution{ public: int getPairsCount(int arr[], int n, int k) { // codint k=0; int l=0; int i=0; while( i<n){ for(int j=i+1;j<n;j++){ int sum=0; if (arr[i]<k){ sum=arr[i]+arr[j]; if (sum==k){ l+=1; } } }i++; } return l; }};
+1
deepakprakashjyotisahu2 weeks ago
//1.HashMap int c=0; HashMap<Integer,Integer>map=new HashMap<>(); for(int i=0;i<arr.length;i++){ if(map.containsKey(k-arr[i])){ c=c+map.get(k-arr[i]); } map.put(arr[i],map.getOrDefault(arr[i],0)+1); } return c;
+2
anishmeena0013 weeks ago
class Solution{ public: int getPairsCount(int arr[], int n, int k) { // code here int ans=0; unordered_map<int,int> m; for(int i=0;i<n;i++) { m[arr[i]]++; } for(int i=0;i<n;i++) { ans+=m[k-arr[i]]; if(k-arr[i]==arr[i]) { ans--; } } return ans/2; }};
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
|
[
{
"code": null,
"e": 361,
"s": 238,
"text": "Given an array of N integers, and an integer K, find the number of pairs of elements in the array whose sum is equal to K."
},
{
"code": null,
"e": 373,
"s": 361,
"text": "\nExample 1:"
},
{
"code": null,
"e": 501,
"s": 373,
"text": "Input:\nN = 4, K = 6\narr[] = {1, 5, 7, 1}\nOutput: 2\nExplanation: \narr[0] + arr[1] = 1 + 5 = 6 \nand arr[1] + arr[3] = 5 + 1 = 6.\n"
},
{
"code": null,
"e": 513,
"s": 501,
"text": "\nExample 2:"
},
{
"code": null,
"e": 616,
"s": 513,
"text": "Input:\nN = 4, K = 2\narr[] = {1, 1, 1, 1}\nOutput: 6\nExplanation: \nEach 1 will produce sum 2 with any 1."
},
{
"code": null,
"e": 826,
"s": 616,
"text": "\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function getPairsCount() which takes arr[], n and k as input parameters and returns the number of pairs that have sum K."
},
{
"code": null,
"e": 950,
"s": 826,
"text": "\nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(N)\n\nConstraints:\n1 <= N <= 105\n1 <= K <= 108\n1 <= Arr[i] <= 106"
},
{
"code": null,
"e": 954,
"s": 952,
"text": "0"
},
{
"code": null,
"e": 970,
"s": 954,
"text": "satan3 days ago"
},
{
"code": null,
"e": 991,
"s": 970,
"text": "Easiest C++ solution"
},
{
"code": null,
"e": 1208,
"s": 991,
"text": "int getPairsCount(int a[], int n, int k) { // code here unordered_map<int,int> m; int c=0; for(int i=0;i<n;i++) { c+=m[k-a[i]]; m[a[i]]++; } return c; }"
},
{
"code": null,
"e": 1210,
"s": 1208,
"text": "0"
},
{
"code": null,
"e": 1231,
"s": 1210,
"text": "ohyeahpiet1 week ago"
},
{
"code": null,
"e": 1539,
"s": 1231,
"text": "class Solution{ public: int getPairsCount(int arr[], int n, int k) { unordered_map<int,int> m; int ans=0; for(int i = 0 ; i < n ; i++){ int val = k - arr[i]; if(m[val]){ ans += m[val]; } m[arr[i]]++; } return ans; }};"
},
{
"code": null,
"e": 1541,
"s": 1539,
"text": "0"
},
{
"code": null,
"e": 1571,
"s": 1541,
"text": "tanishabhadanianve2 weeks ago"
},
{
"code": null,
"e": 1588,
"s": 1571,
"text": "// JAVA SOLUTION"
},
{
"code": null,
"e": 2058,
"s": 1590,
"text": "int getPairsCount(int[] arr, int n, int k) { HashMap<Integer,Integer> map = new HashMap<>(); int count=0; for(int i=0;i<n;i++) { if(map.containsKey(k-arr[i])) { count += map.get(k-arr[i]); } if(!map.containsKey(arr[i])) map.put(arr[i],1); else map.put(arr[i],map.get(arr[i])+1); } return count; }"
},
{
"code": null,
"e": 2061,
"s": 2058,
"text": "+1"
},
{
"code": null,
"e": 2086,
"s": 2061,
"text": "bijeshkumarch2 weeks ago"
},
{
"code": null,
"e": 2094,
"s": 2086,
"text": "#Python"
},
{
"code": null,
"e": 2530,
"s": 2094,
"text": "dct=dict() for i in arr: dct[i]=0 for i in arr: dct[i]+=1 cnt=0 for i in dct.keys(): if 2*i==k and dct[i]>1: cnt+=(dct[i]*(dct[i]-1))//2 dct[i]=0 else: if k-i in dct.keys(): if i==k-i: continue cnt+=(dct[i]*dct[k-i]) dct[i],dct[k-i]=0,0 return cnt"
},
{
"code": null,
"e": 2532,
"s": 2530,
"text": "0"
},
{
"code": null,
"e": 2559,
"s": 2532,
"text": "kousikbarik20002 weeks ago"
},
{
"code": null,
"e": 2812,
"s": 2559,
"text": "def findPairs(arr,target): for i in range(len(arr)): for j in range(i+1,len(arr)): if arr[i] == arr[j]: continue elif arr[i] + arr[j] == target: print(i,j)arr = [1,5,7,1]findPairs(arr,6)"
},
{
"code": null,
"e": 2814,
"s": 2812,
"text": "0"
},
{
"code": null,
"e": 2846,
"s": 2814,
"text": "rajivkumawat280120022 weeks ago"
},
{
"code": null,
"e": 2929,
"s": 2846,
"text": "simple and easy solution in c++........i solve it after 31 attempts..............."
},
{
"code": null,
"e": 3074,
"s": 2931,
"text": " int getPairsCount(int arr[], int n, int k) { // code here sort(arr,arr+n);int flag=0;int count=0;int low=0;int high=n-1;int temp;"
},
{
"code": null,
"e": 3314,
"s": 3074,
"text": "while(low<high){ if(arr[low]+arr[high]==k) { flag=1; count++; temp=high; while(low<high-1) { if(arr[low]+arr[high-1]==k) { count++; } high--; } high=temp; low++; }"
},
{
"code": null,
"e": 3369,
"s": 3314,
"text": " else if(arr[low]+arr[high]>k) { high--; }"
},
{
"code": null,
"e": 3386,
"s": 3369,
"text": " else low++;"
},
{
"code": null,
"e": 3388,
"s": 3386,
"text": "}"
},
{
"code": null,
"e": 3414,
"s": 3388,
"text": "if(flag==0){ return {0};}"
},
{
"code": null,
"e": 3437,
"s": 3414,
"text": "else{ return count;}"
},
{
"code": null,
"e": 3442,
"s": 3437,
"text": " }"
},
{
"code": null,
"e": 3445,
"s": 3442,
"text": "+1"
},
{
"code": null,
"e": 3466,
"s": 3445,
"text": "rajivkumawat28012002"
},
{
"code": null,
"e": 3492,
"s": 3466,
"text": "This comment was deleted."
},
{
"code": null,
"e": 3494,
"s": 3492,
"text": "0"
},
{
"code": null,
"e": 3517,
"s": 3494,
"text": "gautambaddy2 weeks ago"
},
{
"code": null,
"e": 3541,
"s": 3517,
"text": "//optimize the solution"
},
{
"code": null,
"e": 3939,
"s": 3541,
"text": "class Solution{ public: int getPairsCount(int arr[], int n, int k) { // codint k=0; int l=0; int i=0; while( i<n){ for(int j=i+1;j<n;j++){ int sum=0; if (arr[i]<k){ sum=arr[i]+arr[j]; if (sum==k){ l+=1; } } }i++; } return l; }}; "
},
{
"code": null,
"e": 3942,
"s": 3939,
"text": "+1"
},
{
"code": null,
"e": 3976,
"s": 3942,
"text": "deepakprakashjyotisahu2 weeks ago"
},
{
"code": null,
"e": 4267,
"s": 3976,
"text": " //1.HashMap int c=0; HashMap<Integer,Integer>map=new HashMap<>(); for(int i=0;i<arr.length;i++){ if(map.containsKey(k-arr[i])){ c=c+map.get(k-arr[i]); } map.put(arr[i],map.getOrDefault(arr[i],0)+1); } return c;"
},
{
"code": null,
"e": 4270,
"s": 4267,
"text": "+2"
},
{
"code": null,
"e": 4295,
"s": 4270,
"text": "anishmeena0013 weeks ago"
},
{
"code": null,
"e": 4685,
"s": 4295,
"text": "class Solution{ public: int getPairsCount(int arr[], int n, int k) { // code here int ans=0; unordered_map<int,int> m; for(int i=0;i<n;i++) { m[arr[i]]++; } for(int i=0;i<n;i++) { ans+=m[k-arr[i]]; if(k-arr[i]==arr[i]) { ans--; } } return ans/2; }};"
},
{
"code": null,
"e": 4831,
"s": 4685,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 4867,
"s": 4831,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 4877,
"s": 4867,
"text": "\nProblem\n"
},
{
"code": null,
"e": 4887,
"s": 4877,
"text": "\nContest\n"
},
{
"code": null,
"e": 4950,
"s": 4887,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 5098,
"s": 4950,
"text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 5306,
"s": 5098,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints."
},
{
"code": null,
"e": 5412,
"s": 5306,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Boyer Moore Algorithm for Pattern Searching - GeeksforGeeks
|
27 Jan, 2022
Pattern searching is an important problem in computer science. When we do search for a string in a notepad/word file, browser, or database, pattern searching algorithms are used to show the search results. A typical problem statement would be- Given a text txt[0..n-1] and a pattern pat[0..m-1] where n is the length of the text and m is the length of the pattern, write a function search(char pat[], char txt[]) that prints all occurrences of pat[] in txt[]. You may assume that n > m. Examples:
Input: txt[] = "THIS IS A TEST TEXT"
pat[] = "TEST"
Output: Pattern found at index 10
Input: txt[] = "AABAACAADAABAABA"
pat[] = "AABA"
Output: Pattern found at index 0
Pattern found at index 9
Pattern found at index 12
In this post, we will discuss the Boyer Moore pattern searching algorithm. Like KMP and Finite Automata algorithms, Boyer Moore algorithm also preprocesses the pattern. Boyer Moore is a combination of the following two approaches. 1) Bad Character Heuristic 2) Good Suffix Heuristic Both of the above heuristics can also be used independently to search a pattern in a text. Let us first understand how two independent approaches work together in the Boyer Moore algorithm. If we take a look at the Naive algorithm, it slides the pattern over the text one by one. KMP algorithm does preprocessing over the pattern so that the pattern can be shifted by more than one. The Boyer Moore algorithm does preprocessing for the same reason. It processes the pattern and creates different arrays for each of the two heuristics. At every step, it slides the pattern by the max of the slides suggested by each of the two heuristics. So it uses greatest offset suggested by the two heuristics at every step. Unlike the previous pattern searching algorithms, the Boyer Moore algorithm starts matching from the last character of the pattern.In this post, we will discuss the bad character heuristic and the Good Suffix heuristic in the next post.
Bad Character Heuristic
The idea of bad character heuristic is simple. The character of the text which doesn’t match with the current character of the pattern is called the Bad Character. Upon mismatch, we shift the pattern until – 1) The mismatch becomes a match2) Pattern P moves past the mismatched character.Case 1 – Mismatch become match We will lookup the position of the last occurrence of the mismatched character in the pattern, and if the mismatched character exists in the pattern, then we’ll shift the pattern such that it becomes aligned to the mismatched character in the text T.
case 1
Explanation: In the above example, we got a mismatch at position 3. Here our mismatching character is “A”. Now we will search for last occurrence of “A” in pattern. We got “A” at position 1 in pattern (displayed in Blue) and this is the last occurrence of it. Now we will shift pattern 2 times so that “A” in pattern get aligned with “A” in text.Case 2 – Pattern move past the mismatch character We’ll lookup the position of last occurrence of mismatching character in pattern and if character does not exist we will shift pattern past the mismatching character.
case2
Explanation: Here we have a mismatch at position 7. The mismatching character “C” does not exist in pattern before position 7 so we’ll shift pattern past to the position 7 and eventually in above example we have got a perfect match of pattern (displayed in Green). We are doing this because “C” does not exist in the pattern so at every shift before position 7 we will get mismatch and our search will be fruitless.In the following implementation, we preprocess the pattern and store the last occurrence of every possible character in an array of size equal to alphabet size. If the character is not present at all, then it may result in a shift by m (length of pattern). Therefore, the bad character heuristic takes time in the best case.
C++
C
Java
Python3
C#
Javascript
/* C++ Program for Bad Character Heuristic of BoyerMoore String Matching Algorithm */#include <bits/stdc++.h>using namespace std;# define NO_OF_CHARS 256 // The preprocessing function for Boyer Moore's// bad character heuristicvoid badCharHeuristic( string str, int size, int badchar[NO_OF_CHARS]){ int i; // Initialize all occurrences as -1 for (i = 0; i < NO_OF_CHARS; i++) badchar[i] = -1; // Fill the actual value of last occurrence // of a character for (i = 0; i < size; i++) badchar[(int) str[i]] = i;} /* A pattern searching function that uses BadCharacter Heuristic of Boyer Moore Algorithm */void search( string txt, string pat){ int m = pat.size(); int n = txt.size(); int badchar[NO_OF_CHARS]; /* Fill the bad character array by calling the preprocessing function badCharHeuristic() for given pattern */ badCharHeuristic(pat, m, badchar); int s = 0; // s is shift of the pattern with // respect to text while(s <= (n - m)) { int j = m - 1; /* Keep reducing index j of pattern while characters of pattern and text are matching at this shift s */ while(j >= 0 && pat[j] == txt[s + j]) j--; /* If the pattern is present at current shift, then index j will become -1 after the above loop */ if (j < 0) { cout << "pattern occurs at shift = " << s << endl; /* Shift the pattern so that the next character in text aligns with the last occurrence of it in pattern. The condition s+m < n is necessary for the case when pattern occurs at the end of text */ s += (s + m < n)? m-badchar[txt[s + m]] : 1; } else /* Shift the pattern so that the bad character in text aligns with the last occurrence of it in pattern. The max function is used to make sure that we get a positive shift. We may get a negative shift if the last occurrence of bad character in pattern is on the right side of the current character. */ s += max(1, j - badchar[txt[s + j]]); }} /* Driver code */int main(){ string txt= "ABAAABCD"; string pat = "ABC"; search(txt, pat); return 0;} // This code is contributed by rathbhupendra
/* C Program for Bad Character Heuristic of Boyer Moore String Matching Algorithm */# include <limits.h># include <string.h># include <stdio.h> # define NO_OF_CHARS 256 // A utility function to get maximum of two integersint max (int a, int b) { return (a > b)? a: b; } // The preprocessing function for Boyer Moore's// bad character heuristicvoid badCharHeuristic( char *str, int size, int badchar[NO_OF_CHARS]){ int i; // Initialize all occurrences as -1 for (i = 0; i < NO_OF_CHARS; i++) badchar[i] = -1; // Fill the actual value of last occurrence // of a character for (i = 0; i < size; i++) badchar[(int) str[i]] = i;} /* A pattern searching function that uses Bad Character Heuristic of Boyer Moore Algorithm */void search( char *txt, char *pat){ int m = strlen(pat); int n = strlen(txt); int badchar[NO_OF_CHARS]; /* Fill the bad character array by calling the preprocessing function badCharHeuristic() for given pattern */ badCharHeuristic(pat, m, badchar); int s = 0; // s is shift of the pattern with // respect to text while(s <= (n - m)) { int j = m-1; /* Keep reducing index j of pattern while characters of pattern and text are matching at this shift s */ while(j >= 0 && pat[j] == txt[s+j]) j--; /* If the pattern is present at current shift, then index j will become -1 after the above loop */ if (j < 0) { printf("\n pattern occurs at shift = %d", s); /* Shift the pattern so that the next character in text aligns with the last occurrence of it in pattern. The condition s+m < n is necessary for the case when pattern occurs at the end of text */ s += (s+m < n)? m-badchar[txt[s+m]] : 1; } else /* Shift the pattern so that the bad character in text aligns with the last occurrence of it in pattern. The max function is used to make sure that we get a positive shift. We may get a negative shift if the last occurrence of bad character in pattern is on the right side of the current character. */ s += max(1, j - badchar[txt[s+j]]); }} /* Driver program to test above function */int main(){ char txt[] = "ABAAABCD"; char pat[] = "ABC"; search(txt, pat); return 0;}
/* Java Program for Bad Character Heuristic of BoyerMoore String Matching Algorithm */ class AWQ{ static int NO_OF_CHARS = 256; //A utility function to get maximum of two integers static int max (int a, int b) { return (a > b)? a: b; } //The preprocessing function for Boyer Moore's //bad character heuristic static void badCharHeuristic( char []str, int size,int badchar[]) { // Initialize all occurrences as -1 for (int i = 0; i < NO_OF_CHARS; i++) badchar[i] = -1; // Fill the actual value of last occurrence // of a character (indices of table are ascii and values are index of occurrence) for (int i = 0; i < size; i++) badchar[(int) str[i]] = i; } /* A pattern searching function that uses Bad Character Heuristic of Boyer Moore Algorithm */ static void search( char txt[], char pat[]) { int m = pat.length; int n = txt.length; int badchar[] = new int[NO_OF_CHARS]; /* Fill the bad character array by calling the preprocessing function badCharHeuristic() for given pattern */ badCharHeuristic(pat, m, badchar); int s = 0; // s is shift of the pattern with // respect to text //there are n-m+1 potential alignments while(s <= (n - m)) { int j = m-1; /* Keep reducing index j of pattern while characters of pattern and text are matching at this shift s */ while(j >= 0 && pat[j] == txt[s+j]) j--; /* If the pattern is present at current shift, then index j will become -1 after the above loop */ if (j < 0) { System.out.println("Patterns occur at shift = " + s); /* Shift the pattern so that the next character in text aligns with the last occurrence of it in pattern. The condition s+m < n is necessary for the case when pattern occurs at the end of text */ //txt[s+m] is character after the pattern in text s += (s+m < n)? m-badchar[txt[s+m]] : 1; } else /* Shift the pattern so that the bad character in text aligns with the last occurrence of it in pattern. The max function is used to make sure that we get a positive shift. We may get a negative shift if the last occurrence of bad character in pattern is on the right side of the current character. */ s += max(1, j - badchar[txt[s+j]]); } } /* Driver program to test above function */ public static void main(String []args) { char txt[] = "ABAAABCD".toCharArray(); char pat[] = "ABC".toCharArray(); search(txt, pat); }}
# Python3 Program for Bad Character Heuristic# of Boyer Moore String Matching Algorithm NO_OF_CHARS = 256 def badCharHeuristic(string, size): ''' The preprocessing function for Boyer Moore's bad character heuristic ''' # Initialize all occurrence as -1 badChar = [-1]*NO_OF_CHARS # Fill the actual value of last occurrence for i in range(size): badChar[ord(string[i])] = i; # return initialized list return badChar def search(txt, pat): ''' A pattern searching function that uses Bad Character Heuristic of Boyer Moore Algorithm ''' m = len(pat) n = len(txt) # create the bad character list by calling # the preprocessing function badCharHeuristic() # for given pattern badChar = badCharHeuristic(pat, m) # s is shift of the pattern with respect to text s = 0 while(s <= n-m): j = m-1 # Keep reducing index j of pattern while # characters of pattern and text are matching # at this shift s while j>=0 and pat[j] == txt[s+j]: j -= 1 # If the pattern is present at current shift, # then index j will become -1 after the above loop if j<0: print("Pattern occur at shift = {}".format(s)) ''' Shift the pattern so that the next character in text aligns with the last occurrence of it in pattern. The condition s+m < n is necessary for the case when pattern occurs at the end of text ''' s += (m-badChar[ord(txt[s+m])] if s+m<n else 1) else: ''' Shift the pattern so that the bad character in text aligns with the last occurrence of it in pattern. The max function is used to make sure that we get a positive shift. We may get a negative shift if the last occurrence of bad character in pattern is on the right side of the current character. ''' s += max(1, j-badChar[ord(txt[s+j])]) # Driver program to test above functiondef main(): txt = "ABAAABCD" pat = "ABC" search(txt, pat) if __name__ == '__main__': main() # This code is contributed by Atul Kumar# (www.facebook.com/atul.kr.007)
/* C# Program for Bad Character Heuristic of BoyerMoore String Matching Algorithm */ using System;public class AWQ{ static int NO_OF_CHARS = 256; //A utility function to get maximum of two integers static int max (int a, int b) { return (a > b)? a: b; } //The preprocessing function for Boyer Moore's //bad character heuristic static void badCharHeuristic( char []str, int size,int []badchar) { int i; // Initialize all occurrences as -1 for (i = 0; i < NO_OF_CHARS; i++) badchar[i] = -1; // Fill the actual value of last occurrence // of a character for (i = 0; i < size; i++) badchar[(int) str[i]] = i; } /* A pattern searching function that uses Bad Character Heuristic of Boyer Moore Algorithm */ static void search( char []txt, char []pat) { int m = pat.Length; int n = txt.Length; int []badchar = new int[NO_OF_CHARS]; /* Fill the bad character array by calling the preprocessing function badCharHeuristic() for given pattern */ badCharHeuristic(pat, m, badchar); int s = 0; // s is shift of the pattern with // respect to text while(s <= (n - m)) { int j = m-1; /* Keep reducing index j of pattern while characters of pattern and text are matching at this shift s */ while(j >= 0 && pat[j] == txt[s+j]) j--; /* If the pattern is present at current shift, then index j will become -1 after the above loop */ if (j < 0) { Console.WriteLine("Patterns occur at shift = " + s); /* Shift the pattern so that the next character in text aligns with the last occurrence of it in pattern. The condition s+m < n is necessary for the case when pattern occurs at the end of text */ s += (s+m < n)? m-badchar[txt[s+m]] : 1; } else /* Shift the pattern so that the bad character in text aligns with the last occurrence of it in pattern. The max function is used to make sure that we get a positive shift. We may get a negative shift if the last occurrence of bad character in pattern is on the right side of the current character. */ s += max(1, j - badchar[txt[s+j]]); } } /* Driver program to test above function */ public static void Main() { char []txt = "ABAAABCD".ToCharArray(); char []pat = "ABC".ToCharArray(); search(txt, pat); }} // This code is contributed by PrinciRaj19992
<script>/* Javascript Program for Bad Character Heuristic of BoyerMoore String Matching Algorithm */let NO_OF_CHARS = 256; // A utility function to get maximum of two integersfunction max (a,b){ return (a > b)? a: b;} // The preprocessing function for Boyer Moore's// bad character heuristicfunction badCharHeuristic(str,size,badchar){ // Initialize all occurrences as -1 for (let i = 0; i < NO_OF_CHARS; i++) badchar[i] = -1; // Fill the actual value of last occurrence // of a character (indices of table are ascii and values are index of occurrence) for (i = 0; i < size; i++) badchar[ str[i].charCodeAt(0)] = i;} /* A pattern searching function that uses Bad Character Heuristic of Boyer Moore Algorithm */function search(txt,pat){ let m = pat.length; let n = txt.length; let badchar = new Array(NO_OF_CHARS); /* Fill the bad character array by calling the preprocessing function badCharHeuristic() for given pattern */ badCharHeuristic(pat, m, badchar); let s = 0; // s is shift of the pattern with // respect to text // there are n-m+1 potential alignments while(s <= (n - m)) { let j = m-1; /* Keep reducing index j of pattern while characters of pattern and text are matching at this shift s */ while(j >= 0 && pat[j] == txt[s+j]) j--; /* If the pattern is present at current shift, then index j will become -1 after the above loop */ if (j < 0) { document.write("Patterns occur at shift = " + s); /* Shift the pattern so that the next character in text aligns with the last occurrence of it in pattern. The condition s+m < n is necessary for the case when pattern occurs at the end of text */ //txt[s+m] is character after the pattern in text s += (s+m < n)? m-badchar[txt[s+m].charCodeAt(0)] : 1; } else /* Shift the pattern so that the bad character in text aligns with the last occurrence of it in pattern. The max function is used to make sure that we get a positive shift. We may get a negative shift if the last occurrence of bad character in pattern is on the right side of the current character. */ s += max(1, j - badchar[txt[s+j].charCodeAt(0)]); }} /* Driver program to test above function */let txt="ABAAABCD".split("");let pat = "ABC".split("");search(txt, pat); // This code is contributed by unknown2108</script>
Output:
pattern occurs at shift = 4
The Bad Character Heuristic may take time in worst case. The worst case occurs when all characters of the text and pattern are same. For example, txt[] = “AAAAAAAAAAAAAAAAAA” and pat[] = “AAAAA”. The Bad Character Heuristic may take O(n/m) in the best case. The best case occurs when all all the characters of the text and pattern are different.
Boyer Moore Algorithm | Good Suffix heuristicThis article is co-authored by Atul Kumar. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
ukasp
princiraj1992
rathbhupendra
Kirti_Mangal
nidhi_biet
sandellfamily2013
unknown2108
adnanirshad158
ayaankhan98
sweetyty
stryker27
germanshephered48
amartyaghoshgfg
sumitgumber28
Pattern Searching
Strings
Strings
Pattern Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Check if a string is substring of another
Minimize number of cuts required to break N length stick into N unit length sticks
Wildcard Pattern Matching
Check if an URL is valid or not using Regular Expression
Check if a string contains uppercase, lowercase, special characters and numeric values
Reverse a string in Java
Write a program to reverse an array or string
C++ Data Types
Check for Balanced Brackets in an expression (well-formedness) using Stack
Python program to check if a string is palindrome or not
|
[
{
"code": null,
"e": 34594,
"s": 34566,
"text": "\n27 Jan, 2022"
},
{
"code": null,
"e": 35092,
"s": 34594,
"text": "Pattern searching is an important problem in computer science. When we do search for a string in a notepad/word file, browser, or database, pattern searching algorithms are used to show the search results. A typical problem statement would be- Given a text txt[0..n-1] and a pattern pat[0..m-1] where n is the length of the text and m is the length of the pattern, write a function search(char pat[], char txt[]) that prints all occurrences of pat[] in txt[]. You may assume that n > m. Examples: "
},
{
"code": null,
"e": 35348,
"s": 35092,
"text": "Input: txt[] = \"THIS IS A TEST TEXT\"\n pat[] = \"TEST\"\nOutput: Pattern found at index 10\n\nInput: txt[] = \"AABAACAADAABAABA\"\n pat[] = \"AABA\"\nOutput: Pattern found at index 0\n Pattern found at index 9\n Pattern found at index 12"
},
{
"code": null,
"e": 36582,
"s": 35348,
"text": "In this post, we will discuss the Boyer Moore pattern searching algorithm. Like KMP and Finite Automata algorithms, Boyer Moore algorithm also preprocesses the pattern. Boyer Moore is a combination of the following two approaches. 1) Bad Character Heuristic 2) Good Suffix Heuristic Both of the above heuristics can also be used independently to search a pattern in a text. Let us first understand how two independent approaches work together in the Boyer Moore algorithm. If we take a look at the Naive algorithm, it slides the pattern over the text one by one. KMP algorithm does preprocessing over the pattern so that the pattern can be shifted by more than one. The Boyer Moore algorithm does preprocessing for the same reason. It processes the pattern and creates different arrays for each of the two heuristics. At every step, it slides the pattern by the max of the slides suggested by each of the two heuristics. So it uses greatest offset suggested by the two heuristics at every step. Unlike the previous pattern searching algorithms, the Boyer Moore algorithm starts matching from the last character of the pattern.In this post, we will discuss the bad character heuristic and the Good Suffix heuristic in the next post. "
},
{
"code": null,
"e": 36606,
"s": 36582,
"text": "Bad Character Heuristic"
},
{
"code": null,
"e": 37178,
"s": 36606,
"text": "The idea of bad character heuristic is simple. The character of the text which doesn’t match with the current character of the pattern is called the Bad Character. Upon mismatch, we shift the pattern until – 1) The mismatch becomes a match2) Pattern P moves past the mismatched character.Case 1 – Mismatch become match We will lookup the position of the last occurrence of the mismatched character in the pattern, and if the mismatched character exists in the pattern, then we’ll shift the pattern such that it becomes aligned to the mismatched character in the text T. "
},
{
"code": null,
"e": 37185,
"s": 37178,
"text": "case 1"
},
{
"code": null,
"e": 37750,
"s": 37185,
"text": "Explanation: In the above example, we got a mismatch at position 3. Here our mismatching character is “A”. Now we will search for last occurrence of “A” in pattern. We got “A” at position 1 in pattern (displayed in Blue) and this is the last occurrence of it. Now we will shift pattern 2 times so that “A” in pattern get aligned with “A” in text.Case 2 – Pattern move past the mismatch character We’ll lookup the position of last occurrence of mismatching character in pattern and if character does not exist we will shift pattern past the mismatching character. "
},
{
"code": null,
"e": 37756,
"s": 37750,
"text": "case2"
},
{
"code": null,
"e": 38498,
"s": 37756,
"text": "Explanation: Here we have a mismatch at position 7. The mismatching character “C” does not exist in pattern before position 7 so we’ll shift pattern past to the position 7 and eventually in above example we have got a perfect match of pattern (displayed in Green). We are doing this because “C” does not exist in the pattern so at every shift before position 7 we will get mismatch and our search will be fruitless.In the following implementation, we preprocess the pattern and store the last occurrence of every possible character in an array of size equal to alphabet size. If the character is not present at all, then it may result in a shift by m (length of pattern). Therefore, the bad character heuristic takes time in the best case. "
},
{
"code": null,
"e": 38502,
"s": 38498,
"text": "C++"
},
{
"code": null,
"e": 38504,
"s": 38502,
"text": "C"
},
{
"code": null,
"e": 38509,
"s": 38504,
"text": "Java"
},
{
"code": null,
"e": 38517,
"s": 38509,
"text": "Python3"
},
{
"code": null,
"e": 38520,
"s": 38517,
"text": "C#"
},
{
"code": null,
"e": 38531,
"s": 38520,
"text": "Javascript"
},
{
"code": "/* C++ Program for Bad Character Heuristic of BoyerMoore String Matching Algorithm */#include <bits/stdc++.h>using namespace std;# define NO_OF_CHARS 256 // The preprocessing function for Boyer Moore's// bad character heuristicvoid badCharHeuristic( string str, int size, int badchar[NO_OF_CHARS]){ int i; // Initialize all occurrences as -1 for (i = 0; i < NO_OF_CHARS; i++) badchar[i] = -1; // Fill the actual value of last occurrence // of a character for (i = 0; i < size; i++) badchar[(int) str[i]] = i;} /* A pattern searching function that uses BadCharacter Heuristic of Boyer Moore Algorithm */void search( string txt, string pat){ int m = pat.size(); int n = txt.size(); int badchar[NO_OF_CHARS]; /* Fill the bad character array by calling the preprocessing function badCharHeuristic() for given pattern */ badCharHeuristic(pat, m, badchar); int s = 0; // s is shift of the pattern with // respect to text while(s <= (n - m)) { int j = m - 1; /* Keep reducing index j of pattern while characters of pattern and text are matching at this shift s */ while(j >= 0 && pat[j] == txt[s + j]) j--; /* If the pattern is present at current shift, then index j will become -1 after the above loop */ if (j < 0) { cout << \"pattern occurs at shift = \" << s << endl; /* Shift the pattern so that the next character in text aligns with the last occurrence of it in pattern. The condition s+m < n is necessary for the case when pattern occurs at the end of text */ s += (s + m < n)? m-badchar[txt[s + m]] : 1; } else /* Shift the pattern so that the bad character in text aligns with the last occurrence of it in pattern. The max function is used to make sure that we get a positive shift. We may get a negative shift if the last occurrence of bad character in pattern is on the right side of the current character. */ s += max(1, j - badchar[txt[s + j]]); }} /* Driver code */int main(){ string txt= \"ABAAABCD\"; string pat = \"ABC\"; search(txt, pat); return 0;} // This code is contributed by rathbhupendra",
"e": 40942,
"s": 38531,
"text": null
},
{
"code": "/* C Program for Bad Character Heuristic of Boyer Moore String Matching Algorithm */# include <limits.h># include <string.h># include <stdio.h> # define NO_OF_CHARS 256 // A utility function to get maximum of two integersint max (int a, int b) { return (a > b)? a: b; } // The preprocessing function for Boyer Moore's// bad character heuristicvoid badCharHeuristic( char *str, int size, int badchar[NO_OF_CHARS]){ int i; // Initialize all occurrences as -1 for (i = 0; i < NO_OF_CHARS; i++) badchar[i] = -1; // Fill the actual value of last occurrence // of a character for (i = 0; i < size; i++) badchar[(int) str[i]] = i;} /* A pattern searching function that uses Bad Character Heuristic of Boyer Moore Algorithm */void search( char *txt, char *pat){ int m = strlen(pat); int n = strlen(txt); int badchar[NO_OF_CHARS]; /* Fill the bad character array by calling the preprocessing function badCharHeuristic() for given pattern */ badCharHeuristic(pat, m, badchar); int s = 0; // s is shift of the pattern with // respect to text while(s <= (n - m)) { int j = m-1; /* Keep reducing index j of pattern while characters of pattern and text are matching at this shift s */ while(j >= 0 && pat[j] == txt[s+j]) j--; /* If the pattern is present at current shift, then index j will become -1 after the above loop */ if (j < 0) { printf(\"\\n pattern occurs at shift = %d\", s); /* Shift the pattern so that the next character in text aligns with the last occurrence of it in pattern. The condition s+m < n is necessary for the case when pattern occurs at the end of text */ s += (s+m < n)? m-badchar[txt[s+m]] : 1; } else /* Shift the pattern so that the bad character in text aligns with the last occurrence of it in pattern. The max function is used to make sure that we get a positive shift. We may get a negative shift if the last occurrence of bad character in pattern is on the right side of the current character. */ s += max(1, j - badchar[txt[s+j]]); }} /* Driver program to test above function */int main(){ char txt[] = \"ABAAABCD\"; char pat[] = \"ABC\"; search(txt, pat); return 0;}",
"e": 43496,
"s": 40942,
"text": null
},
{
"code": "/* Java Program for Bad Character Heuristic of BoyerMoore String Matching Algorithm */ class AWQ{ static int NO_OF_CHARS = 256; //A utility function to get maximum of two integers static int max (int a, int b) { return (a > b)? a: b; } //The preprocessing function for Boyer Moore's //bad character heuristic static void badCharHeuristic( char []str, int size,int badchar[]) { // Initialize all occurrences as -1 for (int i = 0; i < NO_OF_CHARS; i++) badchar[i] = -1; // Fill the actual value of last occurrence // of a character (indices of table are ascii and values are index of occurrence) for (int i = 0; i < size; i++) badchar[(int) str[i]] = i; } /* A pattern searching function that uses Bad Character Heuristic of Boyer Moore Algorithm */ static void search( char txt[], char pat[]) { int m = pat.length; int n = txt.length; int badchar[] = new int[NO_OF_CHARS]; /* Fill the bad character array by calling the preprocessing function badCharHeuristic() for given pattern */ badCharHeuristic(pat, m, badchar); int s = 0; // s is shift of the pattern with // respect to text //there are n-m+1 potential alignments while(s <= (n - m)) { int j = m-1; /* Keep reducing index j of pattern while characters of pattern and text are matching at this shift s */ while(j >= 0 && pat[j] == txt[s+j]) j--; /* If the pattern is present at current shift, then index j will become -1 after the above loop */ if (j < 0) { System.out.println(\"Patterns occur at shift = \" + s); /* Shift the pattern so that the next character in text aligns with the last occurrence of it in pattern. The condition s+m < n is necessary for the case when pattern occurs at the end of text */ //txt[s+m] is character after the pattern in text s += (s+m < n)? m-badchar[txt[s+m]] : 1; } else /* Shift the pattern so that the bad character in text aligns with the last occurrence of it in pattern. The max function is used to make sure that we get a positive shift. We may get a negative shift if the last occurrence of bad character in pattern is on the right side of the current character. */ s += max(1, j - badchar[txt[s+j]]); } } /* Driver program to test above function */ public static void main(String []args) { char txt[] = \"ABAAABCD\".toCharArray(); char pat[] = \"ABC\".toCharArray(); search(txt, pat); }}",
"e": 46432,
"s": 43496,
"text": null
},
{
"code": "# Python3 Program for Bad Character Heuristic# of Boyer Moore String Matching Algorithm NO_OF_CHARS = 256 def badCharHeuristic(string, size): ''' The preprocessing function for Boyer Moore's bad character heuristic ''' # Initialize all occurrence as -1 badChar = [-1]*NO_OF_CHARS # Fill the actual value of last occurrence for i in range(size): badChar[ord(string[i])] = i; # return initialized list return badChar def search(txt, pat): ''' A pattern searching function that uses Bad Character Heuristic of Boyer Moore Algorithm ''' m = len(pat) n = len(txt) # create the bad character list by calling # the preprocessing function badCharHeuristic() # for given pattern badChar = badCharHeuristic(pat, m) # s is shift of the pattern with respect to text s = 0 while(s <= n-m): j = m-1 # Keep reducing index j of pattern while # characters of pattern and text are matching # at this shift s while j>=0 and pat[j] == txt[s+j]: j -= 1 # If the pattern is present at current shift, # then index j will become -1 after the above loop if j<0: print(\"Pattern occur at shift = {}\".format(s)) ''' Shift the pattern so that the next character in text aligns with the last occurrence of it in pattern. The condition s+m < n is necessary for the case when pattern occurs at the end of text ''' s += (m-badChar[ord(txt[s+m])] if s+m<n else 1) else: ''' Shift the pattern so that the bad character in text aligns with the last occurrence of it in pattern. The max function is used to make sure that we get a positive shift. We may get a negative shift if the last occurrence of bad character in pattern is on the right side of the current character. ''' s += max(1, j-badChar[ord(txt[s+j])]) # Driver program to test above functiondef main(): txt = \"ABAAABCD\" pat = \"ABC\" search(txt, pat) if __name__ == '__main__': main() # This code is contributed by Atul Kumar# (www.facebook.com/atul.kr.007)",
"e": 48721,
"s": 46432,
"text": null
},
{
"code": "/* C# Program for Bad Character Heuristic of BoyerMoore String Matching Algorithm */ using System;public class AWQ{ static int NO_OF_CHARS = 256; //A utility function to get maximum of two integers static int max (int a, int b) { return (a > b)? a: b; } //The preprocessing function for Boyer Moore's //bad character heuristic static void badCharHeuristic( char []str, int size,int []badchar) { int i; // Initialize all occurrences as -1 for (i = 0; i < NO_OF_CHARS; i++) badchar[i] = -1; // Fill the actual value of last occurrence // of a character for (i = 0; i < size; i++) badchar[(int) str[i]] = i; } /* A pattern searching function that uses Bad Character Heuristic of Boyer Moore Algorithm */ static void search( char []txt, char []pat) { int m = pat.Length; int n = txt.Length; int []badchar = new int[NO_OF_CHARS]; /* Fill the bad character array by calling the preprocessing function badCharHeuristic() for given pattern */ badCharHeuristic(pat, m, badchar); int s = 0; // s is shift of the pattern with // respect to text while(s <= (n - m)) { int j = m-1; /* Keep reducing index j of pattern while characters of pattern and text are matching at this shift s */ while(j >= 0 && pat[j] == txt[s+j]) j--; /* If the pattern is present at current shift, then index j will become -1 after the above loop */ if (j < 0) { Console.WriteLine(\"Patterns occur at shift = \" + s); /* Shift the pattern so that the next character in text aligns with the last occurrence of it in pattern. The condition s+m < n is necessary for the case when pattern occurs at the end of text */ s += (s+m < n)? m-badchar[txt[s+m]] : 1; } else /* Shift the pattern so that the bad character in text aligns with the last occurrence of it in pattern. The max function is used to make sure that we get a positive shift. We may get a negative shift if the last occurrence of bad character in pattern is on the right side of the current character. */ s += max(1, j - badchar[txt[s+j]]); } } /* Driver program to test above function */ public static void Main() { char []txt = \"ABAAABCD\".ToCharArray(); char []pat = \"ABC\".ToCharArray(); search(txt, pat); }} // This code is contributed by PrinciRaj19992",
"e": 51434,
"s": 48721,
"text": null
},
{
"code": "<script>/* Javascript Program for Bad Character Heuristic of BoyerMoore String Matching Algorithm */let NO_OF_CHARS = 256; // A utility function to get maximum of two integersfunction max (a,b){ return (a > b)? a: b;} // The preprocessing function for Boyer Moore's// bad character heuristicfunction badCharHeuristic(str,size,badchar){ // Initialize all occurrences as -1 for (let i = 0; i < NO_OF_CHARS; i++) badchar[i] = -1; // Fill the actual value of last occurrence // of a character (indices of table are ascii and values are index of occurrence) for (i = 0; i < size; i++) badchar[ str[i].charCodeAt(0)] = i;} /* A pattern searching function that uses Bad Character Heuristic of Boyer Moore Algorithm */function search(txt,pat){ let m = pat.length; let n = txt.length; let badchar = new Array(NO_OF_CHARS); /* Fill the bad character array by calling the preprocessing function badCharHeuristic() for given pattern */ badCharHeuristic(pat, m, badchar); let s = 0; // s is shift of the pattern with // respect to text // there are n-m+1 potential alignments while(s <= (n - m)) { let j = m-1; /* Keep reducing index j of pattern while characters of pattern and text are matching at this shift s */ while(j >= 0 && pat[j] == txt[s+j]) j--; /* If the pattern is present at current shift, then index j will become -1 after the above loop */ if (j < 0) { document.write(\"Patterns occur at shift = \" + s); /* Shift the pattern so that the next character in text aligns with the last occurrence of it in pattern. The condition s+m < n is necessary for the case when pattern occurs at the end of text */ //txt[s+m] is character after the pattern in text s += (s+m < n)? m-badchar[txt[s+m].charCodeAt(0)] : 1; } else /* Shift the pattern so that the bad character in text aligns with the last occurrence of it in pattern. The max function is used to make sure that we get a positive shift. We may get a negative shift if the last occurrence of bad character in pattern is on the right side of the current character. */ s += max(1, j - badchar[txt[s+j].charCodeAt(0)]); }} /* Driver program to test above function */let txt=\"ABAAABCD\".split(\"\");let pat = \"ABC\".split(\"\");search(txt, pat); // This code is contributed by unknown2108</script>",
"e": 54226,
"s": 51434,
"text": null
},
{
"code": null,
"e": 54235,
"s": 54226,
"text": "Output: "
},
{
"code": null,
"e": 54264,
"s": 54235,
"text": " pattern occurs at shift = 4"
},
{
"code": null,
"e": 54611,
"s": 54264,
"text": "The Bad Character Heuristic may take time in worst case. The worst case occurs when all characters of the text and pattern are same. For example, txt[] = “AAAAAAAAAAAAAAAAAA” and pat[] = “AAAAA”. The Bad Character Heuristic may take O(n/m) in the best case. The best case occurs when all all the characters of the text and pattern are different. "
},
{
"code": null,
"e": 54825,
"s": 54611,
"text": "Boyer Moore Algorithm | Good Suffix heuristicThis article is co-authored by Atul Kumar. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 54831,
"s": 54825,
"text": "ukasp"
},
{
"code": null,
"e": 54845,
"s": 54831,
"text": "princiraj1992"
},
{
"code": null,
"e": 54859,
"s": 54845,
"text": "rathbhupendra"
},
{
"code": null,
"e": 54872,
"s": 54859,
"text": "Kirti_Mangal"
},
{
"code": null,
"e": 54883,
"s": 54872,
"text": "nidhi_biet"
},
{
"code": null,
"e": 54901,
"s": 54883,
"text": "sandellfamily2013"
},
{
"code": null,
"e": 54913,
"s": 54901,
"text": "unknown2108"
},
{
"code": null,
"e": 54928,
"s": 54913,
"text": "adnanirshad158"
},
{
"code": null,
"e": 54940,
"s": 54928,
"text": "ayaankhan98"
},
{
"code": null,
"e": 54949,
"s": 54940,
"text": "sweetyty"
},
{
"code": null,
"e": 54959,
"s": 54949,
"text": "stryker27"
},
{
"code": null,
"e": 54977,
"s": 54959,
"text": "germanshephered48"
},
{
"code": null,
"e": 54993,
"s": 54977,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 55007,
"s": 54993,
"text": "sumitgumber28"
},
{
"code": null,
"e": 55025,
"s": 55007,
"text": "Pattern Searching"
},
{
"code": null,
"e": 55033,
"s": 55025,
"text": "Strings"
},
{
"code": null,
"e": 55041,
"s": 55033,
"text": "Strings"
},
{
"code": null,
"e": 55059,
"s": 55041,
"text": "Pattern Searching"
},
{
"code": null,
"e": 55157,
"s": 55059,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 55199,
"s": 55157,
"text": "Check if a string is substring of another"
},
{
"code": null,
"e": 55282,
"s": 55199,
"text": "Minimize number of cuts required to break N length stick into N unit length sticks"
},
{
"code": null,
"e": 55308,
"s": 55282,
"text": "Wildcard Pattern Matching"
},
{
"code": null,
"e": 55365,
"s": 55308,
"text": "Check if an URL is valid or not using Regular Expression"
},
{
"code": null,
"e": 55452,
"s": 55365,
"text": "Check if a string contains uppercase, lowercase, special characters and numeric values"
},
{
"code": null,
"e": 55477,
"s": 55452,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 55523,
"s": 55477,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 55538,
"s": 55523,
"text": "C++ Data Types"
},
{
"code": null,
"e": 55613,
"s": 55538,
"text": "Check for Balanced Brackets in an expression (well-formedness) using Stack"
}
] |
Python - Sort by Uppercase Frequency - GeeksforGeeks
|
24 Oct, 2020
Given a list of strings, perform sorting by frequency of uppercase characters.
Input : test_list = [“Gfg”, “is”, “FoR”, “GEEKS”] Output : [‘is’, ‘Gfg’, ‘FoR’, ‘GEEKS’] Explanation : 0, 1, 2, 5 uppercase letters in strings respectively.
Input : test_list = [“is”, “GEEKS”] Output : [‘is’, ‘GEEKS’] Explanation : 0, 5 uppercase letters in strings respectively.
Method #1 : Using sort() + isupper()
In this, we perform task of checking for uppercase using isupper(), and sort() to perform task of sorting.
Python3
# Python3 code to demonstrate working of# Sort by Uppercase Frequency# Using isupper() + sort() # helper functiondef upper_sort(sub): # len() to get total uppercase characters return len([ele for ele in sub if ele.isupper()]) # initializing listtest_list = ["Gfg", "is", "BEST", "FoR", "GEEKS"] # printing original listprint("The original list is: " + str(test_list)) # using external function to perform sortingtest_list.sort(key=upper_sort) # printing resultprint("Elements after uppercase sorting: " + str(test_list))
Output:
The original list is: ['Gfg', 'is', 'BEST', 'FoR', 'GEEKS']
Elements after uppercase sorting: ['is', 'Gfg', 'FoR', 'BEST', 'GEEKS']
Method #2 : Using sorted() + lambda function
In this, we perform the task of sorting using sorted(), and lambda function is used rather than external sort() function to perform task of sorting.
Python3
# Python3 code to demonstrate working of# Sort by Uppercase Frequency# Using sorted() + lambda function # initializing listtest_list = ["Gfg", "is", "BEST", "FoR", "GEEKS"] # printing original listprint("The original list is: " + str(test_list)) # sorted() + lambda function used to solve problemres = sorted(test_list, key=lambda sub: len( [ele for ele in sub if ele.isupper()])) # printing resultprint("Elements after uppercase sorting: " + str(res))
Output:
The original list is: ['Gfg', 'is', 'BEST', 'FoR', 'GEEKS']
Elements after uppercase sorting: ['is', 'Gfg', 'FoR', 'BEST', 'GEEKS']
Python list-programs
Python string-programs
Python
Python Programs
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 program to convert a list to string
Defaultdict in Python
Python | Split string into list of characters
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
|
[
{
"code": null,
"e": 24668,
"s": 24640,
"text": "\n24 Oct, 2020"
},
{
"code": null,
"e": 24748,
"s": 24668,
"text": "Given a list of strings, perform sorting by frequency of uppercase characters. "
},
{
"code": null,
"e": 24906,
"s": 24748,
"text": "Input : test_list = [“Gfg”, “is”, “FoR”, “GEEKS”] Output : [‘is’, ‘Gfg’, ‘FoR’, ‘GEEKS’] Explanation : 0, 1, 2, 5 uppercase letters in strings respectively. "
},
{
"code": null,
"e": 25030,
"s": 24906,
"text": "Input : test_list = [“is”, “GEEKS”] Output : [‘is’, ‘GEEKS’] Explanation : 0, 5 uppercase letters in strings respectively. "
},
{
"code": null,
"e": 25067,
"s": 25030,
"text": "Method #1 : Using sort() + isupper()"
},
{
"code": null,
"e": 25174,
"s": 25067,
"text": "In this, we perform task of checking for uppercase using isupper(), and sort() to perform task of sorting."
},
{
"code": null,
"e": 25182,
"s": 25174,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Sort by Uppercase Frequency# Using isupper() + sort() # helper functiondef upper_sort(sub): # len() to get total uppercase characters return len([ele for ele in sub if ele.isupper()]) # initializing listtest_list = [\"Gfg\", \"is\", \"BEST\", \"FoR\", \"GEEKS\"] # printing original listprint(\"The original list is: \" + str(test_list)) # using external function to perform sortingtest_list.sort(key=upper_sort) # printing resultprint(\"Elements after uppercase sorting: \" + str(test_list))",
"e": 25720,
"s": 25182,
"text": null
},
{
"code": null,
"e": 25728,
"s": 25720,
"text": "Output:"
},
{
"code": null,
"e": 25860,
"s": 25728,
"text": "The original list is: ['Gfg', 'is', 'BEST', 'FoR', 'GEEKS']\nElements after uppercase sorting: ['is', 'Gfg', 'FoR', 'BEST', 'GEEKS']"
},
{
"code": null,
"e": 25905,
"s": 25860,
"text": "Method #2 : Using sorted() + lambda function"
},
{
"code": null,
"e": 26054,
"s": 25905,
"text": "In this, we perform the task of sorting using sorted(), and lambda function is used rather than external sort() function to perform task of sorting."
},
{
"code": null,
"e": 26062,
"s": 26054,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Sort by Uppercase Frequency# Using sorted() + lambda function # initializing listtest_list = [\"Gfg\", \"is\", \"BEST\", \"FoR\", \"GEEKS\"] # printing original listprint(\"The original list is: \" + str(test_list)) # sorted() + lambda function used to solve problemres = sorted(test_list, key=lambda sub: len( [ele for ele in sub if ele.isupper()])) # printing resultprint(\"Elements after uppercase sorting: \" + str(res))",
"e": 26524,
"s": 26062,
"text": null
},
{
"code": null,
"e": 26532,
"s": 26524,
"text": "Output:"
},
{
"code": null,
"e": 26664,
"s": 26532,
"text": "The original list is: ['Gfg', 'is', 'BEST', 'FoR', 'GEEKS']\nElements after uppercase sorting: ['is', 'Gfg', 'FoR', 'BEST', 'GEEKS']"
},
{
"code": null,
"e": 26685,
"s": 26664,
"text": "Python list-programs"
},
{
"code": null,
"e": 26708,
"s": 26685,
"text": "Python string-programs"
},
{
"code": null,
"e": 26715,
"s": 26708,
"text": "Python"
},
{
"code": null,
"e": 26731,
"s": 26715,
"text": "Python Programs"
},
{
"code": null,
"e": 26829,
"s": 26731,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26847,
"s": 26829,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26882,
"s": 26847,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 26904,
"s": 26882,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 26936,
"s": 26904,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26966,
"s": 26936,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 27009,
"s": 26966,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 27031,
"s": 27009,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27077,
"s": 27031,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 27116,
"s": 27077,
"text": "Python | Get dictionary keys as a list"
}
] |
How do we stash changes in Git?
|
This question can be rephrased as "How to save work in progress (WIP) in Git and return to it later when convenient?"
The problem − When we switch branches, Git resets our working directory to contain the snapshot stored in the last commit of the target branch. For example, if we switch from feature to the master branch, Git will replace contents in the working directory with the last commit of the master branch. But if we have local changes in our working directory that we haven't committed yet, these changes will be lost. In this situation, Git will not allow us to switch branches. Let us see how this happens and how we should solve this.
Example − Create an empty repository and execute the commands given below. The example shows that we are working in a feature branch, editing and adding files. Suddenly, we might have to switch to the master for an immediate bugfix in the master branch. It will not allow us to switch to the master branch as we have some work in progress (WIP) in featurebranch.
$ git init // initialize an empty repo
$ echo abc>abc.txt // create a file and add some text to it
$ git add abc.txt // stage the file
$ git commit −m abc.txt // commit changes to the repo
$ git checkout feature // Switch to the feature branch
$ git log −−oneline // Display commit history
$ echo lmno>lmno.txt // create a file and add some text
$ git add lmno.txt // stage the file
$ git commit −m 'save lmno' // commit changes to the repo
$ echo lmno lmno>>lmno.txt // append data to the file
$ git checkout master // Switch to the master branch
Git prompts us to stash the changes when we try to switch the branch.
delI@DESKTOP-N961NR5 MINGW64 —/Desktop/Internship/Batch_01/Session03/git/test-re
po (feature)
$ git checkout master
error: Your local changes to the following files would be overwritten by checkout
Imno. txt
please commit your changes or stash them before you switch branches.
Aborting
We don't want to commit our changes as we are not done yet. In situations like this we need to stash our changes. Stashing means storing things in a safe place. We are going to store this in a separate stash area in the Git repository. Stashing will not be a part of our history. Let us see how it works.
The following command pushes the work that is lying in the staging area and is pending to be committed into a stash. The −m flag is used to provide a stash message.
$ git stash push −m 'working on lmno file not completed '
By default, untracked files are not included in your stash. To push untracked files, i.e., files in the working directory, we need to include the option −am flag. Let us see an example −
$ echo hello > newfile.txt //create a file in the working area
$ git stash push −am 'my new stash' //push untracked files into the stash
To view all the stashes, use the command − git stash list
$ git stash list
The command returns all stashes. Note that the latest stash will be listed at the top of the list, i.e., at index 0.
stash@{0}: On feature: my new stash
stash@{1}: On feature: working on lmno file not completed
After stashing, the working tree will be clean. Now the collaborator can switch to any other branch and do some important work. Once done, the collaborator can switch back to the feature branch again. At this point, we decide to apply one of the stashes to our working directory.
To apply stashed changes back to our working directory we can use the following command −
$ git stash apply <index_number>
The following example applies stash sequences at index 0 and index 1
$ git stash apply 0
$ git stash apply 1
The output shows that the stashes have been applied and now our working directory will contain all changes as expected.
dell@DESKTOP−N96LNR5 MINGw64 /e/tut_repo (feature)
$ git stash apply 0
Al ready up to date!
On branch feature
untracked files:
(use ''git add <file>... " to include in what will be committed)
newfile. txt
nothing added to commit but untracked fi les present
dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (feature)
$ git stash apply 1
On branch feature
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git restore <file>... " to discard changes in working directory)
modified: Imno.txt
untracked files:
(use "git add <file>... " to include in what will be committed)
no changes added to commit (use "git add" and/or "git commit −a")
We can verify contents of our working directory using the following commands −
$ ls // lists contents of the current directory
$ cat newfile.txt // lists contents of newfile.txt
$ cat lmno.txt // list contents of lmno.txt
The output is as shown below −
//output of ls
abc.txt lmno.txt newfile.txt
//output of cat newfile.txt
hello
//output of cat lmno.txt
lmno
lmno lmno
Once stashes are applied successfully, we may need to clean up things as stashes are not removed by default. We can use the following command to drop a specific stash.
$ git stash drop 0
To clear entire contents in the stash in one go, we can use the following command
$ git stash clear
|
[
{
"code": null,
"e": 1180,
"s": 1062,
"text": "This question can be rephrased as \"How to save work in progress (WIP) in Git and return to it later when convenient?\""
},
{
"code": null,
"e": 1711,
"s": 1180,
"text": "The problem − When we switch branches, Git resets our working directory to contain the snapshot stored in the last commit of the target branch. For example, if we switch from feature to the master branch, Git will replace contents in the working directory with the last commit of the master branch. But if we have local changes in our working directory that we haven't committed yet, these changes will be lost. In this situation, Git will not allow us to switch branches. Let us see how this happens and how we should solve this."
},
{
"code": null,
"e": 2074,
"s": 1711,
"text": "Example − Create an empty repository and execute the commands given below. The example shows that we are working in a feature branch, editing and adding files. Suddenly, we might have to switch to the master for an immediate bugfix in the master branch. It will not allow us to switch to the master branch as we have some work in progress (WIP) in featurebranch."
},
{
"code": null,
"e": 2698,
"s": 2074,
"text": "$ git init // initialize an empty repo\n$ echo abc>abc.txt // create a file and add some text to it\n$ git add abc.txt // stage the file\n$ git commit −m abc.txt // commit changes to the repo\n$ git checkout feature // Switch to the feature branch\n$ git log −−oneline // Display commit history\n$ echo lmno>lmno.txt // create a file and add some text\n$ git add lmno.txt // stage the file\n$ git commit −m 'save lmno' // commit changes to the repo\n$ echo lmno lmno>>lmno.txt // append data to the file\n$ git checkout master // Switch to the master branch"
},
{
"code": null,
"e": 2768,
"s": 2698,
"text": "Git prompts us to stash the changes when we try to switch the branch."
},
{
"code": null,
"e": 3054,
"s": 2768,
"text": "delI@DESKTOP-N961NR5 MINGW64 —/Desktop/Internship/Batch_01/Session03/git/test-re\npo (feature)\n$ git checkout master\nerror: Your local changes to the following files would be overwritten by checkout\nImno. txt\nplease commit your changes or stash them before you switch branches.\nAborting"
},
{
"code": null,
"e": 3359,
"s": 3054,
"text": "We don't want to commit our changes as we are not done yet. In situations like this we need to stash our changes. Stashing means storing things in a safe place. We are going to store this in a separate stash area in the Git repository. Stashing will not be a part of our history. Let us see how it works."
},
{
"code": null,
"e": 3524,
"s": 3359,
"text": "The following command pushes the work that is lying in the staging area and is pending to be committed into a stash. The −m flag is used to provide a stash message."
},
{
"code": null,
"e": 3582,
"s": 3524,
"text": "$ git stash push −m 'working on lmno file not completed '"
},
{
"code": null,
"e": 3769,
"s": 3582,
"text": "By default, untracked files are not included in your stash. To push untracked files, i.e., files in the working directory, we need to include the option −am flag. Let us see an example −"
},
{
"code": null,
"e": 3906,
"s": 3769,
"text": "$ echo hello > newfile.txt //create a file in the working area\n$ git stash push −am 'my new stash' //push untracked files into the stash"
},
{
"code": null,
"e": 3964,
"s": 3906,
"text": "To view all the stashes, use the command − git stash list"
},
{
"code": null,
"e": 3981,
"s": 3964,
"text": "$ git stash list"
},
{
"code": null,
"e": 4098,
"s": 3981,
"text": "The command returns all stashes. Note that the latest stash will be listed at the top of the list, i.e., at index 0."
},
{
"code": null,
"e": 4192,
"s": 4098,
"text": "stash@{0}: On feature: my new stash\nstash@{1}: On feature: working on lmno file not completed"
},
{
"code": null,
"e": 4472,
"s": 4192,
"text": "After stashing, the working tree will be clean. Now the collaborator can switch to any other branch and do some important work. Once done, the collaborator can switch back to the feature branch again. At this point, we decide to apply one of the stashes to our working directory."
},
{
"code": null,
"e": 4562,
"s": 4472,
"text": "To apply stashed changes back to our working directory we can use the following command −"
},
{
"code": null,
"e": 4595,
"s": 4562,
"text": "$ git stash apply <index_number>"
},
{
"code": null,
"e": 4664,
"s": 4595,
"text": "The following example applies stash sequences at index 0 and index 1"
},
{
"code": null,
"e": 4704,
"s": 4664,
"text": "$ git stash apply 0\n$ git stash apply 1"
},
{
"code": null,
"e": 4824,
"s": 4704,
"text": "The output shows that the stashes have been applied and now our working directory will contain all changes as expected."
},
{
"code": null,
"e": 5500,
"s": 4824,
"text": "dell@DESKTOP−N96LNR5 MINGw64 /e/tut_repo (feature)\n$ git stash apply 0\nAl ready up to date!\nOn branch feature\nuntracked files:\n(use ''git add <file>... \" to include in what will be committed)\n\nnewfile. txt\nnothing added to commit but untracked fi les present\n\ndell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (feature)\n$ git stash apply 1\nOn branch feature\nChanges not staged for commit:\n(use \"git add <file>...\" to update what will be committed)\n(use \"git restore <file>... \" to discard changes in working directory)\nmodified: Imno.txt\nuntracked files:\n(use \"git add <file>... \" to include in what will be committed)\nno changes added to commit (use \"git add\" and/or \"git commit −a\")"
},
{
"code": null,
"e": 5579,
"s": 5500,
"text": "We can verify contents of our working directory using the following commands −"
},
{
"code": null,
"e": 5722,
"s": 5579,
"text": "$ ls // lists contents of the current directory\n$ cat newfile.txt // lists contents of newfile.txt\n$ cat lmno.txt // list contents of lmno.txt"
},
{
"code": null,
"e": 5753,
"s": 5722,
"text": "The output is as shown below −"
},
{
"code": null,
"e": 5871,
"s": 5753,
"text": "//output of ls\nabc.txt lmno.txt newfile.txt\n//output of cat newfile.txt\nhello\n//output of cat lmno.txt\nlmno\nlmno lmno"
},
{
"code": null,
"e": 6039,
"s": 5871,
"text": "Once stashes are applied successfully, we may need to clean up things as stashes are not removed by default. We can use the following command to drop a specific stash."
},
{
"code": null,
"e": 6058,
"s": 6039,
"text": "$ git stash drop 0"
},
{
"code": null,
"e": 6140,
"s": 6058,
"text": "To clear entire contents in the stash in one go, we can use the following command"
},
{
"code": null,
"e": 6158,
"s": 6140,
"text": "$ git stash clear"
}
] |
A Practical Guide for Exploratory Data Analysis — Churn Dataset | by Soner Yıldırım | Towards Data Science
|
Exploratory data analysis (EDA) is an essential part of the data science or the machine learning pipeline. In order to create a robust and valuable product using the data, you need to explore the data, understand the relations among variables, and the underlying structure of the data.
In this post, we will explore a customer churn dataset using Pandas, Matplotlib, and Seaborn libraries. The dataset is available here on Kaggle.
The first step is to read the dataset into a pandas dataframe.
import pandas as pdimport numpy as npdf = pd.read_csv("/content/Churn_Modelling.csv")df.shape(10000, 14)df.head()
The dataset contains 10000 customers (i.e. rows) and 14 features about the customers and their products at a bank. The goal here is to predict whether a customer will churn (i.e. exited = 1) using the provided features. Thus, in terms of machine learning, we aim to build a supervised learning algorithm to perform a classification task.
We should never just dump the raw data into a machine learning model. Garbage in, garbage out! That is the reason why a thorough EDA process is highly important.
Let’s first check if there are any missing values.
df.isna().sum()
This dataset does not have any missing value which is not typical with real-life datasets. Handling missing values is an important part of the EDA process. If there are very few missing values compared to the size of the dataset, we may choose to drop rows that have missing values. Otherwise, it is better to replace them with appropriate values. Pandas fillna function can be used to handle this task.
Important note: If you choose to impute missing values based on the non-missing values in a column (e.g. fill missing values with the mean value of a column), you should do it after splitting your dataset into train and test subsets. Otherwise, you leak data to the machine learning model from the test set which is supposed to be new, previously unseen data.
Tasks like churn prediction and email spam detection are likely to have an imbalance class distribution. The number of customers who churned (i.e. left) is usually much less than the number of customers who did not churn. We can check the distribution of values with the value_counts function.
df.Exited.value_counts()0 7963 1 2037 Name: Exited, dtype: int64
There is an imbalance in the target variable (“Exited”). It is important to eliminate the imbalance. Otherwise, the machine learning model is likely to be biased towards the dominant class. There are different techniques to handle class imbalance such as undersampling and oversampling.
We should also make sure the data stored with appropriate data types. For instance, the numerical values should not be stored as “object”. Dtypes function returns the data type of each column.
df.dtypes
The data types are appropriate. The next step is to get rid of redundant features. “RowNumber” column is just an index. “CustomerId” and “Surname” columns are obviously useless for a machine learning model. Thus, we should drop them.
df.drop(['RowNumber','CustomerId','Surname'], axis=1, inplace=True)
We just pass the list of labels to be dropped. The axis parameter tells the drop function if we are dropping rows (0) or columns (1). The inplace parameter is set as true to save the changes.
It is time to dive deep into the dataset now.
Let’s check how “Gender” and “Geography” are related to customer churn. One way is to use the groupby function of pandas.
df[['Geography','Gender','Exited']].groupby(['Geography','Gender']).agg(['mean','count'])
Finding: In general, females are more likely to “exit” than males. The exit (churn) rate in Germany is higher than in France and Spain.
Another common practice in the EDA process is to check the distribution of variables. Distribution plots, histograms, and boxplots give us an idea about the distribution of variables (i.e. features).
fig , axs = plt.subplots(ncols=2, figsize=(12,6))fig.suptitle("Distribution of Balance and Estimated Salary", fontsize=15)sns.distplot(df.Balance, hist=False, ax=axs[0])sns.distplot(df.EstimatedSalary, hist=False, ax=axs[1])
Most of the customers have zero balance. For the remaining customers, the “Balance” has a normal distribution. The “EstimatedSalary” seems to have a uniform distribution.
Since there are lots of customers with zero balance, We may create a new binary feature indicating whether a customer has zero balance. The where function of pandas will do the job.
df['Balance_binary'] = df['Balance'].where(df['Balance'] == 0, 1)df['Balance_binary'].value_counts()1.0 6383 0.0 3617 Name: Balance_binary, dtype: int64
Approximately one-third of customers have zero balance. Let’s see the effect of having zero balance on churning.
df[['Balance_binary','Exited']].groupby('Balance_binary').mean()
Finding: Customers with zero balance are less likely to churn.
Another important statistic to check is the correlation among variables.
Correlation is a normalization of covariance by the standard deviation of each variable. Covariance is a quantitative measure that represents how much the variations of two variables match each other. To be more specific, covariance compares two variables in terms of the deviations from their mean (or expected) value.
By checking the correlation, we are trying to find how similarly two random variables deviate from their mean.
The corr function of pandas returns a correlation matrix indicating the correlations between numerical variables. We can then plot this matrix as a heatmap.
It is better if we convert the values in the “Gender” column to numeric ones which can be done with the replace function of pandas.
df['Gender'].replace({'Male':0, 'Female':1}, inplace=True)corr = df.corr()plt.figure(figsize=(12,8))sns.heatmap(corr, cmap='Blues_r', annot=True)
Finding: The “Age”, “Balance”, and “Gender” columns are positively correlated with customer churn (“Exited”). There is a negative correlation between being an active member (“IsActiveMember”) and customer churn.
If you compare “Balance” and “Balance_binary”, you will notice a very strong positive correlation since we created one based on the other.
Since “Age” turns out to have the highest correlation values, let’s dig in a little deeper.
df[['Exited','Age']].groupby('Exited').mean()
The average age of churned customers is higher. We should also check the distribution of the “Age” column.
plt.figure(figsize=(6,6))plt.title("Boxplot of the Age Column", fontsize=15)sns.boxplot(y=df['Age'])
The dots above the upper line indicate outliers. Thus, there are many outliers on the upper side. Another way to check outliers is comparing the mean and median.
print(df['Age'].mean())38.9218print(df['Age'].median())37.0
The mean is higher than the median which is compatible with the boxplot. There are many different ways to handle outliers. It can be the topic of an entire post.
Let’s do a simple one here. We will remove the data points that are in the top 5 percent.
Q1 = np.quantile(df['Age'],0.95)df = df[df['Age'] < Q1]df.shape(9474, 14)
The first line finds the value that distinguishes the top 5 percent. In the second line, we used this value to filter the dataframe. The original dataframe has 10000 rows so we deleted 526 rows.
Please note that this is not acceptable in many cases. We cannot just get rid of rows because data is a valuable asset and the more data we have the better models we can build. We are just trying to see if outliers have an effect on the correlation between age and customer churn.
Let’s compare the new mean and median.
print(df['Age'].mean())37.383681655055945print(df['Age'].median())37.0
They are pretty close. It is time to check the difference between the average age of churned customers and those who did not churn.
df[['Exited','Age']].groupby('Exited').mean()
Our finding still holds true. The average age of churned customers is higher.
There is no limit on exploratory data analysis. Depending on our task or goal, we can approach the data from a different perspective and dig deep to explore. However, the tools used in the process are usually similar. It is very important to practice a lot in order to get well in this process.
Thank you for reading. Please let me know if you have any feedback.
|
[
{
"code": null,
"e": 457,
"s": 171,
"text": "Exploratory data analysis (EDA) is an essential part of the data science or the machine learning pipeline. In order to create a robust and valuable product using the data, you need to explore the data, understand the relations among variables, and the underlying structure of the data."
},
{
"code": null,
"e": 602,
"s": 457,
"text": "In this post, we will explore a customer churn dataset using Pandas, Matplotlib, and Seaborn libraries. The dataset is available here on Kaggle."
},
{
"code": null,
"e": 665,
"s": 602,
"text": "The first step is to read the dataset into a pandas dataframe."
},
{
"code": null,
"e": 779,
"s": 665,
"text": "import pandas as pdimport numpy as npdf = pd.read_csv(\"/content/Churn_Modelling.csv\")df.shape(10000, 14)df.head()"
},
{
"code": null,
"e": 1117,
"s": 779,
"text": "The dataset contains 10000 customers (i.e. rows) and 14 features about the customers and their products at a bank. The goal here is to predict whether a customer will churn (i.e. exited = 1) using the provided features. Thus, in terms of machine learning, we aim to build a supervised learning algorithm to perform a classification task."
},
{
"code": null,
"e": 1279,
"s": 1117,
"text": "We should never just dump the raw data into a machine learning model. Garbage in, garbage out! That is the reason why a thorough EDA process is highly important."
},
{
"code": null,
"e": 1330,
"s": 1279,
"text": "Let’s first check if there are any missing values."
},
{
"code": null,
"e": 1346,
"s": 1330,
"text": "df.isna().sum()"
},
{
"code": null,
"e": 1750,
"s": 1346,
"text": "This dataset does not have any missing value which is not typical with real-life datasets. Handling missing values is an important part of the EDA process. If there are very few missing values compared to the size of the dataset, we may choose to drop rows that have missing values. Otherwise, it is better to replace them with appropriate values. Pandas fillna function can be used to handle this task."
},
{
"code": null,
"e": 2110,
"s": 1750,
"text": "Important note: If you choose to impute missing values based on the non-missing values in a column (e.g. fill missing values with the mean value of a column), you should do it after splitting your dataset into train and test subsets. Otherwise, you leak data to the machine learning model from the test set which is supposed to be new, previously unseen data."
},
{
"code": null,
"e": 2404,
"s": 2110,
"text": "Tasks like churn prediction and email spam detection are likely to have an imbalance class distribution. The number of customers who churned (i.e. left) is usually much less than the number of customers who did not churn. We can check the distribution of values with the value_counts function."
},
{
"code": null,
"e": 2475,
"s": 2404,
"text": "df.Exited.value_counts()0 7963 1 2037 Name: Exited, dtype: int64"
},
{
"code": null,
"e": 2762,
"s": 2475,
"text": "There is an imbalance in the target variable (“Exited”). It is important to eliminate the imbalance. Otherwise, the machine learning model is likely to be biased towards the dominant class. There are different techniques to handle class imbalance such as undersampling and oversampling."
},
{
"code": null,
"e": 2955,
"s": 2762,
"text": "We should also make sure the data stored with appropriate data types. For instance, the numerical values should not be stored as “object”. Dtypes function returns the data type of each column."
},
{
"code": null,
"e": 2965,
"s": 2955,
"text": "df.dtypes"
},
{
"code": null,
"e": 3199,
"s": 2965,
"text": "The data types are appropriate. The next step is to get rid of redundant features. “RowNumber” column is just an index. “CustomerId” and “Surname” columns are obviously useless for a machine learning model. Thus, we should drop them."
},
{
"code": null,
"e": 3267,
"s": 3199,
"text": "df.drop(['RowNumber','CustomerId','Surname'], axis=1, inplace=True)"
},
{
"code": null,
"e": 3459,
"s": 3267,
"text": "We just pass the list of labels to be dropped. The axis parameter tells the drop function if we are dropping rows (0) or columns (1). The inplace parameter is set as true to save the changes."
},
{
"code": null,
"e": 3505,
"s": 3459,
"text": "It is time to dive deep into the dataset now."
},
{
"code": null,
"e": 3627,
"s": 3505,
"text": "Let’s check how “Gender” and “Geography” are related to customer churn. One way is to use the groupby function of pandas."
},
{
"code": null,
"e": 3717,
"s": 3627,
"text": "df[['Geography','Gender','Exited']].groupby(['Geography','Gender']).agg(['mean','count'])"
},
{
"code": null,
"e": 3853,
"s": 3717,
"text": "Finding: In general, females are more likely to “exit” than males. The exit (churn) rate in Germany is higher than in France and Spain."
},
{
"code": null,
"e": 4053,
"s": 3853,
"text": "Another common practice in the EDA process is to check the distribution of variables. Distribution plots, histograms, and boxplots give us an idea about the distribution of variables (i.e. features)."
},
{
"code": null,
"e": 4278,
"s": 4053,
"text": "fig , axs = plt.subplots(ncols=2, figsize=(12,6))fig.suptitle(\"Distribution of Balance and Estimated Salary\", fontsize=15)sns.distplot(df.Balance, hist=False, ax=axs[0])sns.distplot(df.EstimatedSalary, hist=False, ax=axs[1])"
},
{
"code": null,
"e": 4449,
"s": 4278,
"text": "Most of the customers have zero balance. For the remaining customers, the “Balance” has a normal distribution. The “EstimatedSalary” seems to have a uniform distribution."
},
{
"code": null,
"e": 4631,
"s": 4449,
"text": "Since there are lots of customers with zero balance, We may create a new binary feature indicating whether a customer has zero balance. The where function of pandas will do the job."
},
{
"code": null,
"e": 4790,
"s": 4631,
"text": "df['Balance_binary'] = df['Balance'].where(df['Balance'] == 0, 1)df['Balance_binary'].value_counts()1.0 6383 0.0 3617 Name: Balance_binary, dtype: int64"
},
{
"code": null,
"e": 4903,
"s": 4790,
"text": "Approximately one-third of customers have zero balance. Let’s see the effect of having zero balance on churning."
},
{
"code": null,
"e": 4968,
"s": 4903,
"text": "df[['Balance_binary','Exited']].groupby('Balance_binary').mean()"
},
{
"code": null,
"e": 5031,
"s": 4968,
"text": "Finding: Customers with zero balance are less likely to churn."
},
{
"code": null,
"e": 5104,
"s": 5031,
"text": "Another important statistic to check is the correlation among variables."
},
{
"code": null,
"e": 5424,
"s": 5104,
"text": "Correlation is a normalization of covariance by the standard deviation of each variable. Covariance is a quantitative measure that represents how much the variations of two variables match each other. To be more specific, covariance compares two variables in terms of the deviations from their mean (or expected) value."
},
{
"code": null,
"e": 5535,
"s": 5424,
"text": "By checking the correlation, we are trying to find how similarly two random variables deviate from their mean."
},
{
"code": null,
"e": 5692,
"s": 5535,
"text": "The corr function of pandas returns a correlation matrix indicating the correlations between numerical variables. We can then plot this matrix as a heatmap."
},
{
"code": null,
"e": 5824,
"s": 5692,
"text": "It is better if we convert the values in the “Gender” column to numeric ones which can be done with the replace function of pandas."
},
{
"code": null,
"e": 5970,
"s": 5824,
"text": "df['Gender'].replace({'Male':0, 'Female':1}, inplace=True)corr = df.corr()plt.figure(figsize=(12,8))sns.heatmap(corr, cmap='Blues_r', annot=True)"
},
{
"code": null,
"e": 6182,
"s": 5970,
"text": "Finding: The “Age”, “Balance”, and “Gender” columns are positively correlated with customer churn (“Exited”). There is a negative correlation between being an active member (“IsActiveMember”) and customer churn."
},
{
"code": null,
"e": 6321,
"s": 6182,
"text": "If you compare “Balance” and “Balance_binary”, you will notice a very strong positive correlation since we created one based on the other."
},
{
"code": null,
"e": 6413,
"s": 6321,
"text": "Since “Age” turns out to have the highest correlation values, let’s dig in a little deeper."
},
{
"code": null,
"e": 6459,
"s": 6413,
"text": "df[['Exited','Age']].groupby('Exited').mean()"
},
{
"code": null,
"e": 6566,
"s": 6459,
"text": "The average age of churned customers is higher. We should also check the distribution of the “Age” column."
},
{
"code": null,
"e": 6667,
"s": 6566,
"text": "plt.figure(figsize=(6,6))plt.title(\"Boxplot of the Age Column\", fontsize=15)sns.boxplot(y=df['Age'])"
},
{
"code": null,
"e": 6829,
"s": 6667,
"text": "The dots above the upper line indicate outliers. Thus, there are many outliers on the upper side. Another way to check outliers is comparing the mean and median."
},
{
"code": null,
"e": 6889,
"s": 6829,
"text": "print(df['Age'].mean())38.9218print(df['Age'].median())37.0"
},
{
"code": null,
"e": 7051,
"s": 6889,
"text": "The mean is higher than the median which is compatible with the boxplot. There are many different ways to handle outliers. It can be the topic of an entire post."
},
{
"code": null,
"e": 7141,
"s": 7051,
"text": "Let’s do a simple one here. We will remove the data points that are in the top 5 percent."
},
{
"code": null,
"e": 7215,
"s": 7141,
"text": "Q1 = np.quantile(df['Age'],0.95)df = df[df['Age'] < Q1]df.shape(9474, 14)"
},
{
"code": null,
"e": 7410,
"s": 7215,
"text": "The first line finds the value that distinguishes the top 5 percent. In the second line, we used this value to filter the dataframe. The original dataframe has 10000 rows so we deleted 526 rows."
},
{
"code": null,
"e": 7691,
"s": 7410,
"text": "Please note that this is not acceptable in many cases. We cannot just get rid of rows because data is a valuable asset and the more data we have the better models we can build. We are just trying to see if outliers have an effect on the correlation between age and customer churn."
},
{
"code": null,
"e": 7730,
"s": 7691,
"text": "Let’s compare the new mean and median."
},
{
"code": null,
"e": 7801,
"s": 7730,
"text": "print(df['Age'].mean())37.383681655055945print(df['Age'].median())37.0"
},
{
"code": null,
"e": 7933,
"s": 7801,
"text": "They are pretty close. It is time to check the difference between the average age of churned customers and those who did not churn."
},
{
"code": null,
"e": 7979,
"s": 7933,
"text": "df[['Exited','Age']].groupby('Exited').mean()"
},
{
"code": null,
"e": 8057,
"s": 7979,
"text": "Our finding still holds true. The average age of churned customers is higher."
},
{
"code": null,
"e": 8352,
"s": 8057,
"text": "There is no limit on exploratory data analysis. Depending on our task or goal, we can approach the data from a different perspective and dig deep to explore. However, the tools used in the process are usually similar. It is very important to practice a lot in order to get well in this process."
}
] |
Python OpenCV: Building Instagram-Like Image Filters | by Marius Borcan | Towards Data Science
|
OpenCV is a library built for solving a large number of computer vision tasks. It is packed with lots of basic and advanced features, very easy to pick up and available for several programming languages.
In this article, we are going to apply some basic image transformation techniques in order to obtain image filters. For those of you accustomed with all the image editing software out there, these filters may seem very basic to you. But I think they are great for a first plunge into OpenCV because they allow us to learn some basic principles without writing tons of code. 😀
This article was originally published on the Programmer Backpack Blog. Make sure to visit this blog if you want to read more stories of this kind.
Interested in more? Follow me on Twitter at @b_dmarius and I’ll post there every new article.
In this section, I am going to explain the logic behind how RGB images are stored and manipulated by computers. If you are already familiar with this stuff, please skip to the next section where we are going to jump to more advanced details.
The basic unit data in an image is the pixel. A pixel is just a single point in the image and is stored as a number within the range of [0, 256]. The RGB model stands for Red-Green-Blue and tells us that for every pixel we store the intensity of red, green and blue(we will call these channels) as a number from 0 to 256. The pixel is white if all 3 channels are 256 and black if all 3 channels are 0. A pixel is fully red/green/blue if the respective channel is 256 and all other channels are 0. You get the idea, every color will be represented as a mix of these 3 channels.
So an image is a collection of pixels. If, let’s say, our image is 300x200, then we will store it as a 2D array of 300 lines and 200 columns where every cell is a pixel. But we know from above that for every pixel we will store the information about all 3 channels, so that gives us actually a 3D array.
This is the last section which consists entirely of theory. If you want to jump straight to the practical part, please see next section.
Now that we know how images are stored as pixels, we can learn to apply transformations on those pixels.
A convolution is the operation of transforming and image by splitting it into small parts called windows and applying an operator called kernel for every part.
The kernel is usually a fixed, small size 2D array containing numbers. An important part in the kernel is the center which is called anchor point.
A convolution is performed by following these steps:
Place the kernel on top of an image, with the kernel anchor point on top of a predetermined pixel.Perform a multiplication between the kernel numbers and the pixel values overlapped by the kernel, sum the multiplication results and place the result on the pixel that is below the anchor point.Repeat the process by sliding the kernel on top of the image for every possible position on the image.
Place the kernel on top of an image, with the kernel anchor point on top of a predetermined pixel.
Perform a multiplication between the kernel numbers and the pixel values overlapped by the kernel, sum the multiplication results and place the result on the pixel that is below the anchor point.
Repeat the process by sliding the kernel on top of the image for every possible position on the image.
If you are wondering how to choose values for the kernels, please note that the most popular kernels are results of lots of research from image processing scientists. You can of course try to choose your own kernels, but for the most basic transformations we already have good kernels which offer us great results.
We need to install 2 python packages and then we are good to go.
pip3 install opencv-pythonpip3 install scipy
We are going to import a single image(it’s an image I personally took) and for every transformation we are going to make a copy of that image. Then we apply the transformation through a separate method so that we can keep our code clean. At the end, we are going to save the result as a separate image. Here’s how the basic flow looks:
initialImage = cv2.imread("image1.jpg")blurredImage = gaussianBlur(copy.deepcopy(initialImage))cv2.imwrite("blurred.jpg", blurredImage)
This is the section where we are going to apply convolutions with a set of predefined kernels to obtain beautiful effects. For other types of transformations, please skip to the next section. For every transformation, I’m going to show you the kernel and the code and at the end of this section, I’m going to display a gallery with the initial image and the results.
This is the kernel used to sharpen the details on a picture. We are going to use the filter2D method from OpenCV library which will perform the convolution for us.
def sharpen(image): kernel = np.array([[-1, -1, -1], [-1, 9, -1], [-1, -1, -1]]) return cv2.filter2D(image, -1, kernel)
def sepia(image): kernel = np.array([[0.272, 0.534, 0.131], [0.349, 0.686, 0.168], [0.393, 0.769, 0.189]]) return cv2.filter2D(image, -1, kernel)
For this effect we can use a basic kernel like all of the above, but the results are pretty lame. Luckily, OpenCV has a gaussian blur implemented which will do the job for us. All we need to do is:
def gaussianBlur(image): return cv2.GaussianBlur(image, (35, 35), 0)
def emboss(image): kernel = np.array([[0,-1,-1], [1,0,-1], [1,1,0]]) return cv2.filter2D(image, -1, kernel)
And here is a gallery of our kernel transformation results.
Next up we are going to increase the brightness of an image. All we need to do for this is navigate to every pixel of the image and then to every channel of a specific pixel. Then we are going to increase the value for every channel by a specific value. This is going to give us a nice brightness effect.
To spare us from all this code, the OpenCV framework has a method implemented that can do exactly this.
def brightnessControl(image, level): return cv2.convertScaleAbs(image, beta=level)
Here’s the result of our brightness control method.
We are going to use this type of transformations to make an image appear warmer and colder, but first let’s see how we can use lookup tables for that.
A lookup table is just a simple collection of value pairs looking like this: [value1, value2, ...., valueN], [modifiedValue1, modifiedValue2, ..., modifiedValueN] and the logic behind this is simple — we are going to take every pixel value and replace it with the corresponding value from the lookup table(meaning replace value1 with modifiedValue1 and so on).
Now the problem with this is that there are lots of values to be replaced(from 0 to 256) and creating a lookup table for this is a painful process. But luck is on our side again, because there’s a tool we can use for that.
The UnivariateSpline smoothing method from the scipy package is here to help us. This method only takes a few reference values and tries to find a method to modify all the other values in the range with respect to the reference values we have provided.
Basically, we are going to define a short lookup table like this
[0, 64, 128, 256], [0, 80, 160, 256]
and apply the UnivariateSpline transformation which will fill up the rest of the values in the [0, 256] range.
Having our lookup tables built, we only need to apply them to the specific channels. For obtaining a warm image, we are going to increase the values of the red channel and decrease the values of the blue channel for all the pixels in the image. For obtaining a cold image, we are going to do the opposite: increase the values for the blue channel and decrease the values for the red channel. The green channel removes untouched in both cases.
def spreadLookupTable(x, y): spline = UnivariateSpline(x, y) return spline(range(256))def warmImage(image): increaseLookupTable = spreadLookupTable([0, 64, 128, 256], [0, 80, 160, 256]) decreaseLookupTable = spreadLookupTable([0, 64, 128, 256], [0, 50, 100, 256]) red_channel, green_channel, blue_channel = cv2.split(image) red_channel = cv2.LUT(red_channel, increaseLookupTable).astype(np.uint8) blue_channel = cv2.LUT(blue_channel, decreaseLookupTable).astype(np.uint8) return cv2.merge((red_channel, green_channel, blue_channel))def coldImage(image): increaseLookupTable = spreadLookupTable([0, 64, 128, 256], [0, 80, 160, 256]) decreaseLookupTable = spreadLookupTable([0, 64, 128, 256], [0, 50, 100, 256]) red_channel, green_channel, blue_channel = cv2.split(image) red_channel = cv2.LUT(red_channel, decreaseLookupTable).astype(np.uint8) blue_channel = cv2.LUT(blue_channel, increaseLookupTable).astype(np.uint8) return cv2.merge((red_channel, green_channel, blue_channel))
And the results here are as expected.
This was fun! We saw a bit of math here, a bit of code and learned a lot about how images are stored and manipulated by computers and how we can use this to obtain beautiful transformations for images. If you enjoyed this article and want to learn more, then make sure you follow me on Twitter because soon I'll post another article about building an Instagram-like mask using OpenCV.
This article was originally published on the Programmer Backpack Blog. Make sure to visit this blog if you want to read more stories of this kind.
Thank you so much for reading this! Interested in more? Follow me on Twitter at @b_dmarius and I’ll post there every new article.
|
[
{
"code": null,
"e": 376,
"s": 172,
"text": "OpenCV is a library built for solving a large number of computer vision tasks. It is packed with lots of basic and advanced features, very easy to pick up and available for several programming languages."
},
{
"code": null,
"e": 752,
"s": 376,
"text": "In this article, we are going to apply some basic image transformation techniques in order to obtain image filters. For those of you accustomed with all the image editing software out there, these filters may seem very basic to you. But I think they are great for a first plunge into OpenCV because they allow us to learn some basic principles without writing tons of code. 😀"
},
{
"code": null,
"e": 899,
"s": 752,
"text": "This article was originally published on the Programmer Backpack Blog. Make sure to visit this blog if you want to read more stories of this kind."
},
{
"code": null,
"e": 993,
"s": 899,
"text": "Interested in more? Follow me on Twitter at @b_dmarius and I’ll post there every new article."
},
{
"code": null,
"e": 1235,
"s": 993,
"text": "In this section, I am going to explain the logic behind how RGB images are stored and manipulated by computers. If you are already familiar with this stuff, please skip to the next section where we are going to jump to more advanced details."
},
{
"code": null,
"e": 1812,
"s": 1235,
"text": "The basic unit data in an image is the pixel. A pixel is just a single point in the image and is stored as a number within the range of [0, 256]. The RGB model stands for Red-Green-Blue and tells us that for every pixel we store the intensity of red, green and blue(we will call these channels) as a number from 0 to 256. The pixel is white if all 3 channels are 256 and black if all 3 channels are 0. A pixel is fully red/green/blue if the respective channel is 256 and all other channels are 0. You get the idea, every color will be represented as a mix of these 3 channels."
},
{
"code": null,
"e": 2116,
"s": 1812,
"text": "So an image is a collection of pixels. If, let’s say, our image is 300x200, then we will store it as a 2D array of 300 lines and 200 columns where every cell is a pixel. But we know from above that for every pixel we will store the information about all 3 channels, so that gives us actually a 3D array."
},
{
"code": null,
"e": 2253,
"s": 2116,
"text": "This is the last section which consists entirely of theory. If you want to jump straight to the practical part, please see next section."
},
{
"code": null,
"e": 2358,
"s": 2253,
"text": "Now that we know how images are stored as pixels, we can learn to apply transformations on those pixels."
},
{
"code": null,
"e": 2518,
"s": 2358,
"text": "A convolution is the operation of transforming and image by splitting it into small parts called windows and applying an operator called kernel for every part."
},
{
"code": null,
"e": 2665,
"s": 2518,
"text": "The kernel is usually a fixed, small size 2D array containing numbers. An important part in the kernel is the center which is called anchor point."
},
{
"code": null,
"e": 2718,
"s": 2665,
"text": "A convolution is performed by following these steps:"
},
{
"code": null,
"e": 3114,
"s": 2718,
"text": "Place the kernel on top of an image, with the kernel anchor point on top of a predetermined pixel.Perform a multiplication between the kernel numbers and the pixel values overlapped by the kernel, sum the multiplication results and place the result on the pixel that is below the anchor point.Repeat the process by sliding the kernel on top of the image for every possible position on the image."
},
{
"code": null,
"e": 3213,
"s": 3114,
"text": "Place the kernel on top of an image, with the kernel anchor point on top of a predetermined pixel."
},
{
"code": null,
"e": 3409,
"s": 3213,
"text": "Perform a multiplication between the kernel numbers and the pixel values overlapped by the kernel, sum the multiplication results and place the result on the pixel that is below the anchor point."
},
{
"code": null,
"e": 3512,
"s": 3409,
"text": "Repeat the process by sliding the kernel on top of the image for every possible position on the image."
},
{
"code": null,
"e": 3827,
"s": 3512,
"text": "If you are wondering how to choose values for the kernels, please note that the most popular kernels are results of lots of research from image processing scientists. You can of course try to choose your own kernels, but for the most basic transformations we already have good kernels which offer us great results."
},
{
"code": null,
"e": 3892,
"s": 3827,
"text": "We need to install 2 python packages and then we are good to go."
},
{
"code": null,
"e": 3937,
"s": 3892,
"text": "pip3 install opencv-pythonpip3 install scipy"
},
{
"code": null,
"e": 4273,
"s": 3937,
"text": "We are going to import a single image(it’s an image I personally took) and for every transformation we are going to make a copy of that image. Then we apply the transformation through a separate method so that we can keep our code clean. At the end, we are going to save the result as a separate image. Here’s how the basic flow looks:"
},
{
"code": null,
"e": 4409,
"s": 4273,
"text": "initialImage = cv2.imread(\"image1.jpg\")blurredImage = gaussianBlur(copy.deepcopy(initialImage))cv2.imwrite(\"blurred.jpg\", blurredImage)"
},
{
"code": null,
"e": 4776,
"s": 4409,
"text": "This is the section where we are going to apply convolutions with a set of predefined kernels to obtain beautiful effects. For other types of transformations, please skip to the next section. For every transformation, I’m going to show you the kernel and the code and at the end of this section, I’m going to display a gallery with the initial image and the results."
},
{
"code": null,
"e": 4940,
"s": 4776,
"text": "This is the kernel used to sharpen the details on a picture. We are going to use the filter2D method from OpenCV library which will perform the convolution for us."
},
{
"code": null,
"e": 5066,
"s": 4940,
"text": "def sharpen(image): kernel = np.array([[-1, -1, -1], [-1, 9, -1], [-1, -1, -1]]) return cv2.filter2D(image, -1, kernel)"
},
{
"code": null,
"e": 5262,
"s": 5066,
"text": "def sepia(image): kernel = np.array([[0.272, 0.534, 0.131], [0.349, 0.686, 0.168], [0.393, 0.769, 0.189]]) return cv2.filter2D(image, -1, kernel)"
},
{
"code": null,
"e": 5460,
"s": 5262,
"text": "For this effect we can use a basic kernel like all of the above, but the results are pretty lame. Luckily, OpenCV has a gaussian blur implemented which will do the job for us. All we need to do is:"
},
{
"code": null,
"e": 5532,
"s": 5460,
"text": "def gaussianBlur(image): return cv2.GaussianBlur(image, (35, 35), 0)"
},
{
"code": null,
"e": 5700,
"s": 5532,
"text": "def emboss(image): kernel = np.array([[0,-1,-1], [1,0,-1], [1,1,0]]) return cv2.filter2D(image, -1, kernel)"
},
{
"code": null,
"e": 5760,
"s": 5700,
"text": "And here is a gallery of our kernel transformation results."
},
{
"code": null,
"e": 6065,
"s": 5760,
"text": "Next up we are going to increase the brightness of an image. All we need to do for this is navigate to every pixel of the image and then to every channel of a specific pixel. Then we are going to increase the value for every channel by a specific value. This is going to give us a nice brightness effect."
},
{
"code": null,
"e": 6169,
"s": 6065,
"text": "To spare us from all this code, the OpenCV framework has a method implemented that can do exactly this."
},
{
"code": null,
"e": 6255,
"s": 6169,
"text": "def brightnessControl(image, level): return cv2.convertScaleAbs(image, beta=level)"
},
{
"code": null,
"e": 6307,
"s": 6255,
"text": "Here’s the result of our brightness control method."
},
{
"code": null,
"e": 6458,
"s": 6307,
"text": "We are going to use this type of transformations to make an image appear warmer and colder, but first let’s see how we can use lookup tables for that."
},
{
"code": null,
"e": 6819,
"s": 6458,
"text": "A lookup table is just a simple collection of value pairs looking like this: [value1, value2, ...., valueN], [modifiedValue1, modifiedValue2, ..., modifiedValueN] and the logic behind this is simple — we are going to take every pixel value and replace it with the corresponding value from the lookup table(meaning replace value1 with modifiedValue1 and so on)."
},
{
"code": null,
"e": 7042,
"s": 6819,
"text": "Now the problem with this is that there are lots of values to be replaced(from 0 to 256) and creating a lookup table for this is a painful process. But luck is on our side again, because there’s a tool we can use for that."
},
{
"code": null,
"e": 7295,
"s": 7042,
"text": "The UnivariateSpline smoothing method from the scipy package is here to help us. This method only takes a few reference values and tries to find a method to modify all the other values in the range with respect to the reference values we have provided."
},
{
"code": null,
"e": 7360,
"s": 7295,
"text": "Basically, we are going to define a short lookup table like this"
},
{
"code": null,
"e": 7397,
"s": 7360,
"text": "[0, 64, 128, 256], [0, 80, 160, 256]"
},
{
"code": null,
"e": 7508,
"s": 7397,
"text": "and apply the UnivariateSpline transformation which will fill up the rest of the values in the [0, 256] range."
},
{
"code": null,
"e": 7951,
"s": 7508,
"text": "Having our lookup tables built, we only need to apply them to the specific channels. For obtaining a warm image, we are going to increase the values of the red channel and decrease the values of the blue channel for all the pixels in the image. For obtaining a cold image, we are going to do the opposite: increase the values for the blue channel and decrease the values for the red channel. The green channel removes untouched in both cases."
},
{
"code": null,
"e": 8968,
"s": 7951,
"text": "def spreadLookupTable(x, y): spline = UnivariateSpline(x, y) return spline(range(256))def warmImage(image): increaseLookupTable = spreadLookupTable([0, 64, 128, 256], [0, 80, 160, 256]) decreaseLookupTable = spreadLookupTable([0, 64, 128, 256], [0, 50, 100, 256]) red_channel, green_channel, blue_channel = cv2.split(image) red_channel = cv2.LUT(red_channel, increaseLookupTable).astype(np.uint8) blue_channel = cv2.LUT(blue_channel, decreaseLookupTable).astype(np.uint8) return cv2.merge((red_channel, green_channel, blue_channel))def coldImage(image): increaseLookupTable = spreadLookupTable([0, 64, 128, 256], [0, 80, 160, 256]) decreaseLookupTable = spreadLookupTable([0, 64, 128, 256], [0, 50, 100, 256]) red_channel, green_channel, blue_channel = cv2.split(image) red_channel = cv2.LUT(red_channel, decreaseLookupTable).astype(np.uint8) blue_channel = cv2.LUT(blue_channel, increaseLookupTable).astype(np.uint8) return cv2.merge((red_channel, green_channel, blue_channel))"
},
{
"code": null,
"e": 9006,
"s": 8968,
"text": "And the results here are as expected."
},
{
"code": null,
"e": 9391,
"s": 9006,
"text": "This was fun! We saw a bit of math here, a bit of code and learned a lot about how images are stored and manipulated by computers and how we can use this to obtain beautiful transformations for images. If you enjoyed this article and want to learn more, then make sure you follow me on Twitter because soon I'll post another article about building an Instagram-like mask using OpenCV."
},
{
"code": null,
"e": 9538,
"s": 9391,
"text": "This article was originally published on the Programmer Backpack Blog. Make sure to visit this blog if you want to read more stories of this kind."
}
] |
SCAN (Elevator) Disk Scheduling Algorithms - GeeksforGeeks
|
19 Aug, 2021
Prerequisite-Disk scheduling algorithms.Given an array of disk track numbers and initial head position, our task is to find the total number of seek operations done to access all the requested tracks if SCAN disk scheduling algorithm is used.
SCAN (Elevator) algorithm In SCAN disk scheduling algorithm, head starts from one end of the disk and moves towards the other end, servicing requests in between one by one and reach the other end. Then the direction of the head is reversed and the process continues as head continuously scan back and forth to access the disk. So, this algorithm works as an elevator and hence also known as the elevator algorithm. As a result, the requests at the midrange are serviced more and those arriving behind the disk arm will have to wait.
Advantages of SCAN (Elevator) algorithm
This algorithm is simple and easy to understand.SCAN algorithm have no starvation.This algorithm is better than FCFS Scheduling algorithm .
This algorithm is simple and easy to understand.
SCAN algorithm have no starvation.
This algorithm is better than FCFS Scheduling algorithm .
Disadvantages of SCAN (Elevator) algorithm
More complex algorithm to implement.This algorithm is not fair because it cause long waiting time for the cylinders just visited by the head.It causes the head to move till the end of the disk in this way the requests arriving ahead of the arm position would get immediate service but some other requests that arrive behind the arm position will have to wait for the request to complete.
More complex algorithm to implement.
This algorithm is not fair because it cause long waiting time for the cylinders just visited by the head.
It causes the head to move till the end of the disk in this way the requests arriving ahead of the arm position would get immediate service but some other requests that arrive behind the arm position will have to wait for the request to complete.
Algorithm-
Let Request array represents an array storing indexes of tracks that have been requested in ascending order of their time of arrival. ‘head’ is the position of disk head.Let direction represents whether the head is moving towards left or right.In the direction in which head is moving service all tracks one by one.Calculate the absolute distance of the track from the head.Increment the total seek count with this distance.Currently serviced track position now becomes the new head position.Go to step 3 until we reach at one of the ends of the disk.If we reach at the end of the disk reverse the direction and go to step 2 until all tracks in request array have not been serviced.
Let Request array represents an array storing indexes of tracks that have been requested in ascending order of their time of arrival. ‘head’ is the position of disk head.
Let direction represents whether the head is moving towards left or right.
In the direction in which head is moving service all tracks one by one.
Calculate the absolute distance of the track from the head.
Increment the total seek count with this distance.
Currently serviced track position now becomes the new head position.
Go to step 3 until we reach at one of the ends of the disk.
If we reach at the end of the disk reverse the direction and go to step 2 until all tracks in request array have not been serviced.
Example:
Input:
Request sequence = {176, 79, 34, 60, 92, 11, 41, 114}
Initial head position = 50
Direction = left (We are moving from right to left)
Output:
Total number of seek operations = 226
Seek Sequence is
41
34
11
0
60
79
92
114
176
The following chart shows the sequence in which requested tracks are serviced using SCAN.
Therefore, the total seek count is calculated as:
= (50-41)+(41-34)+(34-11)
+(11-0)+(60-0)+(79-60)
+(92-79)+(114-92)+(176-114)
= 226
Implementation: Implementation of SCAN is given below. Note that distance is used to store the absolute distance between the head and current track position. disk_size is the size of the disk. Vectors left and right stores all the request tracks on the left-hand side and the right-hand side of the initial head position respectively.
C++
Java
Python3
C#
Javascript
// C++ program to demonstrate// SCAN Disk Scheduling algorithm #include <bits/stdc++.h>using namespace std; int size = 8;int disk_size = 200; void SCAN(int arr[], int head, string direction){ int seek_count = 0; int distance, cur_track; vector<int> left, right; vector<int> seek_sequence; // appending end values // which has to be visited // before reversing the direction if (direction == "left") left.push_back(0); else if (direction == "right") right.push_back(disk_size - 1); for (int i = 0; i < size; i++) { if (arr[i] < head) left.push_back(arr[i]); if (arr[i] > head) right.push_back(arr[i]); } // sorting left and right vectors std::sort(left.begin(), left.end()); std::sort(right.begin(), right.end()); // run the while loop two times. // one by one scanning right // and left of the head int run = 2; while (run--) { if (direction == "left") { for (int i = left.size() - 1; i >= 0; i--) { cur_track = left[i]; // appending current track to seek sequence seek_sequence.push_back(cur_track); // calculate absolute distance distance = abs(cur_track - head); // increase the total count seek_count += distance; // accessed track is now the new head head = cur_track; } direction = "right"; } else if (direction == "right") { for (int i = 0; i < right.size(); i++) { cur_track = right[i]; // appending current track to seek sequence seek_sequence.push_back(cur_track); // calculate absolute distance distance = abs(cur_track - head); // increase the total count seek_count += distance; // accessed track is now new head head = cur_track; } direction = "left"; } } cout << "Total number of seek operations = " << seek_count << endl; cout << "Seek Sequence is" << endl; for (int i = 0; i < seek_sequence.size(); i++) { cout << seek_sequence[i] << endl; }} // Driver codeint main(){ // request array int arr[size] = { 176, 79, 34, 60, 92, 11, 41, 114 }; int head = 50; string direction = "left"; SCAN(arr, head, direction); return 0;}
// Java program to demonstrate// SCAN Disk Scheduling algorithmimport java.util.*; class GFG{ static int size = 8;static int disk_size = 200; static void SCAN(int arr[], int head, String direction){ int seek_count = 0; int distance, cur_track; Vector<Integer> left = new Vector<Integer>(), right = new Vector<Integer>(); Vector<Integer> seek_sequence = new Vector<Integer>(); // appending end values // which has to be visited // before reversing the direction if (direction == "left") left.add(0); else if (direction == "right") right.add(disk_size - 1); for (int i = 0; i < size; i++) { if (arr[i] < head) left.add(arr[i]); if (arr[i] > head) right.add(arr[i]); } // sorting left and right vectors Collections.sort(left); Collections.sort(right); // run the while loop two times. // one by one scanning right // and left of the head int run = 2; while (run-- >0) { if (direction == "left") { for (int i = left.size() - 1; i >= 0; i--) { cur_track = left.get(i); // appending current track to seek sequence seek_sequence.add(cur_track); // calculate absolute distance distance = Math.abs(cur_track - head); // increase the total count seek_count += distance; // accessed track is now the new head head = cur_track; } direction = "right"; } else if (direction == "right") { for (int i = 0; i < right.size(); i++) { cur_track = right.get(i); // appending current track to seek sequence seek_sequence.add(cur_track); // calculate absolute distance distance = Math.abs(cur_track - head); // increase the total count seek_count += distance; // accessed track is now new head head = cur_track; } direction = "left"; } } System.out.print("Total number of seek operations = " + seek_count + "\n"); System.out.print("Seek Sequence is" + "\n"); for (int i = 0; i < seek_sequence.size(); i++) { System.out.print(seek_sequence.get(i) + "\n"); }} // Driver codepublic static void main(String[] args){ // request array int arr[] = { 176, 79, 34, 60, 92, 11, 41, 114 }; int head = 50; String direction = "left"; SCAN(arr, head, direction);}} // This code is contributed by 29AjayKumar
# Python3 program to demonstrate# SCAN Disk Scheduling algorithmsize = 8disk_size = 200 def SCAN(arr, head, direction): seek_count = 0 distance, cur_track = 0, 0 left = [] right = [] seek_sequence = [] # Appending end values # which has to be visited # before reversing the direction if (direction == "left"): left.append(0) elif (direction == "right"): right.append(disk_size - 1) for i in range(size): if (arr[i] < head): left.append(arr[i]) if (arr[i] > head): right.append(arr[i]) # Sorting left and right vectors left.sort() right.sort() # Run the while loop two times. # one by one scanning right # and left of the head run = 2 while (run != 0): if (direction == "left"): for i in range(len(left) - 1, -1, -1): cur_track = left[i] # Appending current track to # seek sequence seek_sequence.append(cur_track) # Calculate absolute distance distance = abs(cur_track - head) # Increase the total count seek_count += distance # Accessed track is now the new head head = cur_track direction = "right" elif (direction == "right"): for i in range(len(right)): cur_track = right[i] # Appending current track to seek # sequence seek_sequence.append(cur_track) # Calculate absolute distance distance = abs(cur_track - head) # Increase the total count seek_count += distance # Accessed track is now new head head = cur_track direction = "left" run -= 1 print("Total number of seek operations =", seek_count) print("Seek Sequence is") for i in range(len(seek_sequence)): print(seek_sequence[i]) # Driver code # request arrayarr = [ 176, 79, 34, 60, 92, 11, 41, 114 ]head = 50direction = "left" SCAN(arr, head, direction) # This code is contributed by divyesh072019
// C# program to demonstrate// SCAN Disk Scheduling algorithmusing System;using System.Collections.Generic; class GFG{ static int size = 8;static int disk_size = 200; static void SCAN(int []arr, int head, String direction){ int seek_count = 0; int distance, cur_track; List<int> left = new List<int>(), right = new List<int>(); List<int> seek_sequence = new List<int>(); // appending end values // which has to be visited // before reversing the direction if (direction == "left") left.Add(0); else if (direction == "right") right.Add(disk_size - 1); for (int i = 0; i < size; i++) { if (arr[i] < head) left.Add(arr[i]); if (arr[i] > head) right.Add(arr[i]); } // sorting left and right vectors left.Sort(); right.Sort(); // run the while loop two times. // one by one scanning right // and left of the head int run = 2; while (run-- >0) { if (direction == "left") { for (int i = left.Count - 1; i >= 0; i--) { cur_track = left[i]; // appending current track to seek sequence seek_sequence.Add(cur_track); // calculate absolute distance distance = Math.Abs(cur_track - head); // increase the total count seek_count += distance; // accessed track is now the new head head = cur_track; } direction = "right"; } else if (direction == "right") { for (int i = 0; i < right.Count; i++) { cur_track = right[i]; // appending current track to seek sequence seek_sequence.Add(cur_track); // calculate absolute distance distance = Math.Abs(cur_track - head); // increase the total count seek_count += distance; // accessed track is now new head head = cur_track; } direction = "left"; } } Console.Write("Total number of seek operations = " + seek_count + "\n"); Console.Write("Seek Sequence is" + "\n"); for (int i = 0; i < seek_sequence.Count; i++) { Console.Write(seek_sequence[i] + "\n"); }} // Driver codepublic static void Main(String[] args){ // request array int []arr = { 176, 79, 34, 60, 92, 11, 41, 114 }; int head = 50; String direction = "left"; SCAN(arr, head, direction);}} // This code is contributed by 29AjayKumar
<script> // Javascript program to demonstrate // SCAN Disk Scheduling algorithm let size = 8; let disk_size = 200; function SCAN(arr, head, direction) { let seek_count = 0; let distance, cur_track; let left = [], right = []; let seek_sequence = []; // appending end values // which has to be visited // before reversing the direction if (direction == "left") left.push(0); else if (direction == "right") right.push(disk_size - 1); for (let i = 0; i < size; i++) { if (arr[i] < head) left.push(arr[i]); if (arr[i] > head) right.push(arr[i]); } // sorting left and right vectors left.sort(function(a, b){return a - b}); right.sort(function(a, b){return a - b}); // run the while loop two times. // one by one scanning right // and left of the head let run = 2; while (run-- >0) { if (direction == "left") { for (let i = left.length - 1; i >= 0; i--) { cur_track = left[i]; // appending current track to seek sequence seek_sequence.push(cur_track); // calculate absolute distance distance = Math.abs(cur_track - head); // increase the total count seek_count += distance; // accessed track is now the new head head = cur_track; } direction = "right"; } else if (direction == "right") { for (let i = 0; i < right.length; i++) { cur_track = right[i]; // appending current track to seek sequence seek_sequence.push(cur_track); // calculate absolute distance distance = Math.abs(cur_track - head); // increase the total count seek_count += distance; // accessed track is now new head head = cur_track; } direction = "left"; } } document.write("Total number of seek operations = " + seek_count + "</br>"); document.write("Seek Sequence is" + "</br>"); for (let i = 0; i < seek_sequence.length; i++) { document.write(seek_sequence[i] + "</br>"); } } // request array let arr = [ 176, 79, 34, 60, 92, 11, 41, 114 ]; let head = 50; let direction = "left"; SCAN(arr, head, direction); </script>
Total number of seek operations = 226
Seek Sequence is
41
34
11
0
60
79
92
114
176
Time Complexity: O(N * logN)Auxiliary Space: O(N)
29AjayKumar
itskawal2000
divyesh072019
mukesh07
pankajsharmagfg
Algorithms
Operating Systems
Operating Systems
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
SDE SHEET - A Complete Guide for SDE Preparation
Top 50 Array Coding Problems for Interviews
DSA Sheet by Love Babbar
Difference between BFS and DFS
A* Search Algorithm
LRU Cache Implementation
Cache Memory in Computer Organization
Memory Management in Operating System
'crontab' in Linux with Examples
Difference between Internal and External fragmentation
|
[
{
"code": null,
"e": 27809,
"s": 27781,
"text": "\n19 Aug, 2021"
},
{
"code": null,
"e": 28052,
"s": 27809,
"text": "Prerequisite-Disk scheduling algorithms.Given an array of disk track numbers and initial head position, our task is to find the total number of seek operations done to access all the requested tracks if SCAN disk scheduling algorithm is used."
},
{
"code": null,
"e": 28585,
"s": 28052,
"text": "SCAN (Elevator) algorithm In SCAN disk scheduling algorithm, head starts from one end of the disk and moves towards the other end, servicing requests in between one by one and reach the other end. Then the direction of the head is reversed and the process continues as head continuously scan back and forth to access the disk. So, this algorithm works as an elevator and hence also known as the elevator algorithm. As a result, the requests at the midrange are serviced more and those arriving behind the disk arm will have to wait."
},
{
"code": null,
"e": 28626,
"s": 28585,
"text": "Advantages of SCAN (Elevator) algorithm "
},
{
"code": null,
"e": 28766,
"s": 28626,
"text": "This algorithm is simple and easy to understand.SCAN algorithm have no starvation.This algorithm is better than FCFS Scheduling algorithm ."
},
{
"code": null,
"e": 28815,
"s": 28766,
"text": "This algorithm is simple and easy to understand."
},
{
"code": null,
"e": 28850,
"s": 28815,
"text": "SCAN algorithm have no starvation."
},
{
"code": null,
"e": 28908,
"s": 28850,
"text": "This algorithm is better than FCFS Scheduling algorithm ."
},
{
"code": null,
"e": 28952,
"s": 28908,
"text": "Disadvantages of SCAN (Elevator) algorithm "
},
{
"code": null,
"e": 29340,
"s": 28952,
"text": "More complex algorithm to implement.This algorithm is not fair because it cause long waiting time for the cylinders just visited by the head.It causes the head to move till the end of the disk in this way the requests arriving ahead of the arm position would get immediate service but some other requests that arrive behind the arm position will have to wait for the request to complete."
},
{
"code": null,
"e": 29377,
"s": 29340,
"text": "More complex algorithm to implement."
},
{
"code": null,
"e": 29483,
"s": 29377,
"text": "This algorithm is not fair because it cause long waiting time for the cylinders just visited by the head."
},
{
"code": null,
"e": 29730,
"s": 29483,
"text": "It causes the head to move till the end of the disk in this way the requests arriving ahead of the arm position would get immediate service but some other requests that arrive behind the arm position will have to wait for the request to complete."
},
{
"code": null,
"e": 29742,
"s": 29730,
"text": "Algorithm- "
},
{
"code": null,
"e": 30425,
"s": 29742,
"text": "Let Request array represents an array storing indexes of tracks that have been requested in ascending order of their time of arrival. ‘head’ is the position of disk head.Let direction represents whether the head is moving towards left or right.In the direction in which head is moving service all tracks one by one.Calculate the absolute distance of the track from the head.Increment the total seek count with this distance.Currently serviced track position now becomes the new head position.Go to step 3 until we reach at one of the ends of the disk.If we reach at the end of the disk reverse the direction and go to step 2 until all tracks in request array have not been serviced."
},
{
"code": null,
"e": 30596,
"s": 30425,
"text": "Let Request array represents an array storing indexes of tracks that have been requested in ascending order of their time of arrival. ‘head’ is the position of disk head."
},
{
"code": null,
"e": 30671,
"s": 30596,
"text": "Let direction represents whether the head is moving towards left or right."
},
{
"code": null,
"e": 30743,
"s": 30671,
"text": "In the direction in which head is moving service all tracks one by one."
},
{
"code": null,
"e": 30803,
"s": 30743,
"text": "Calculate the absolute distance of the track from the head."
},
{
"code": null,
"e": 30854,
"s": 30803,
"text": "Increment the total seek count with this distance."
},
{
"code": null,
"e": 30923,
"s": 30854,
"text": "Currently serviced track position now becomes the new head position."
},
{
"code": null,
"e": 30983,
"s": 30923,
"text": "Go to step 3 until we reach at one of the ends of the disk."
},
{
"code": null,
"e": 31115,
"s": 30983,
"text": "If we reach at the end of the disk reverse the direction and go to step 2 until all tracks in request array have not been serviced."
},
{
"code": null,
"e": 31126,
"s": 31115,
"text": "Example: "
},
{
"code": null,
"e": 31359,
"s": 31126,
"text": "Input: \nRequest sequence = {176, 79, 34, 60, 92, 11, 41, 114}\nInitial head position = 50\nDirection = left (We are moving from right to left)\n\nOutput:\nTotal number of seek operations = 226\nSeek Sequence is\n41\n34\n11\n0\n60\n79\n92\n114\n176"
},
{
"code": null,
"e": 31451,
"s": 31359,
"text": "The following chart shows the sequence in which requested tracks are serviced using SCAN. "
},
{
"code": null,
"e": 31502,
"s": 31451,
"text": "Therefore, the total seek count is calculated as: "
},
{
"code": null,
"e": 31587,
"s": 31502,
"text": "= (50-41)+(41-34)+(34-11)\n +(11-0)+(60-0)+(79-60)\n +(92-79)+(114-92)+(176-114)\n= 226"
},
{
"code": null,
"e": 31923,
"s": 31587,
"text": "Implementation: Implementation of SCAN is given below. Note that distance is used to store the absolute distance between the head and current track position. disk_size is the size of the disk. Vectors left and right stores all the request tracks on the left-hand side and the right-hand side of the initial head position respectively. "
},
{
"code": null,
"e": 31927,
"s": 31923,
"text": "C++"
},
{
"code": null,
"e": 31932,
"s": 31927,
"text": "Java"
},
{
"code": null,
"e": 31940,
"s": 31932,
"text": "Python3"
},
{
"code": null,
"e": 31943,
"s": 31940,
"text": "C#"
},
{
"code": null,
"e": 31954,
"s": 31943,
"text": "Javascript"
},
{
"code": "// C++ program to demonstrate// SCAN Disk Scheduling algorithm #include <bits/stdc++.h>using namespace std; int size = 8;int disk_size = 200; void SCAN(int arr[], int head, string direction){ int seek_count = 0; int distance, cur_track; vector<int> left, right; vector<int> seek_sequence; // appending end values // which has to be visited // before reversing the direction if (direction == \"left\") left.push_back(0); else if (direction == \"right\") right.push_back(disk_size - 1); for (int i = 0; i < size; i++) { if (arr[i] < head) left.push_back(arr[i]); if (arr[i] > head) right.push_back(arr[i]); } // sorting left and right vectors std::sort(left.begin(), left.end()); std::sort(right.begin(), right.end()); // run the while loop two times. // one by one scanning right // and left of the head int run = 2; while (run--) { if (direction == \"left\") { for (int i = left.size() - 1; i >= 0; i--) { cur_track = left[i]; // appending current track to seek sequence seek_sequence.push_back(cur_track); // calculate absolute distance distance = abs(cur_track - head); // increase the total count seek_count += distance; // accessed track is now the new head head = cur_track; } direction = \"right\"; } else if (direction == \"right\") { for (int i = 0; i < right.size(); i++) { cur_track = right[i]; // appending current track to seek sequence seek_sequence.push_back(cur_track); // calculate absolute distance distance = abs(cur_track - head); // increase the total count seek_count += distance; // accessed track is now new head head = cur_track; } direction = \"left\"; } } cout << \"Total number of seek operations = \" << seek_count << endl; cout << \"Seek Sequence is\" << endl; for (int i = 0; i < seek_sequence.size(); i++) { cout << seek_sequence[i] << endl; }} // Driver codeint main(){ // request array int arr[size] = { 176, 79, 34, 60, 92, 11, 41, 114 }; int head = 50; string direction = \"left\"; SCAN(arr, head, direction); return 0;}",
"e": 34449,
"s": 31954,
"text": null
},
{
"code": "// Java program to demonstrate// SCAN Disk Scheduling algorithmimport java.util.*; class GFG{ static int size = 8;static int disk_size = 200; static void SCAN(int arr[], int head, String direction){ int seek_count = 0; int distance, cur_track; Vector<Integer> left = new Vector<Integer>(), right = new Vector<Integer>(); Vector<Integer> seek_sequence = new Vector<Integer>(); // appending end values // which has to be visited // before reversing the direction if (direction == \"left\") left.add(0); else if (direction == \"right\") right.add(disk_size - 1); for (int i = 0; i < size; i++) { if (arr[i] < head) left.add(arr[i]); if (arr[i] > head) right.add(arr[i]); } // sorting left and right vectors Collections.sort(left); Collections.sort(right); // run the while loop two times. // one by one scanning right // and left of the head int run = 2; while (run-- >0) { if (direction == \"left\") { for (int i = left.size() - 1; i >= 0; i--) { cur_track = left.get(i); // appending current track to seek sequence seek_sequence.add(cur_track); // calculate absolute distance distance = Math.abs(cur_track - head); // increase the total count seek_count += distance; // accessed track is now the new head head = cur_track; } direction = \"right\"; } else if (direction == \"right\") { for (int i = 0; i < right.size(); i++) { cur_track = right.get(i); // appending current track to seek sequence seek_sequence.add(cur_track); // calculate absolute distance distance = Math.abs(cur_track - head); // increase the total count seek_count += distance; // accessed track is now new head head = cur_track; } direction = \"left\"; } } System.out.print(\"Total number of seek operations = \" + seek_count + \"\\n\"); System.out.print(\"Seek Sequence is\" + \"\\n\"); for (int i = 0; i < seek_sequence.size(); i++) { System.out.print(seek_sequence.get(i) + \"\\n\"); }} // Driver codepublic static void main(String[] args){ // request array int arr[] = { 176, 79, 34, 60, 92, 11, 41, 114 }; int head = 50; String direction = \"left\"; SCAN(arr, head, direction);}} // This code is contributed by 29AjayKumar",
"e": 37167,
"s": 34449,
"text": null
},
{
"code": "# Python3 program to demonstrate# SCAN Disk Scheduling algorithmsize = 8disk_size = 200 def SCAN(arr, head, direction): seek_count = 0 distance, cur_track = 0, 0 left = [] right = [] seek_sequence = [] # Appending end values # which has to be visited # before reversing the direction if (direction == \"left\"): left.append(0) elif (direction == \"right\"): right.append(disk_size - 1) for i in range(size): if (arr[i] < head): left.append(arr[i]) if (arr[i] > head): right.append(arr[i]) # Sorting left and right vectors left.sort() right.sort() # Run the while loop two times. # one by one scanning right # and left of the head run = 2 while (run != 0): if (direction == \"left\"): for i in range(len(left) - 1, -1, -1): cur_track = left[i] # Appending current track to # seek sequence seek_sequence.append(cur_track) # Calculate absolute distance distance = abs(cur_track - head) # Increase the total count seek_count += distance # Accessed track is now the new head head = cur_track direction = \"right\" elif (direction == \"right\"): for i in range(len(right)): cur_track = right[i] # Appending current track to seek # sequence seek_sequence.append(cur_track) # Calculate absolute distance distance = abs(cur_track - head) # Increase the total count seek_count += distance # Accessed track is now new head head = cur_track direction = \"left\" run -= 1 print(\"Total number of seek operations =\", seek_count) print(\"Seek Sequence is\") for i in range(len(seek_sequence)): print(seek_sequence[i]) # Driver code # request arrayarr = [ 176, 79, 34, 60, 92, 11, 41, 114 ]head = 50direction = \"left\" SCAN(arr, head, direction) # This code is contributed by divyesh072019",
"e": 39402,
"s": 37167,
"text": null
},
{
"code": "// C# program to demonstrate// SCAN Disk Scheduling algorithmusing System;using System.Collections.Generic; class GFG{ static int size = 8;static int disk_size = 200; static void SCAN(int []arr, int head, String direction){ int seek_count = 0; int distance, cur_track; List<int> left = new List<int>(), right = new List<int>(); List<int> seek_sequence = new List<int>(); // appending end values // which has to be visited // before reversing the direction if (direction == \"left\") left.Add(0); else if (direction == \"right\") right.Add(disk_size - 1); for (int i = 0; i < size; i++) { if (arr[i] < head) left.Add(arr[i]); if (arr[i] > head) right.Add(arr[i]); } // sorting left and right vectors left.Sort(); right.Sort(); // run the while loop two times. // one by one scanning right // and left of the head int run = 2; while (run-- >0) { if (direction == \"left\") { for (int i = left.Count - 1; i >= 0; i--) { cur_track = left[i]; // appending current track to seek sequence seek_sequence.Add(cur_track); // calculate absolute distance distance = Math.Abs(cur_track - head); // increase the total count seek_count += distance; // accessed track is now the new head head = cur_track; } direction = \"right\"; } else if (direction == \"right\") { for (int i = 0; i < right.Count; i++) { cur_track = right[i]; // appending current track to seek sequence seek_sequence.Add(cur_track); // calculate absolute distance distance = Math.Abs(cur_track - head); // increase the total count seek_count += distance; // accessed track is now new head head = cur_track; } direction = \"left\"; } } Console.Write(\"Total number of seek operations = \" + seek_count + \"\\n\"); Console.Write(\"Seek Sequence is\" + \"\\n\"); for (int i = 0; i < seek_sequence.Count; i++) { Console.Write(seek_sequence[i] + \"\\n\"); }} // Driver codepublic static void Main(String[] args){ // request array int []arr = { 176, 79, 34, 60, 92, 11, 41, 114 }; int head = 50; String direction = \"left\"; SCAN(arr, head, direction);}} // This code is contributed by 29AjayKumar",
"e": 42067,
"s": 39402,
"text": null
},
{
"code": "<script> // Javascript program to demonstrate // SCAN Disk Scheduling algorithm let size = 8; let disk_size = 200; function SCAN(arr, head, direction) { let seek_count = 0; let distance, cur_track; let left = [], right = []; let seek_sequence = []; // appending end values // which has to be visited // before reversing the direction if (direction == \"left\") left.push(0); else if (direction == \"right\") right.push(disk_size - 1); for (let i = 0; i < size; i++) { if (arr[i] < head) left.push(arr[i]); if (arr[i] > head) right.push(arr[i]); } // sorting left and right vectors left.sort(function(a, b){return a - b}); right.sort(function(a, b){return a - b}); // run the while loop two times. // one by one scanning right // and left of the head let run = 2; while (run-- >0) { if (direction == \"left\") { for (let i = left.length - 1; i >= 0; i--) { cur_track = left[i]; // appending current track to seek sequence seek_sequence.push(cur_track); // calculate absolute distance distance = Math.abs(cur_track - head); // increase the total count seek_count += distance; // accessed track is now the new head head = cur_track; } direction = \"right\"; } else if (direction == \"right\") { for (let i = 0; i < right.length; i++) { cur_track = right[i]; // appending current track to seek sequence seek_sequence.push(cur_track); // calculate absolute distance distance = Math.abs(cur_track - head); // increase the total count seek_count += distance; // accessed track is now new head head = cur_track; } direction = \"left\"; } } document.write(\"Total number of seek operations = \" + seek_count + \"</br>\"); document.write(\"Seek Sequence is\" + \"</br>\"); for (let i = 0; i < seek_sequence.length; i++) { document.write(seek_sequence[i] + \"</br>\"); } } // request array let arr = [ 176, 79, 34, 60, 92, 11, 41, 114 ]; let head = 50; let direction = \"left\"; SCAN(arr, head, direction); </script>",
"e": 44851,
"s": 42067,
"text": null
},
{
"code": null,
"e": 44934,
"s": 44851,
"text": "Total number of seek operations = 226\nSeek Sequence is\n41\n34\n11\n0\n60\n79\n92\n114\n176"
},
{
"code": null,
"e": 44986,
"s": 44936,
"text": "Time Complexity: O(N * logN)Auxiliary Space: O(N)"
},
{
"code": null,
"e": 44998,
"s": 44986,
"text": "29AjayKumar"
},
{
"code": null,
"e": 45011,
"s": 44998,
"text": "itskawal2000"
},
{
"code": null,
"e": 45025,
"s": 45011,
"text": "divyesh072019"
},
{
"code": null,
"e": 45034,
"s": 45025,
"text": "mukesh07"
},
{
"code": null,
"e": 45050,
"s": 45034,
"text": "pankajsharmagfg"
},
{
"code": null,
"e": 45061,
"s": 45050,
"text": "Algorithms"
},
{
"code": null,
"e": 45079,
"s": 45061,
"text": "Operating Systems"
},
{
"code": null,
"e": 45097,
"s": 45079,
"text": "Operating Systems"
},
{
"code": null,
"e": 45108,
"s": 45097,
"text": "Algorithms"
},
{
"code": null,
"e": 45206,
"s": 45108,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 45215,
"s": 45206,
"text": "Comments"
},
{
"code": null,
"e": 45228,
"s": 45215,
"text": "Old Comments"
},
{
"code": null,
"e": 45277,
"s": 45228,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 45321,
"s": 45277,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 45346,
"s": 45321,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 45377,
"s": 45346,
"text": "Difference between BFS and DFS"
},
{
"code": null,
"e": 45397,
"s": 45377,
"text": "A* Search Algorithm"
},
{
"code": null,
"e": 45422,
"s": 45397,
"text": "LRU Cache Implementation"
},
{
"code": null,
"e": 45460,
"s": 45422,
"text": "Cache Memory in Computer Organization"
},
{
"code": null,
"e": 45498,
"s": 45460,
"text": "Memory Management in Operating System"
},
{
"code": null,
"e": 45531,
"s": 45498,
"text": "'crontab' in Linux with Examples"
}
] |
Does MySQL support table inheritance?
|
MySQL uses foreign key constraint instead of inheritance. MySQL does not support table inheritance.
You can achieve the same with the help of foreign key constraint. Let us create a table and use the foreign key constraint. The query to create the first table is as follows −
mysql> create table Parent_Table
-> (
-> ParentId int,
-> PRIMARY KEY(ParentId)
-> );
Query OK, 0 rows affected (3.59 sec)
Now create the second table. The query to create the second table is as follows −
mysql> create table Child_Table
-> (
-> ChildId int references Parent_Table,
-> PRIMARY KEY(ChildId)
-> );
Query OK, 0 rows affected (0.73 sec)
Now add the foreign key relationship between two tables. The query is as follows −
mysql> alter table Child_Table add constraint FK_Child Foreign key(ChildId) references Parent_Table(ParentId);
Query OK, 0 rows affected (2.28 sec)
Records: 0 Duplicates: 0 Warnings: 0
|
[
{
"code": null,
"e": 1162,
"s": 1062,
"text": "MySQL uses foreign key constraint instead of inheritance. MySQL does not support table inheritance."
},
{
"code": null,
"e": 1338,
"s": 1162,
"text": "You can achieve the same with the help of foreign key constraint. Let us create a table and use the foreign key constraint. The query to create the first table is as follows −"
},
{
"code": null,
"e": 1473,
"s": 1338,
"text": "mysql> create table Parent_Table\n -> (\n -> ParentId int,\n -> PRIMARY KEY(ParentId)\n -> );\nQuery OK, 0 rows affected (3.59 sec)"
},
{
"code": null,
"e": 1555,
"s": 1473,
"text": "Now create the second table. The query to create the second table is as follows −"
},
{
"code": null,
"e": 1711,
"s": 1555,
"text": "mysql> create table Child_Table\n -> (\n -> ChildId int references Parent_Table,\n -> PRIMARY KEY(ChildId)\n -> );\nQuery OK, 0 rows affected (0.73 sec)"
},
{
"code": null,
"e": 1794,
"s": 1711,
"text": "Now add the foreign key relationship between two tables. The query is as follows −"
},
{
"code": null,
"e": 1979,
"s": 1794,
"text": "mysql> alter table Child_Table add constraint FK_Child Foreign key(ChildId) references Parent_Table(ParentId);\nQuery OK, 0 rows affected (2.28 sec)\nRecords: 0 Duplicates: 0 Warnings: 0"
}
] |
Type Parameter Naming Conventions
|
By convention, type parameter names are named as single, uppercase letters so that a type parameter can be distinguished easily with an ordinary class or interface name. Following is the list of commonly used type parameter names −
E − Element, and is mainly used by Java Collections framework.
E − Element, and is mainly used by Java Collections framework.
K − Key, and is mainly used to represent parameter type of key of a map.
K − Key, and is mainly used to represent parameter type of key of a map.
V − Value, and is mainly used to represent parameter type of value of a map.
V − Value, and is mainly used to represent parameter type of value of a map.
N − Number, and is mainly used to represent numbers.
N − Number, and is mainly used to represent numbers.
T − Type, and is mainly used to represent first generic type parameter.
T − Type, and is mainly used to represent first generic type parameter.
S − Type, and is mainly used to represent second generic type parameter.
S − Type, and is mainly used to represent second generic type parameter.
U − Type, and is mainly used to represent third generic type parameter.
U − Type, and is mainly used to represent third generic type parameter.
V − Type, and is mainly used to represent fourth generic type parameter.
V − Type, and is mainly used to represent fourth generic type parameter.
Following example will showcase above mentioned concept.
Create the following java program using any editor of your choice.
GenericsTester.java
package com.tutorialspoint;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class GenericsTester {
public static void main(String[] args) {
Box<Integer, String> box = new Box<Integer, String>();
box.add(Integer.valueOf(10),"Hello World");
System.out.printf("Integer Value :%d\n", box.getFirst());
System.out.printf("String Value :%s\n", box.getSecond());
Pair<String, Integer> pair = new Pair<String, Integer>();
pair.addKeyValue("1", Integer.valueOf(10));
System.out.printf("(Pair)Integer Value :%d\n", pair.getValue("1"));
CustomList<Box> list = new CustomList<Box>();
list.addItem(box);
System.out.printf("(CustomList)Integer Value :%d\n", list.getItem(0).getFirst());
}
}
class Box<T, S> {
private T t;
private S s;
public void add(T t, S s) {
this.t = t;
this.s = s;
}
public T getFirst() {
return t;
}
public S getSecond() {
return s;
}
}
class Pair<K,V>{
private Map<K,V> map = new HashMap<K,V>();
public void addKeyValue(K key, V value) {
map.put(key, value);
}
public V getValue(K key) {
return map.get(key);
}
}
class CustomList<E>{
private List<E> list = new ArrayList<E>();
public void addItem(E value) {
list.add(value);
}
public E getItem(int index) {
return list.get(index);
}
}
This will produce the following result.
Integer Value :10
String Value :Hello World
(Pair)Integer Value :10
(CustomList)Integer Value :10
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": 2872,
"s": 2640,
"text": "By convention, type parameter names are named as single, uppercase letters so that a type parameter can be distinguished easily with an ordinary class or interface name. Following is the list of commonly used type parameter names −"
},
{
"code": null,
"e": 2935,
"s": 2872,
"text": "E − Element, and is mainly used by Java Collections framework."
},
{
"code": null,
"e": 2998,
"s": 2935,
"text": "E − Element, and is mainly used by Java Collections framework."
},
{
"code": null,
"e": 3071,
"s": 2998,
"text": "K − Key, and is mainly used to represent parameter type of key of a map."
},
{
"code": null,
"e": 3144,
"s": 3071,
"text": "K − Key, and is mainly used to represent parameter type of key of a map."
},
{
"code": null,
"e": 3221,
"s": 3144,
"text": "V − Value, and is mainly used to represent parameter type of value of a map."
},
{
"code": null,
"e": 3298,
"s": 3221,
"text": "V − Value, and is mainly used to represent parameter type of value of a map."
},
{
"code": null,
"e": 3351,
"s": 3298,
"text": "N − Number, and is mainly used to represent numbers."
},
{
"code": null,
"e": 3404,
"s": 3351,
"text": "N − Number, and is mainly used to represent numbers."
},
{
"code": null,
"e": 3476,
"s": 3404,
"text": "T − Type, and is mainly used to represent first generic type parameter."
},
{
"code": null,
"e": 3548,
"s": 3476,
"text": "T − Type, and is mainly used to represent first generic type parameter."
},
{
"code": null,
"e": 3621,
"s": 3548,
"text": "S − Type, and is mainly used to represent second generic type parameter."
},
{
"code": null,
"e": 3694,
"s": 3621,
"text": "S − Type, and is mainly used to represent second generic type parameter."
},
{
"code": null,
"e": 3766,
"s": 3694,
"text": "U − Type, and is mainly used to represent third generic type parameter."
},
{
"code": null,
"e": 3838,
"s": 3766,
"text": "U − Type, and is mainly used to represent third generic type parameter."
},
{
"code": null,
"e": 3911,
"s": 3838,
"text": "V − Type, and is mainly used to represent fourth generic type parameter."
},
{
"code": null,
"e": 3984,
"s": 3911,
"text": "V − Type, and is mainly used to represent fourth generic type parameter."
},
{
"code": null,
"e": 4041,
"s": 3984,
"text": "Following example will showcase above mentioned concept."
},
{
"code": null,
"e": 4108,
"s": 4041,
"text": "Create the following java program using any editor of your choice."
},
{
"code": null,
"e": 4128,
"s": 4108,
"text": "GenericsTester.java"
},
{
"code": null,
"e": 5565,
"s": 4128,
"text": "package com.tutorialspoint;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\npublic class GenericsTester {\n public static void main(String[] args) {\n Box<Integer, String> box = new Box<Integer, String>();\n box.add(Integer.valueOf(10),\"Hello World\");\n System.out.printf(\"Integer Value :%d\\n\", box.getFirst());\n System.out.printf(\"String Value :%s\\n\", box.getSecond());\n\n Pair<String, Integer> pair = new Pair<String, Integer>(); \n pair.addKeyValue(\"1\", Integer.valueOf(10));\n System.out.printf(\"(Pair)Integer Value :%d\\n\", pair.getValue(\"1\"));\n\n CustomList<Box> list = new CustomList<Box>();\n list.addItem(box);\n System.out.printf(\"(CustomList)Integer Value :%d\\n\", list.getItem(0).getFirst());\n }\n}\n\nclass Box<T, S> {\n private T t;\n private S s;\n\n public void add(T t, S s) {\n this.t = t;\n this.s = s;\n }\n\n public T getFirst() {\n return t;\n } \n\n public S getSecond() {\n return s;\n } \n}\n\nclass Pair<K,V>{\n private Map<K,V> map = new HashMap<K,V>();\n\n public void addKeyValue(K key, V value) {\n map.put(key, value);\n }\n\n public V getValue(K key) {\n return map.get(key);\n }\n}\n\nclass CustomList<E>{\n private List<E> list = new ArrayList<E>();\n\n public void addItem(E value) {\n list.add(value);\n }\n\n public E getItem(int index) {\n return list.get(index);\n }\n}"
},
{
"code": null,
"e": 5605,
"s": 5565,
"text": "This will produce the following result."
},
{
"code": null,
"e": 5704,
"s": 5605,
"text": "Integer Value :10\nString Value :Hello World\n(Pair)Integer Value :10\n(CustomList)Integer Value :10\n"
},
{
"code": null,
"e": 5737,
"s": 5704,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 5753,
"s": 5737,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 5786,
"s": 5753,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 5802,
"s": 5786,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 5837,
"s": 5802,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5851,
"s": 5837,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 5885,
"s": 5851,
"text": "\n 126 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 5899,
"s": 5885,
"text": " Tushar Kale"
},
{
"code": null,
"e": 5936,
"s": 5899,
"text": "\n 119 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 5951,
"s": 5936,
"text": " Monica Mittal"
},
{
"code": null,
"e": 5984,
"s": 5951,
"text": "\n 76 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 6003,
"s": 5984,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 6010,
"s": 6003,
"text": " Print"
},
{
"code": null,
"e": 6021,
"s": 6010,
"text": " Add Notes"
}
] |
How to remove specific value from array using jQuery ? - GeeksforGeeks
|
24 Apr, 2020
Given an array elements and the task is to remove the specific value element from the array with the help of JQuery. There are two approaches that are discussed below:
Approach 1: We can use the not() method which removes the element that we want. Later, use get() method to get the rest of the elements from the array.
Example:<!DOCTYPE HTML><html> <head> <title> Remove certain property for all objects in array with JavaScript. </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 id="GFG_UP"></p> <button onclick="gfg_Run()"> Click Here </button> <p id="GFG_DOWN" style="color:green;"></p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var arr = ["GFG", "GeeksForGeeks", "Geek", "Geeks"]; var remEl = "Geek"; el_up.innerHTML = "Click on the button to perform " + "the operation.<br>Array - [" + arr + "]"; function gfg_Run() { var arr2 = $(arr).not([remEl]).get(); el_down.innerHTML = "[" + arr2 + "]"; } </script></body> </html>
<!DOCTYPE HTML><html> <head> <title> Remove certain property for all objects in array with JavaScript. </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 id="GFG_UP"></p> <button onclick="gfg_Run()"> Click Here </button> <p id="GFG_DOWN" style="color:green;"></p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var arr = ["GFG", "GeeksForGeeks", "Geek", "Geeks"]; var remEl = "Geek"; el_up.innerHTML = "Click on the button to perform " + "the operation.<br>Array - [" + arr + "]"; function gfg_Run() { var arr2 = $(arr).not([remEl]).get(); el_down.innerHTML = "[" + arr2 + "]"; } </script></body> </html>
Output:
Approach 2: We can use the inArray() method to get the index of the element (that is to be removed) and then use slice() method to get the rest of the elements.
Example:<!DOCTYPE HTML><html> <head> <title> Remove certain property for all objects in array with JavaScript. </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 id="GFG_UP"></p> <button onclick="gfg_Run()"> Click Here </button> <p id="GFG_DOWN" style="color:green;"></p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var arr = ["GFG", "GeeksForGeeks", "Geek", "Geeks"]; var remEl = "Geek"; el_up.innerHTML = "Click on the button to perform " + "the operation.<br>Array - [" + arr + "]"; function gfg_Run() { arr.splice($.inArray(remEl, arr), 1); el_down.innerHTML = "[" + arr + "]"; } </script></body> </html>
<!DOCTYPE HTML><html> <head> <title> Remove certain property for all objects in array with JavaScript. </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 id="GFG_UP"></p> <button onclick="gfg_Run()"> Click Here </button> <p id="GFG_DOWN" style="color:green;"></p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var arr = ["GFG", "GeeksForGeeks", "Geek", "Geeks"]; var remEl = "Geek"; el_up.innerHTML = "Click on the button to perform " + "the operation.<br>Array - [" + arr + "]"; function gfg_Run() { arr.splice($.inArray(remEl, arr), 1); el_down.innerHTML = "[" + arr + "]"; } </script></body> </html>
Output:
CSS-Misc
HTML-Misc
JavaScript-Misc
CSS
HTML
JavaScript
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Design a web page using HTML and CSS
Form validation using jQuery
Search Bar using HTML, CSS and JavaScript
How to set space between the flexbox ?
How to Create Time-Table schedule using HTML ?
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
How to Insert Form Data into Database using PHP ?
Hide or show elements in HTML using display property
REST API (Introduction)
|
[
{
"code": null,
"e": 25296,
"s": 25268,
"text": "\n24 Apr, 2020"
},
{
"code": null,
"e": 25464,
"s": 25296,
"text": "Given an array elements and the task is to remove the specific value element from the array with the help of JQuery. There are two approaches that are discussed below:"
},
{
"code": null,
"e": 25616,
"s": 25464,
"text": "Approach 1: We can use the not() method which removes the element that we want. Later, use get() method to get the rest of the elements from the array."
},
{
"code": null,
"e": 26611,
"s": 25616,
"text": "Example:<!DOCTYPE HTML><html> <head> <title> Remove certain property for all objects in array with JavaScript. </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 id=\"GFG_UP\"></p> <button onclick=\"gfg_Run()\"> Click Here </button> <p id=\"GFG_DOWN\" style=\"color:green;\"></p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var arr = [\"GFG\", \"GeeksForGeeks\", \"Geek\", \"Geeks\"]; var remEl = \"Geek\"; el_up.innerHTML = \"Click on the button to perform \" + \"the operation.<br>Array - [\" + arr + \"]\"; function gfg_Run() { var arr2 = $(arr).not([remEl]).get(); el_down.innerHTML = \"[\" + arr2 + \"]\"; } </script></body> </html>"
},
{
"code": "<!DOCTYPE HTML><html> <head> <title> Remove certain property for all objects in array with JavaScript. </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 id=\"GFG_UP\"></p> <button onclick=\"gfg_Run()\"> Click Here </button> <p id=\"GFG_DOWN\" style=\"color:green;\"></p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var arr = [\"GFG\", \"GeeksForGeeks\", \"Geek\", \"Geeks\"]; var remEl = \"Geek\"; el_up.innerHTML = \"Click on the button to perform \" + \"the operation.<br>Array - [\" + arr + \"]\"; function gfg_Run() { var arr2 = $(arr).not([remEl]).get(); el_down.innerHTML = \"[\" + arr2 + \"]\"; } </script></body> </html>",
"e": 27598,
"s": 26611,
"text": null
},
{
"code": null,
"e": 27606,
"s": 27598,
"text": "Output:"
},
{
"code": null,
"e": 27767,
"s": 27606,
"text": "Approach 2: We can use the inArray() method to get the index of the element (that is to be removed) and then use slice() method to get the rest of the elements."
},
{
"code": null,
"e": 28761,
"s": 27767,
"text": "Example:<!DOCTYPE HTML><html> <head> <title> Remove certain property for all objects in array with JavaScript. </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 id=\"GFG_UP\"></p> <button onclick=\"gfg_Run()\"> Click Here </button> <p id=\"GFG_DOWN\" style=\"color:green;\"></p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var arr = [\"GFG\", \"GeeksForGeeks\", \"Geek\", \"Geeks\"]; var remEl = \"Geek\"; el_up.innerHTML = \"Click on the button to perform \" + \"the operation.<br>Array - [\" + arr + \"]\"; function gfg_Run() { arr.splice($.inArray(remEl, arr), 1); el_down.innerHTML = \"[\" + arr + \"]\"; } </script></body> </html>"
},
{
"code": "<!DOCTYPE HTML><html> <head> <title> Remove certain property for all objects in array with JavaScript. </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 id=\"GFG_UP\"></p> <button onclick=\"gfg_Run()\"> Click Here </button> <p id=\"GFG_DOWN\" style=\"color:green;\"></p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var arr = [\"GFG\", \"GeeksForGeeks\", \"Geek\", \"Geeks\"]; var remEl = \"Geek\"; el_up.innerHTML = \"Click on the button to perform \" + \"the operation.<br>Array - [\" + arr + \"]\"; function gfg_Run() { arr.splice($.inArray(remEl, arr), 1); el_down.innerHTML = \"[\" + arr + \"]\"; } </script></body> </html>",
"e": 29747,
"s": 28761,
"text": null
},
{
"code": null,
"e": 29755,
"s": 29747,
"text": "Output:"
},
{
"code": null,
"e": 29764,
"s": 29755,
"text": "CSS-Misc"
},
{
"code": null,
"e": 29774,
"s": 29764,
"text": "HTML-Misc"
},
{
"code": null,
"e": 29790,
"s": 29774,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 29794,
"s": 29790,
"text": "CSS"
},
{
"code": null,
"e": 29799,
"s": 29794,
"text": "HTML"
},
{
"code": null,
"e": 29810,
"s": 29799,
"text": "JavaScript"
},
{
"code": null,
"e": 29827,
"s": 29810,
"text": "Web Technologies"
},
{
"code": null,
"e": 29854,
"s": 29827,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 29859,
"s": 29854,
"text": "HTML"
},
{
"code": null,
"e": 29957,
"s": 29859,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29966,
"s": 29957,
"text": "Comments"
},
{
"code": null,
"e": 29979,
"s": 29966,
"text": "Old Comments"
},
{
"code": null,
"e": 30016,
"s": 29979,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 30045,
"s": 30016,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 30087,
"s": 30045,
"text": "Search Bar using HTML, CSS and JavaScript"
},
{
"code": null,
"e": 30126,
"s": 30087,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 30173,
"s": 30126,
"text": "How to Create Time-Table schedule using HTML ?"
},
{
"code": null,
"e": 30233,
"s": 30173,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 30294,
"s": 30233,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 30344,
"s": 30294,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 30397,
"s": 30344,
"text": "Hide or show elements in HTML using display property"
}
] |
Count of index pairs with equal elements in an array - GeeksforGeeks
|
15 Sep, 2021
Given an array of n elements. The task is to count the total number of indices (i, j) such that arr[i] = arr[j] and i < jExamples :
Input : arr[] = {1, 1, 2}
Output : 1
As arr[0] = arr[1], the pair of indices is (0, 1)
Input : arr[] = {1, 1, 1}
Output : 3
As arr[0] = arr[1], the pair of indices is (0, 1),
(0, 2) and (1, 2)
Input : arr[] = {1, 2, 3}
Output : 0
Method 1 (Brute Force): For each index i, find element after it with same value as arr[i]. Below is the implementation of this approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ program to count of pairs with equal// elements in an array.#include<bits/stdc++.h>using namespace std; // Return the number of pairs with equal// values.int countPairs(int arr[], int n){ int ans = 0; // for each index i and j for (int i = 0; i < n; i++) for (int j = i+1; j < n; j++) // finding the index with same // value but different index. if (arr[i] == arr[j]) ans++; return ans;} // Driven Programint main(){ int arr[] = { 1, 1, 2 }; int n = sizeof(arr)/sizeof(arr[0]); cout << countPairs(arr, n) << endl; return 0;}
// Java program to count of pairs with equal// elements in an array.class GFG { // Return the number of pairs with equal // values. static int countPairs(int arr[], int n) { int ans = 0; // for each index i and j for (int i = 0; i < n; i++) for (int j = i+1; j < n; j++) // finding the index with same // value but different index. if (arr[i] == arr[j]) ans++; return ans; } //driver code public static void main (String[] args) { int arr[] = { 1, 1, 2 }; int n = arr.length; System.out.println(countPairs(arr, n)); }} // This code is contributed by Anant Agarwal.
# Python3 program to# count of pairs with equal# elements in an array. # Return the number of# pairs with equal values.def countPairs(arr, n): ans = 0 # for each index i and j for i in range(0 , n): for j in range(i + 1, n): # finding the index # with same value but # different index. if (arr[i] == arr[j]): ans += 1 return ans # Driven Codearr = [1, 1, 2 ]n = len(arr)print(countPairs(arr, n)) # This code is contributed# by Smitha
// C# program to count of pairs with equal// elements in an array.using System; class GFG { // Return the number of pairs with equal // values. static int countPairs(int []arr, int n) { int ans = 0; // for each index i and j for (int i = 0; i < n; i++) for (int j = i+1; j < n; j++) // finding the index with same // value but different index. if (arr[i] == arr[j]) ans++; return ans; } // Driver code public static void Main () { int []arr = { 1, 1, 2 }; int n = arr.Length; Console.WriteLine(countPairs(arr, n)); }} // This code is contributed by anuj_67.
<?php// PHP program to count of// pairs with equal elements// in an array. // Return the number of pairs// with equal values.function countPairs( $arr, $n){ $ans = 0; // for each index i and j for ( $i = 0; $i < $n; $i++) for ( $j = $i + 1; $j < $n; $j++) // finding the index with same // value but different index. if ($arr[$i] == $arr[$j]) $ans++; return $ans;} // Driven Code$arr = array( 1, 1, 2 );$n = count($arr);echo countPairs($arr, $n) ; // This code is contributed by anuj_67.?>
<script>// Javascript program to count of pairs with equal// elements in an array. // Return the number of pairs with equal // values. function countPairs(arr, n) { let ans = 0; // for each index i and j for (let i = 0; i < n; i++) for (let j = i+1; j < n; j++) // finding the index with same // value but different index. if (arr[i] == arr[j]) ans++; return ans; } // Driver code let arr = [ 1, 1, 2 ]; let n = arr.length; document.write(countPairs(arr, n)); // This code is contributed by susmitakundugoaldanga.</script>
Output :
1
Time Complexity : O(n2)Method 2 (Efficient approach): The idea is to count the frequency of each number and then find the number of pairs with equal elements. Suppose, a number x appears k times at index i1, i2,....,ik. Then pick any two indexes ix and iy which will be counted as 1 pair. Similarly, iy and ix can also be pair. So, choose nC2 is the number of pairs such that arr[i] = arr[j] = x.Below is the implementation of this approach:
C++
Java
Python3
C#
Javascript
// C++ program to count of index pairs with// equal elements in an array.#include<bits/stdc++.h>using namespace std; // Return the number of pairs with equal// values.int countPairs(int arr[], int n){ unordered_map<int, int> mp; // Finding frequency of each number. for (int i = 0; i < n; i++) mp[arr[i]]++; // Calculating pairs of each value. int ans = 0; for (auto it=mp.begin(); it!=mp.end(); it++) { int count = it->second; ans += (count * (count - 1))/2; } return ans;} // Driven Programint main(){ int arr[] = {1, 1, 2}; int n = sizeof(arr)/sizeof(arr[0]); cout << countPairs(arr, n) << endl; return 0;}
// Java program to count of index pairs with// equal elements in an array.import java.util.*; class GFG { public static int countPairs(int arr[], int n) { //A method to return number of pairs with // equal values HashMap<Integer,Integer> hm = new HashMap<>(); // Finding frequency of each number. for(int i = 0; i < n; i++) { if(hm.containsKey(arr[i])) hm.put(arr[i],hm.get(arr[i]) + 1); else hm.put(arr[i], 1); } int ans=0; // Calculating count of pairs with equal values for(Map.Entry<Integer,Integer> it : hm.entrySet()) { int count = it.getValue(); ans += (count * (count - 1)) / 2; } return ans; } // Driver code public static void main(String[] args) { int arr[] = new int[]{1, 2, 3, 1}; System.out.println(countPairs(arr,arr.length)); }} // This Code is Contributed// by Adarsh_Verma
# Python3 program to count of index pairs# with equal elements in an array.import math as mt # Return the number of pairs with# equal values.def countPairs(arr, n): mp = dict() # Finding frequency of each number. for i in range(n): if arr[i] in mp.keys(): mp[arr[i]] += 1 else: mp[arr[i]] = 1 # Calculating pairs of each value. ans = 0 for it in mp: count = mp[it] ans += (count * (count - 1)) // 2 return ans # Driver Codearr = [1, 1, 2]n = len(arr)print(countPairs(arr, n)) # This code is contributed by mohit kumar 29
// C# program to count of index pairs with// equal elements in an array.using System;using System.Collections.Generic; class GFG{ // Return the number of pairs with // equal values. public static int countPairs(int []arr, int n) { // A method to return number of pairs // with equal values Dictionary<int, int> hm = new Dictionary<int, int>(); // Finding frequency of each number. for(int i = 0; i < n; i++) { if(hm.ContainsKey(arr[i])) { int a = hm[arr[i]]; hm.Remove(arr[i]); hm.Add(arr[i], a + 1); } else hm.Add(arr[i], 1); } int ans = 0; // Calculating count of pairs with // equal values foreach(var it in hm) { int count = it.Value; ans += (count * (count - 1)) / 2; } return ans; } // Driver code public static void Main() { int []arr = new int[]{1, 2, 3, 1}; Console.WriteLine(countPairs(arr,arr.Length)); }} // This code is contributed by 29AjayKumar
<script>// Javascript program to count of index pairs with// equal elements in an array. function countPairs(arr,n) { //A method to return number of pairs with // equal values let hm = new Map(); // Finding frequency of each number. for(let i = 0; i < n; i++) { if(hm.has(arr[i])) hm.set(arr[i],hm.get(arr[i]) + 1); else hm.set(arr[i], 1); } let ans=0; // Calculating count of pairs with equal values for(let [key, value] of hm.entries()) { let count = value; ans += (count * (count - 1)) / 2; } return ans; } // Driver code let arr=[1, 2, 3, 1]; document.write(countPairs(arr,arr.length)); // This code is contributed by patel2127</script>
Output :
1
Time Complexity : O(n)Source: http://stackoverflow.com/questions/26772364/efficient-algorithm-for-counting-number-of-pairs-of-identical-elements-in-an-arr#comment42124861_26772516This article is contributed by Anuj Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
ash_maurya
vt_m
Smitha Dinesh Semwal
Adarsh_Verma
mohit kumar 29
29AjayKumar
susmitakundugoaldanga
patel2127
aadityapburujwale
Arrays
Hash
Searching
Sorting
Arrays
Searching
Hash
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Stack Data Structure (Introduction and Program)
Introduction to Arrays
Multidimensional Arrays in Java
Internal Working of HashMap in Java
Hashing | Set 1 (Introduction)
Hashing | Set 3 (Open Addressing)
Hashing | Set 2 (Separate Chaining)
Sort string of characters
|
[
{
"code": null,
"e": 26465,
"s": 26437,
"text": "\n15 Sep, 2021"
},
{
"code": null,
"e": 26599,
"s": 26465,
"text": "Given an array of n elements. The task is to count the total number of indices (i, j) such that arr[i] = arr[j] and i < jExamples : "
},
{
"code": null,
"e": 26832,
"s": 26599,
"text": "Input : arr[] = {1, 1, 2}\nOutput : 1\nAs arr[0] = arr[1], the pair of indices is (0, 1)\n\nInput : arr[] = {1, 1, 1}\nOutput : 3\nAs arr[0] = arr[1], the pair of indices is (0, 1), \n(0, 2) and (1, 2)\n\nInput : arr[] = {1, 2, 3}\nOutput : 0"
},
{
"code": null,
"e": 26973,
"s": 26834,
"text": "Method 1 (Brute Force): For each index i, find element after it with same value as arr[i]. Below is the implementation of this approach: "
},
{
"code": null,
"e": 26977,
"s": 26973,
"text": "C++"
},
{
"code": null,
"e": 26982,
"s": 26977,
"text": "Java"
},
{
"code": null,
"e": 26990,
"s": 26982,
"text": "Python3"
},
{
"code": null,
"e": 26993,
"s": 26990,
"text": "C#"
},
{
"code": null,
"e": 26997,
"s": 26993,
"text": "PHP"
},
{
"code": null,
"e": 27008,
"s": 26997,
"text": "Javascript"
},
{
"code": "// C++ program to count of pairs with equal// elements in an array.#include<bits/stdc++.h>using namespace std; // Return the number of pairs with equal// values.int countPairs(int arr[], int n){ int ans = 0; // for each index i and j for (int i = 0; i < n; i++) for (int j = i+1; j < n; j++) // finding the index with same // value but different index. if (arr[i] == arr[j]) ans++; return ans;} // Driven Programint main(){ int arr[] = { 1, 1, 2 }; int n = sizeof(arr)/sizeof(arr[0]); cout << countPairs(arr, n) << endl; return 0;}",
"e": 27621,
"s": 27008,
"text": null
},
{
"code": "// Java program to count of pairs with equal// elements in an array.class GFG { // Return the number of pairs with equal // values. static int countPairs(int arr[], int n) { int ans = 0; // for each index i and j for (int i = 0; i < n; i++) for (int j = i+1; j < n; j++) // finding the index with same // value but different index. if (arr[i] == arr[j]) ans++; return ans; } //driver code public static void main (String[] args) { int arr[] = { 1, 1, 2 }; int n = arr.length; System.out.println(countPairs(arr, n)); }} // This code is contributed by Anant Agarwal.",
"e": 28370,
"s": 27621,
"text": null
},
{
"code": "# Python3 program to# count of pairs with equal# elements in an array. # Return the number of# pairs with equal values.def countPairs(arr, n): ans = 0 # for each index i and j for i in range(0 , n): for j in range(i + 1, n): # finding the index # with same value but # different index. if (arr[i] == arr[j]): ans += 1 return ans # Driven Codearr = [1, 1, 2 ]n = len(arr)print(countPairs(arr, n)) # This code is contributed# by Smitha",
"e": 28885,
"s": 28370,
"text": null
},
{
"code": "// C# program to count of pairs with equal// elements in an array.using System; class GFG { // Return the number of pairs with equal // values. static int countPairs(int []arr, int n) { int ans = 0; // for each index i and j for (int i = 0; i < n; i++) for (int j = i+1; j < n; j++) // finding the index with same // value but different index. if (arr[i] == arr[j]) ans++; return ans; } // Driver code public static void Main () { int []arr = { 1, 1, 2 }; int n = arr.Length; Console.WriteLine(countPairs(arr, n)); }} // This code is contributed by anuj_67.",
"e": 29627,
"s": 28885,
"text": null
},
{
"code": "<?php// PHP program to count of// pairs with equal elements// in an array. // Return the number of pairs// with equal values.function countPairs( $arr, $n){ $ans = 0; // for each index i and j for ( $i = 0; $i < $n; $i++) for ( $j = $i + 1; $j < $n; $j++) // finding the index with same // value but different index. if ($arr[$i] == $arr[$j]) $ans++; return $ans;} // Driven Code$arr = array( 1, 1, 2 );$n = count($arr);echo countPairs($arr, $n) ; // This code is contributed by anuj_67.?>",
"e": 30186,
"s": 29627,
"text": null
},
{
"code": "<script>// Javascript program to count of pairs with equal// elements in an array. // Return the number of pairs with equal // values. function countPairs(arr, n) { let ans = 0; // for each index i and j for (let i = 0; i < n; i++) for (let j = i+1; j < n; j++) // finding the index with same // value but different index. if (arr[i] == arr[j]) ans++; return ans; } // Driver code let arr = [ 1, 1, 2 ]; let n = arr.length; document.write(countPairs(arr, n)); // This code is contributed by susmitakundugoaldanga.</script>",
"e": 30879,
"s": 30186,
"text": null
},
{
"code": null,
"e": 30889,
"s": 30879,
"text": "Output : "
},
{
"code": null,
"e": 30891,
"s": 30889,
"text": "1"
},
{
"code": null,
"e": 31335,
"s": 30891,
"text": "Time Complexity : O(n2)Method 2 (Efficient approach): The idea is to count the frequency of each number and then find the number of pairs with equal elements. Suppose, a number x appears k times at index i1, i2,....,ik. Then pick any two indexes ix and iy which will be counted as 1 pair. Similarly, iy and ix can also be pair. So, choose nC2 is the number of pairs such that arr[i] = arr[j] = x.Below is the implementation of this approach: "
},
{
"code": null,
"e": 31339,
"s": 31335,
"text": "C++"
},
{
"code": null,
"e": 31344,
"s": 31339,
"text": "Java"
},
{
"code": null,
"e": 31352,
"s": 31344,
"text": "Python3"
},
{
"code": null,
"e": 31355,
"s": 31352,
"text": "C#"
},
{
"code": null,
"e": 31366,
"s": 31355,
"text": "Javascript"
},
{
"code": "// C++ program to count of index pairs with// equal elements in an array.#include<bits/stdc++.h>using namespace std; // Return the number of pairs with equal// values.int countPairs(int arr[], int n){ unordered_map<int, int> mp; // Finding frequency of each number. for (int i = 0; i < n; i++) mp[arr[i]]++; // Calculating pairs of each value. int ans = 0; for (auto it=mp.begin(); it!=mp.end(); it++) { int count = it->second; ans += (count * (count - 1))/2; } return ans;} // Driven Programint main(){ int arr[] = {1, 1, 2}; int n = sizeof(arr)/sizeof(arr[0]); cout << countPairs(arr, n) << endl; return 0;}",
"e": 32039,
"s": 31366,
"text": null
},
{
"code": "// Java program to count of index pairs with// equal elements in an array.import java.util.*; class GFG { public static int countPairs(int arr[], int n) { //A method to return number of pairs with // equal values HashMap<Integer,Integer> hm = new HashMap<>(); // Finding frequency of each number. for(int i = 0; i < n; i++) { if(hm.containsKey(arr[i])) hm.put(arr[i],hm.get(arr[i]) + 1); else hm.put(arr[i], 1); } int ans=0; // Calculating count of pairs with equal values for(Map.Entry<Integer,Integer> it : hm.entrySet()) { int count = it.getValue(); ans += (count * (count - 1)) / 2; } return ans; } // Driver code public static void main(String[] args) { int arr[] = new int[]{1, 2, 3, 1}; System.out.println(countPairs(arr,arr.length)); }} // This Code is Contributed// by Adarsh_Verma",
"e": 33047,
"s": 32039,
"text": null
},
{
"code": "# Python3 program to count of index pairs# with equal elements in an array.import math as mt # Return the number of pairs with# equal values.def countPairs(arr, n): mp = dict() # Finding frequency of each number. for i in range(n): if arr[i] in mp.keys(): mp[arr[i]] += 1 else: mp[arr[i]] = 1 # Calculating pairs of each value. ans = 0 for it in mp: count = mp[it] ans += (count * (count - 1)) // 2 return ans # Driver Codearr = [1, 1, 2]n = len(arr)print(countPairs(arr, n)) # This code is contributed by mohit kumar 29",
"e": 33654,
"s": 33047,
"text": null
},
{
"code": "// C# program to count of index pairs with// equal elements in an array.using System;using System.Collections.Generic; class GFG{ // Return the number of pairs with // equal values. public static int countPairs(int []arr, int n) { // A method to return number of pairs // with equal values Dictionary<int, int> hm = new Dictionary<int, int>(); // Finding frequency of each number. for(int i = 0; i < n; i++) { if(hm.ContainsKey(arr[i])) { int a = hm[arr[i]]; hm.Remove(arr[i]); hm.Add(arr[i], a + 1); } else hm.Add(arr[i], 1); } int ans = 0; // Calculating count of pairs with // equal values foreach(var it in hm) { int count = it.Value; ans += (count * (count - 1)) / 2; } return ans; } // Driver code public static void Main() { int []arr = new int[]{1, 2, 3, 1}; Console.WriteLine(countPairs(arr,arr.Length)); }} // This code is contributed by 29AjayKumar",
"e": 34868,
"s": 33654,
"text": null
},
{
"code": "<script>// Javascript program to count of index pairs with// equal elements in an array. function countPairs(arr,n) { //A method to return number of pairs with // equal values let hm = new Map(); // Finding frequency of each number. for(let i = 0; i < n; i++) { if(hm.has(arr[i])) hm.set(arr[i],hm.get(arr[i]) + 1); else hm.set(arr[i], 1); } let ans=0; // Calculating count of pairs with equal values for(let [key, value] of hm.entries()) { let count = value; ans += (count * (count - 1)) / 2; } return ans; } // Driver code let arr=[1, 2, 3, 1]; document.write(countPairs(arr,arr.length)); // This code is contributed by patel2127</script>",
"e": 35718,
"s": 34868,
"text": null
},
{
"code": null,
"e": 35729,
"s": 35718,
"text": "Output : "
},
{
"code": null,
"e": 35731,
"s": 35729,
"text": "1"
},
{
"code": null,
"e": 36331,
"s": 35731,
"text": "Time Complexity : O(n)Source: http://stackoverflow.com/questions/26772364/efficient-algorithm-for-counting-number-of-pairs-of-identical-elements-in-an-arr#comment42124861_26772516This article is contributed by Anuj Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 36342,
"s": 36331,
"text": "ash_maurya"
},
{
"code": null,
"e": 36347,
"s": 36342,
"text": "vt_m"
},
{
"code": null,
"e": 36368,
"s": 36347,
"text": "Smitha Dinesh Semwal"
},
{
"code": null,
"e": 36381,
"s": 36368,
"text": "Adarsh_Verma"
},
{
"code": null,
"e": 36396,
"s": 36381,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 36408,
"s": 36396,
"text": "29AjayKumar"
},
{
"code": null,
"e": 36430,
"s": 36408,
"text": "susmitakundugoaldanga"
},
{
"code": null,
"e": 36440,
"s": 36430,
"text": "patel2127"
},
{
"code": null,
"e": 36458,
"s": 36440,
"text": "aadityapburujwale"
},
{
"code": null,
"e": 36465,
"s": 36458,
"text": "Arrays"
},
{
"code": null,
"e": 36470,
"s": 36465,
"text": "Hash"
},
{
"code": null,
"e": 36480,
"s": 36470,
"text": "Searching"
},
{
"code": null,
"e": 36488,
"s": 36480,
"text": "Sorting"
},
{
"code": null,
"e": 36495,
"s": 36488,
"text": "Arrays"
},
{
"code": null,
"e": 36505,
"s": 36495,
"text": "Searching"
},
{
"code": null,
"e": 36510,
"s": 36505,
"text": "Hash"
},
{
"code": null,
"e": 36518,
"s": 36510,
"text": "Sorting"
},
{
"code": null,
"e": 36616,
"s": 36518,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36684,
"s": 36616,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 36728,
"s": 36684,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 36776,
"s": 36728,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 36799,
"s": 36776,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 36831,
"s": 36799,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 36867,
"s": 36831,
"text": "Internal Working of HashMap in Java"
},
{
"code": null,
"e": 36898,
"s": 36867,
"text": "Hashing | Set 1 (Introduction)"
},
{
"code": null,
"e": 36932,
"s": 36898,
"text": "Hashing | Set 3 (Open Addressing)"
},
{
"code": null,
"e": 36968,
"s": 36932,
"text": "Hashing | Set 2 (Separate Chaining)"
}
] |
ArrayStoreException in Java - GeeksforGeeks
|
10 Oct, 2018
ArrayStoreException in Java occurs whenever an attempt is made to store the wrong type of object into an array of objects. The ArrayStoreException is a class which extends RuntimeException, which means that it is an exception thrown at the runtime.
Class Hierarchy:
java.lang.Object
↳ java.lang.Throwable
↳ java.lang.Exception
↳ java.lang.RuntimeException
↳ java.lang.ArrayStoreException
Constructors of ArrayStoreException:
ArrayStoreException(): Constructs an ArrayStoreException instance with no detail message.ArrayStoreException(String s): Constructs an ArrayStoreException instance with the specified message s.
ArrayStoreException(): Constructs an ArrayStoreException instance with no detail message.
ArrayStoreException(String s): Constructs an ArrayStoreException instance with the specified message s.
When does ArrayStoreException occurs?ArrayStoreException in Java occurs whenever an attempt is made to store the wrong type of object into an array of objects.Below example illustrates when does ArrayStoreException occur:Since Number class is a superclass of Double class, and one can store an object of subclass in super class object in Java. Now If an integer value is tried to be stored in Double type array, it throws a runtime error during execution. The same thing wouldn’t happen if the array declaration would be like:public class GFG { public static void main(String args[]) { // Since Double class extends Number class // only Double type numbers // can be stored in this array Number[] a = new Double[2]; // Trying to store an integer value // in this Double type array a[0] = new Integer(4); }}Runtime Exception:Exception in thread “main” java.lang.ArrayStoreException: java.lang.Integerat GFG.main(GFG.java:13)
ArrayStoreException in Java occurs whenever an attempt is made to store the wrong type of object into an array of objects.
Below example illustrates when does ArrayStoreException occur:
Since Number class is a superclass of Double class, and one can store an object of subclass in super class object in Java. Now If an integer value is tried to be stored in Double type array, it throws a runtime error during execution. The same thing wouldn’t happen if the array declaration would be like:
public class GFG { public static void main(String args[]) { // Since Double class extends Number class // only Double type numbers // can be stored in this array Number[] a = new Double[2]; // Trying to store an integer value // in this Double type array a[0] = new Integer(4); }}
Runtime Exception:
Exception in thread “main” java.lang.ArrayStoreException: java.lang.Integerat GFG.main(GFG.java:13)
How to handle with ArrayStoreException?One can use try-catch block in Java to handle ArrayStoreException.Below example illustrates how to handle ArrayStoreException:public class GFG { public static void main(String args[]) { // use try-catch block // to handle ArrayStoreException try { Object a[] = new Double[2]; // This will throw ArrayStoreException a[0] = 4; } catch (ArrayStoreException e) { // When caught, print the ArrayStoreException System.out.println("ArrayStoreException found: " + e); } }}Output:ArrayStoreException found: java.lang.ArrayStoreException: java.lang.Integer
One can use try-catch block in Java to handle ArrayStoreException.
Below example illustrates how to handle ArrayStoreException:
public class GFG { public static void main(String args[]) { // use try-catch block // to handle ArrayStoreException try { Object a[] = new Double[2]; // This will throw ArrayStoreException a[0] = 4; } catch (ArrayStoreException e) { // When caught, print the ArrayStoreException System.out.println("ArrayStoreException found: " + e); } }}
Output:
ArrayStoreException found: java.lang.ArrayStoreException: java.lang.Integer
Java-Exception Handling
Java-Exceptions
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Exceptions in Java
Constructors in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Generics in Java
Introduction to Java
Comparator Interface in Java with Examples
PriorityQueue in Java
How to remove an element from ArrayList in Java?
|
[
{
"code": null,
"e": 25347,
"s": 25319,
"text": "\n10 Oct, 2018"
},
{
"code": null,
"e": 25596,
"s": 25347,
"text": "ArrayStoreException in Java occurs whenever an attempt is made to store the wrong type of object into an array of objects. The ArrayStoreException is a class which extends RuntimeException, which means that it is an exception thrown at the runtime."
},
{
"code": null,
"e": 25613,
"s": 25596,
"text": "Class Hierarchy:"
},
{
"code": null,
"e": 25761,
"s": 25613,
"text": "java.lang.Object\n↳ java.lang.Throwable\n ↳ java.lang.Exception\n ↳ java.lang.RuntimeException\n ↳ java.lang.ArrayStoreException \n"
},
{
"code": null,
"e": 25798,
"s": 25761,
"text": "Constructors of ArrayStoreException:"
},
{
"code": null,
"e": 25991,
"s": 25798,
"text": "ArrayStoreException(): Constructs an ArrayStoreException instance with no detail message.ArrayStoreException(String s): Constructs an ArrayStoreException instance with the specified message s."
},
{
"code": null,
"e": 26081,
"s": 25991,
"text": "ArrayStoreException(): Constructs an ArrayStoreException instance with no detail message."
},
{
"code": null,
"e": 26185,
"s": 26081,
"text": "ArrayStoreException(String s): Constructs an ArrayStoreException instance with the specified message s."
},
{
"code": null,
"e": 27173,
"s": 26185,
"text": "When does ArrayStoreException occurs?ArrayStoreException in Java occurs whenever an attempt is made to store the wrong type of object into an array of objects.Below example illustrates when does ArrayStoreException occur:Since Number class is a superclass of Double class, and one can store an object of subclass in super class object in Java. Now If an integer value is tried to be stored in Double type array, it throws a runtime error during execution. The same thing wouldn’t happen if the array declaration would be like:public class GFG { public static void main(String args[]) { // Since Double class extends Number class // only Double type numbers // can be stored in this array Number[] a = new Double[2]; // Trying to store an integer value // in this Double type array a[0] = new Integer(4); }}Runtime Exception:Exception in thread “main” java.lang.ArrayStoreException: java.lang.Integerat GFG.main(GFG.java:13)"
},
{
"code": null,
"e": 27296,
"s": 27173,
"text": "ArrayStoreException in Java occurs whenever an attempt is made to store the wrong type of object into an array of objects."
},
{
"code": null,
"e": 27359,
"s": 27296,
"text": "Below example illustrates when does ArrayStoreException occur:"
},
{
"code": null,
"e": 27665,
"s": 27359,
"text": "Since Number class is a superclass of Double class, and one can store an object of subclass in super class object in Java. Now If an integer value is tried to be stored in Double type array, it throws a runtime error during execution. The same thing wouldn’t happen if the array declaration would be like:"
},
{
"code": "public class GFG { public static void main(String args[]) { // Since Double class extends Number class // only Double type numbers // can be stored in this array Number[] a = new Double[2]; // Trying to store an integer value // in this Double type array a[0] = new Integer(4); }}",
"e": 28010,
"s": 27665,
"text": null
},
{
"code": null,
"e": 28029,
"s": 28010,
"text": "Runtime Exception:"
},
{
"code": null,
"e": 28129,
"s": 28029,
"text": "Exception in thread “main” java.lang.ArrayStoreException: java.lang.Integerat GFG.main(GFG.java:13)"
},
{
"code": null,
"e": 28863,
"s": 28129,
"text": "How to handle with ArrayStoreException?One can use try-catch block in Java to handle ArrayStoreException.Below example illustrates how to handle ArrayStoreException:public class GFG { public static void main(String args[]) { // use try-catch block // to handle ArrayStoreException try { Object a[] = new Double[2]; // This will throw ArrayStoreException a[0] = 4; } catch (ArrayStoreException e) { // When caught, print the ArrayStoreException System.out.println(\"ArrayStoreException found: \" + e); } }}Output:ArrayStoreException found: java.lang.ArrayStoreException: java.lang.Integer"
},
{
"code": null,
"e": 28930,
"s": 28863,
"text": "One can use try-catch block in Java to handle ArrayStoreException."
},
{
"code": null,
"e": 28991,
"s": 28930,
"text": "Below example illustrates how to handle ArrayStoreException:"
},
{
"code": "public class GFG { public static void main(String args[]) { // use try-catch block // to handle ArrayStoreException try { Object a[] = new Double[2]; // This will throw ArrayStoreException a[0] = 4; } catch (ArrayStoreException e) { // When caught, print the ArrayStoreException System.out.println(\"ArrayStoreException found: \" + e); } }}",
"e": 29478,
"s": 28991,
"text": null
},
{
"code": null,
"e": 29486,
"s": 29478,
"text": "Output:"
},
{
"code": null,
"e": 29562,
"s": 29486,
"text": "ArrayStoreException found: java.lang.ArrayStoreException: java.lang.Integer"
},
{
"code": null,
"e": 29586,
"s": 29562,
"text": "Java-Exception Handling"
},
{
"code": null,
"e": 29602,
"s": 29586,
"text": "Java-Exceptions"
},
{
"code": null,
"e": 29607,
"s": 29602,
"text": "Java"
},
{
"code": null,
"e": 29612,
"s": 29607,
"text": "Java"
},
{
"code": null,
"e": 29710,
"s": 29612,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29725,
"s": 29710,
"text": "Stream In Java"
},
{
"code": null,
"e": 29744,
"s": 29725,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 29765,
"s": 29744,
"text": "Constructors in Java"
},
{
"code": null,
"e": 29795,
"s": 29765,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 29841,
"s": 29795,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 29858,
"s": 29841,
"text": "Generics in Java"
},
{
"code": null,
"e": 29879,
"s": 29858,
"text": "Introduction to Java"
},
{
"code": null,
"e": 29922,
"s": 29879,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 29944,
"s": 29922,
"text": "PriorityQueue in Java"
}
] |
Android TableLayout in Kotlin - GeeksforGeeks
|
21 Feb, 2022
Android TableLayout is a ViewGroup subclass which is used to display the child View elements in rows and columns. It will arrange all the children elements into rows and columns and does not display any border lines in between rows, columns or cells.
The working of TableLayout is almost similar to HTML table and it contains as many columns as row with the most cells.
The TableLayout can be defined using <TableLayout> like below:
XML
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_marginTop="10dp" android:paddingLeft="5dp" android:paddingRight="5dp"> // Add Table rows here</TableLayout>
and TableRow can be defined using
XML
<TableRow android:background="#51B435" android:padding="10dp"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="Rank" /></TableRow>
In this file, we declare the TableLayout and start adding table rows with the help of TableRow. We are creating ranking table of players where we define four columns Rank, Name, Country and Points.
The code for the Table is:
XML
<?xml version="1.0" encoding="utf-8"?><TableLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_marginTop="10dp" android:paddingLeft="5dp" android:paddingRight="5dp"> <TextView android:id="@+id/txt" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="ICC Ranking of Players:" android:textSize = "20dp" android:textStyle="bold"> </TextView> <TableRow android:background="#51B435" android:padding="10dp"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="Rank" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="Player" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="Team" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="Points" /> </TableRow> <TableRow android:background="#F0F7F7" android:padding="5dp"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="1" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="Virat Kohli" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="IND" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="895" /> </TableRow> <TableRow android:background="#F0F7F7" android:padding="5dp"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="2" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="Rohit Sharma" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="IND" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="863" /> </TableRow> <TableRow android:background="#F0F7F7" android:padding="5dp"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="3" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="Faf du Plessis" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="PAK" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="834" /> </TableRow> <TableRow android:background="#F0F7F7" android:padding="5dp"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="4" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="Steven Smith" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="AUS" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="820" /> </TableRow> <TableRow android:background="#F0F7F7" android:padding="5dp"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="5" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="Ross Taylor" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="NZ" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="817" /> </TableRow> </TableLayout>
When we have created layout, we need to load the XML layout resource from our activity onCreate() callback method and access the UI element form the XML using findViewById.
Kotlin
package com.geeksforgeeks.myfirstKotlinapp import androidx.appcompat.app.AppCompatActivityimport android.os.Bundle class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // finding the UI elements }}
We need to run using Android Virtual Device(AVD) to see the output.
ayushpandey3july
Kotlin Android
Kotlin
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Broadcast Receiver in Android With Example
Android RecyclerView in Kotlin
Content Providers in Android with Example
Retrofit with Kotlin Coroutine in Android
Kotlin Setters and Getters
How to Add and Customize Back Button of Action Bar in Android?
How to Change the Color of Status Bar in an Android App?
Kotlin Higher-Order Functions
How to Get Current Location in Android?
|
[
{
"code": null,
"e": 25297,
"s": 25269,
"text": "\n21 Feb, 2022"
},
{
"code": null,
"e": 25548,
"s": 25297,
"text": "Android TableLayout is a ViewGroup subclass which is used to display the child View elements in rows and columns. It will arrange all the children elements into rows and columns and does not display any border lines in between rows, columns or cells."
},
{
"code": null,
"e": 25667,
"s": 25548,
"text": "The working of TableLayout is almost similar to HTML table and it contains as many columns as row with the most cells."
},
{
"code": null,
"e": 25730,
"s": 25667,
"text": "The TableLayout can be defined using <TableLayout> like below:"
},
{
"code": null,
"e": 25734,
"s": 25730,
"text": "XML"
},
{
"code": "<TableLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_marginTop=\"10dp\" android:paddingLeft=\"5dp\" android:paddingRight=\"5dp\"> // Add Table rows here</TableLayout>",
"e": 26023,
"s": 25734,
"text": null
},
{
"code": null,
"e": 26057,
"s": 26023,
"text": "and TableRow can be defined using"
},
{
"code": null,
"e": 26061,
"s": 26057,
"text": "XML"
},
{
"code": "<TableRow android:background=\"#51B435\" android:padding=\"10dp\"> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_weight=\"1\" android:text=\"Rank\" /></TableRow>",
"e": 26318,
"s": 26061,
"text": null
},
{
"code": null,
"e": 26516,
"s": 26318,
"text": "In this file, we declare the TableLayout and start adding table rows with the help of TableRow. We are creating ranking table of players where we define four columns Rank, Name, Country and Points."
},
{
"code": null,
"e": 26543,
"s": 26516,
"text": "The code for the Table is:"
},
{
"code": null,
"e": 26547,
"s": 26543,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><TableLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_marginTop=\"10dp\" android:paddingLeft=\"5dp\" android:paddingRight=\"5dp\"> <TextView android:id=\"@+id/txt\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"ICC Ranking of Players:\" android:textSize = \"20dp\" android:textStyle=\"bold\"> </TextView> <TableRow android:background=\"#51B435\" android:padding=\"10dp\"> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_weight=\"1\" android:text=\"Rank\" /> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_weight=\"1\" android:text=\"Player\" /> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_weight=\"1\" android:text=\"Team\" /> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_weight=\"1\" android:text=\"Points\" /> </TableRow> <TableRow android:background=\"#F0F7F7\" android:padding=\"5dp\"> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_weight=\"1\" android:text=\"1\" /> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_weight=\"1\" android:text=\"Virat Kohli\" /> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_weight=\"1\" android:text=\"IND\" /> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_weight=\"1\" android:text=\"895\" /> </TableRow> <TableRow android:background=\"#F0F7F7\" android:padding=\"5dp\"> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_weight=\"1\" android:text=\"2\" /> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_weight=\"1\" android:text=\"Rohit Sharma\" /> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_weight=\"1\" android:text=\"IND\" /> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_weight=\"1\" android:text=\"863\" /> </TableRow> <TableRow android:background=\"#F0F7F7\" android:padding=\"5dp\"> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_weight=\"1\" android:text=\"3\" /> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_weight=\"1\" android:text=\"Faf du Plessis\" /> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_weight=\"1\" android:text=\"PAK\" /> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_weight=\"1\" android:text=\"834\" /> </TableRow> <TableRow android:background=\"#F0F7F7\" android:padding=\"5dp\"> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_weight=\"1\" android:text=\"4\" /> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_weight=\"1\" android:text=\"Steven Smith\" /> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_weight=\"1\" android:text=\"AUS\" /> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_weight=\"1\" android:text=\"820\" /> </TableRow> <TableRow android:background=\"#F0F7F7\" android:padding=\"5dp\"> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_weight=\"1\" android:text=\"5\" /> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_weight=\"1\" android:text=\"Ross Taylor\" /> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_weight=\"1\" android:text=\"NZ\" /> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_weight=\"1\" android:text=\"817\" /> </TableRow> </TableLayout>",
"e": 32014,
"s": 26547,
"text": null
},
{
"code": null,
"e": 32187,
"s": 32014,
"text": "When we have created layout, we need to load the XML layout resource from our activity onCreate() callback method and access the UI element form the XML using findViewById."
},
{
"code": null,
"e": 32194,
"s": 32187,
"text": "Kotlin"
},
{
"code": "package com.geeksforgeeks.myfirstKotlinapp import androidx.appcompat.app.AppCompatActivityimport android.os.Bundle class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // finding the UI elements }}",
"e": 32546,
"s": 32194,
"text": null
},
{
"code": null,
"e": 32614,
"s": 32546,
"text": "We need to run using Android Virtual Device(AVD) to see the output."
},
{
"code": null,
"e": 32631,
"s": 32614,
"text": "ayushpandey3july"
},
{
"code": null,
"e": 32646,
"s": 32631,
"text": "Kotlin Android"
},
{
"code": null,
"e": 32653,
"s": 32646,
"text": "Kotlin"
},
{
"code": null,
"e": 32751,
"s": 32653,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32794,
"s": 32751,
"text": "Broadcast Receiver in Android With Example"
},
{
"code": null,
"e": 32825,
"s": 32794,
"text": "Android RecyclerView in Kotlin"
},
{
"code": null,
"e": 32867,
"s": 32825,
"text": "Content Providers in Android with Example"
},
{
"code": null,
"e": 32909,
"s": 32867,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 32936,
"s": 32909,
"text": "Kotlin Setters and Getters"
},
{
"code": null,
"e": 32999,
"s": 32936,
"text": "How to Add and Customize Back Button of Action Bar in Android?"
},
{
"code": null,
"e": 33056,
"s": 32999,
"text": "How to Change the Color of Status Bar in an Android App?"
},
{
"code": null,
"e": 33086,
"s": 33056,
"text": "Kotlin Higher-Order Functions"
}
] |
Google Cloud Platform - Introduction to PhoneInfoga an OSINT Reconnaissance Tool - GeeksforGeeks
|
27 May, 2021
PhoneInfoga is one of the most advanced tools which one can use to scan phone numbers and get detailed information about them using only free resources. The motive is to gather basic information such as country, area, line, and carrier on any international phone numbers with very good accuracy. Then try to determine the VoIP provider or search for footprints on search engines to try to identify the owner.
It checks if the phone number that you have searched, exists or not.
It gathers information about phone numbers such as country, area, carrier, and line type.
OSINT footprints using external APIs, Google Hacking, search engine, and phone books.
Check for reputation reports, social media, disposable numbers, and more.
Scan several numbers at once.
Run your web instances as a service.
Important
It does not allow to hack a phone.
It does not allow to get the precise phone location.
It does not allow to track phone or it’s owner in real time.
Follow the below steps to use PhoneInfoga on Google Cloud Console:
Step 1: Log in to Google Cloud Console using any of your google accounts and click on the icon shown below.
(This is actually launching your Google cloud shell and giving you access to a machine where you can use “PhoneInfoga“)
Step 2: Now there 2 options, either you can install PhoneInfoga like an application just by typing these commands into your terminal.
Or, you can go the easier way and use Docker.
Step 3: Since the Google cloud console has already installed docker, we can go ahead and type this command on the console.
Step 4: Press enter after typing the command and your console should be looking like this.
Step 5: Now we are going to run it, enter this command and at the end of it type the phone number with the country code:
docker run -it sundowndev/phoneinfoga scan -n 13526006900
Step 6: Let’s see what all the information we were able to get using “PhoneInfoga“.
As you can see, PhoneInfoga first ran numverify scan to check whether the number exists or not, and it returned, ‘true’ indicating the number exists.
We can also see that the location is, ‘Weekichspg‘ and the line type is of landline. Let’s further see what else we have here,
We can see here the social media footprints like on which social media platform this number is used to create an account. So it is quite clear that a tool like PhoneInfoga can prove to be very useful in gathering information on international phone numbers using only free resources.
Cloud-Computing
Google Cloud Platform
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Must Do Coding Questions for Product Based Companies
How to calculate MOVING AVERAGE in a Pandas DataFrame?
What is Transmission Control Protocol (TCP)?
Difference Between Skewness and Kurtosis
How to Convert Categorical Variable to Numeric in Pandas?
Sed Command in Linux/Unix with examples
AWK command in Unix/Linux with examples
grep command in Unix/Linux
cut command in Linux with examples
cp command in Linux with examples
|
[
{
"code": null,
"e": 26417,
"s": 26389,
"text": "\n27 May, 2021"
},
{
"code": null,
"e": 26826,
"s": 26417,
"text": "PhoneInfoga is one of the most advanced tools which one can use to scan phone numbers and get detailed information about them using only free resources. The motive is to gather basic information such as country, area, line, and carrier on any international phone numbers with very good accuracy. Then try to determine the VoIP provider or search for footprints on search engines to try to identify the owner."
},
{
"code": null,
"e": 26895,
"s": 26826,
"text": "It checks if the phone number that you have searched, exists or not."
},
{
"code": null,
"e": 26985,
"s": 26895,
"text": "It gathers information about phone numbers such as country, area, carrier, and line type."
},
{
"code": null,
"e": 27071,
"s": 26985,
"text": "OSINT footprints using external APIs, Google Hacking, search engine, and phone books."
},
{
"code": null,
"e": 27145,
"s": 27071,
"text": "Check for reputation reports, social media, disposable numbers, and more."
},
{
"code": null,
"e": 27175,
"s": 27145,
"text": "Scan several numbers at once."
},
{
"code": null,
"e": 27212,
"s": 27175,
"text": "Run your web instances as a service."
},
{
"code": null,
"e": 27222,
"s": 27212,
"text": "Important"
},
{
"code": null,
"e": 27257,
"s": 27222,
"text": "It does not allow to hack a phone."
},
{
"code": null,
"e": 27310,
"s": 27257,
"text": "It does not allow to get the precise phone location."
},
{
"code": null,
"e": 27371,
"s": 27310,
"text": "It does not allow to track phone or it’s owner in real time."
},
{
"code": null,
"e": 27438,
"s": 27371,
"text": "Follow the below steps to use PhoneInfoga on Google Cloud Console:"
},
{
"code": null,
"e": 27546,
"s": 27438,
"text": "Step 1: Log in to Google Cloud Console using any of your google accounts and click on the icon shown below."
},
{
"code": null,
"e": 27666,
"s": 27546,
"text": "(This is actually launching your Google cloud shell and giving you access to a machine where you can use “PhoneInfoga“)"
},
{
"code": null,
"e": 27800,
"s": 27666,
"text": "Step 2: Now there 2 options, either you can install PhoneInfoga like an application just by typing these commands into your terminal."
},
{
"code": null,
"e": 27846,
"s": 27800,
"text": "Or, you can go the easier way and use Docker."
},
{
"code": null,
"e": 27969,
"s": 27846,
"text": "Step 3: Since the Google cloud console has already installed docker, we can go ahead and type this command on the console."
},
{
"code": null,
"e": 28060,
"s": 27969,
"text": "Step 4: Press enter after typing the command and your console should be looking like this."
},
{
"code": null,
"e": 28182,
"s": 28060,
"text": "Step 5: Now we are going to run it, enter this command and at the end of it type the phone number with the country code: "
},
{
"code": null,
"e": 28240,
"s": 28182,
"text": "docker run -it sundowndev/phoneinfoga scan -n 13526006900"
},
{
"code": null,
"e": 28324,
"s": 28240,
"text": "Step 6: Let’s see what all the information we were able to get using “PhoneInfoga“."
},
{
"code": null,
"e": 28474,
"s": 28324,
"text": "As you can see, PhoneInfoga first ran numverify scan to check whether the number exists or not, and it returned, ‘true’ indicating the number exists."
},
{
"code": null,
"e": 28601,
"s": 28474,
"text": "We can also see that the location is, ‘Weekichspg‘ and the line type is of landline. Let’s further see what else we have here,"
},
{
"code": null,
"e": 28884,
"s": 28601,
"text": "We can see here the social media footprints like on which social media platform this number is used to create an account. So it is quite clear that a tool like PhoneInfoga can prove to be very useful in gathering information on international phone numbers using only free resources."
},
{
"code": null,
"e": 28900,
"s": 28884,
"text": "Cloud-Computing"
},
{
"code": null,
"e": 28922,
"s": 28900,
"text": "Google Cloud Platform"
},
{
"code": null,
"e": 28933,
"s": 28922,
"text": "Linux-Unix"
},
{
"code": null,
"e": 29031,
"s": 28933,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29084,
"s": 29031,
"text": "Must Do Coding Questions for Product Based Companies"
},
{
"code": null,
"e": 29139,
"s": 29084,
"text": "How to calculate MOVING AVERAGE in a Pandas DataFrame?"
},
{
"code": null,
"e": 29184,
"s": 29139,
"text": "What is Transmission Control Protocol (TCP)?"
},
{
"code": null,
"e": 29225,
"s": 29184,
"text": "Difference Between Skewness and Kurtosis"
},
{
"code": null,
"e": 29283,
"s": 29225,
"text": "How to Convert Categorical Variable to Numeric in Pandas?"
},
{
"code": null,
"e": 29323,
"s": 29283,
"text": "Sed Command in Linux/Unix with examples"
},
{
"code": null,
"e": 29363,
"s": 29323,
"text": "AWK command in Unix/Linux with examples"
},
{
"code": null,
"e": 29390,
"s": 29363,
"text": "grep command in Unix/Linux"
},
{
"code": null,
"e": 29425,
"s": 29390,
"text": "cut command in Linux with examples"
}
] |
Explain how to define a variable in SASS - GeeksforGeeks
|
09 Nov, 2021
SASS is a short form of Syntactically Awesome Style Sheet which is an extension to Cascading StyleSheet (CSS). It is a preprocessor of CSS. It is compiled to CSS & is fully compatible with every version of CSS. Sass reduces the repetition of CSS and hence saves time. It allows using the variables, nested rules, mixins, functions, and more, all with a fully CSS-compatible syntax. It helps to organize a complex & large structured stylesheet in a well-organized manner & hence facilitates the reusability of code. It is an open-source free to use extension designed by Hampton Catlin and developed by Natalie Weizenbaum and Chris Eppstein in 2006.
Sass introduces several features that do not exist in CSS like variables that can be used to store data or information that you can use later. It is an important feature of Sass. In this article, we will learn how to define a variable in Sass & will understand its implementation through the example.
Sass Variables:
Sass variables are declared once to store data that can be reused whenever required.
If you modify the variable value once, the changes are reflected in all places whenever the variables are used.
In Sass, we can store data in multiple types such as Numbers, Strings, booleans, lists, nulls, etc.
Sass uses the dollar symbol ($) to declare a variable followed by the specified variable name and the value of that variable separated by a colon (:). The line must end with a semicolon (;). The variables can also be used with other values.
You can also use underscores ( _ ) or Hyphen ( – ) to declare descriptive variable names.
We can enhance the efficiency of Sass by performing multiple math operations on variables.
Syntax:
$var_Name : var-value;
Example: The below examples will demonstrate how to define variables in SASS.
Filename: style.scss
// Global variable declaration
$global__light: #f9f9f9;
$global__dark: #000;
$global__font: ("Poppins");
$global__f_size: 26;
$global__Max_width: 1280px;
div {
$local__green: #00f034;
// Global variable called
color: $global__dark;
border: 1px solid $local__green;
font: $global__font;
// Global variable called
max-width: $global__Max_width;
}
$global_sky: #0000ff;
p {
// Local variable declare
$local__margin: 10px 5px 20px 0;
color: $global__dark;
border: 1px solid $global_sky;
font-size: $global__f_size;
// Local variable called
margin: $local__margin;
}
Output: The generated CSS output will be:
Filename: style.css
div {
/* Global variable called */
color: #000;
border: 1px solid #00f034;
font-family: "Poppins";
/* Global variable called */
max-width: 1280px;
}
p {
color: #000;
border: 1px solid #0000ff;
font-size: 26;
/* Local variable called */
margin: 10px 5px 20px 0;
}
/*# sourceMappingURL=style.css.map */
Example: This example illustrates the SASS variables which is compiled to CSS variables & defining its scopes.
HTML
<!DOCTYPE html><html> <head> <title>Sass Variable</title> <style> div { /* Global variable called */ color: #000; border: 1px solid #00f034; font-family: "Poppins"; /* Global variable called */ max-width: 1280px; } p { color: #000; border: 1px solid #0000ff; font-size: 26; /* Local variable called */ margin: 10px 5px 20px 0; } </style></head> <body> <div>Welcome to GeeksforGeeks</div> <p>A Computer Science portal for geeks.</p></body> </html>
Output:
Scope of a Sass variable: Like other languages, Sass also has the concept of scope. In Sass, you can declare the scope of variable in two ways those are as follows:
Global variables
Local variables
Examples: Here, we can see how we can use the scope of Sass variables.
Global Variable Scope: Global variables are declared at the top of the file and you can use them anywhere in the code. You can also use !global to declare a local variable as a global variable.
Filename: style.scss
// It is a global variable
$clr_primary: #a9a5f4;
div {
// Local variable with global scope
$clr_dark: #000 !global;
background-color: $clr_primary;
}
p {
background-color: $clr_dark;
}
And the generated CSS output will be:
Filename: style.css
div {
// Here, clr_primary variable assigned
background-color: #a9a5f4;
}
p {
// Here, clr_dark variable assigned
background-color: #000;
}
Local Variable: Variables, which are declared in block or with parenthesis {} ie., inside the curly braces, are local variables and you can’t use them outside of the scope of that particular block.
If you try to use variable outside scope, this will generate an error saying “Compilation Error: Undefined variable”, as shown below example.
div {
$clr__dark: #000; // local variable
background-color: $clr_dark;
}
p {
// We cannot use this variable here.
// It will throw an error.
background-color: $clr_dark;
}
Style.scss:
div {
// Local variable scope
$clr_light: #f9f9f9;
background-color: $clr_light;
}
p {
// Local variable scope
$clr_dark: #000;
background-color: $clr_dark;
}
style.css: The generated CSS output will be:
div {
// Here, clr_light variable assigned
background-color: #f9f9f9;
}
p {
// Here, clr_dark variable assigned
background-color: #000;
}
Example: This example illustrates the use of the SASS variables by compiling it to CSS variables.
HTML
<!DOCTYPE html><html> <head> <title>Sass Variable</title> <style> div { /* Here, clr_light variable assigned */ background-color: #f9f9f9; } p { /* Here, clr_dark variable assigned */ background-color: #000; } </style></head> <body> <div>Welcome to GeeksforGeeks</div> <p>A Computer Science portal for geeks.</p></body> </html>
Output:
Difference between Sass variable & CSS variables:
All the variables are compiled in Sass.
The variables is included in the CSS output & need not compile them.
The Sass variables contain only one value at a time.
The CSS variables can contain different values for different elements.
The Sass variables are imperative ie., if the values of the variables are changed that we have used then its previous used values will remain the same.
The CSS variables are declarative ie., if we change the value of the variable then it will affect the both the values which is previous used values & later used values.
Reference: https://sass-lang.com/documentation
CSS-Questions
Picked
SASS
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Design a web page using HTML and CSS
Form validation using jQuery
How to set space between the flexbox ?
Search Bar using HTML, CSS and JavaScript
How to Create Time-Table schedule using HTML ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Convert a string to an integer in JavaScript
Top 10 Angular Libraries For Web Developers
|
[
{
"code": null,
"e": 25376,
"s": 25348,
"text": "\n09 Nov, 2021"
},
{
"code": null,
"e": 26025,
"s": 25376,
"text": "SASS is a short form of Syntactically Awesome Style Sheet which is an extension to Cascading StyleSheet (CSS). It is a preprocessor of CSS. It is compiled to CSS & is fully compatible with every version of CSS. Sass reduces the repetition of CSS and hence saves time. It allows using the variables, nested rules, mixins, functions, and more, all with a fully CSS-compatible syntax. It helps to organize a complex & large structured stylesheet in a well-organized manner & hence facilitates the reusability of code. It is an open-source free to use extension designed by Hampton Catlin and developed by Natalie Weizenbaum and Chris Eppstein in 2006."
},
{
"code": null,
"e": 26326,
"s": 26025,
"text": "Sass introduces several features that do not exist in CSS like variables that can be used to store data or information that you can use later. It is an important feature of Sass. In this article, we will learn how to define a variable in Sass & will understand its implementation through the example."
},
{
"code": null,
"e": 26343,
"s": 26326,
"text": "Sass Variables: "
},
{
"code": null,
"e": 26428,
"s": 26343,
"text": "Sass variables are declared once to store data that can be reused whenever required."
},
{
"code": null,
"e": 26540,
"s": 26428,
"text": "If you modify the variable value once, the changes are reflected in all places whenever the variables are used."
},
{
"code": null,
"e": 26640,
"s": 26540,
"text": "In Sass, we can store data in multiple types such as Numbers, Strings, booleans, lists, nulls, etc."
},
{
"code": null,
"e": 26881,
"s": 26640,
"text": "Sass uses the dollar symbol ($) to declare a variable followed by the specified variable name and the value of that variable separated by a colon (:). The line must end with a semicolon (;). The variables can also be used with other values."
},
{
"code": null,
"e": 26971,
"s": 26881,
"text": "You can also use underscores ( _ ) or Hyphen ( – ) to declare descriptive variable names."
},
{
"code": null,
"e": 27062,
"s": 26971,
"text": "We can enhance the efficiency of Sass by performing multiple math operations on variables."
},
{
"code": null,
"e": 27071,
"s": 27062,
"text": "Syntax: "
},
{
"code": null,
"e": 27094,
"s": 27071,
"text": "$var_Name : var-value;"
},
{
"code": null,
"e": 27172,
"s": 27094,
"text": "Example: The below examples will demonstrate how to define variables in SASS."
},
{
"code": null,
"e": 27193,
"s": 27172,
"text": "Filename: style.scss"
},
{
"code": null,
"e": 27791,
"s": 27193,
"text": "// Global variable declaration\n$global__light: #f9f9f9;\n$global__dark: #000;\n$global__font: (\"Poppins\");\n$global__f_size: 26;\n$global__Max_width: 1280px;\n\ndiv {\n $local__green: #00f034;\n \n // Global variable called\n color: $global__dark;\n border: 1px solid $local__green;\n font: $global__font;\n\n // Global variable called\n max-width: $global__Max_width;\n}\n\n$global_sky: #0000ff;\n\np {\n\n // Local variable declare\n $local__margin: 10px 5px 20px 0;\n color: $global__dark;\n border: 1px solid $global_sky;\n font-size: $global__f_size;\n\n // Local variable called\n margin: $local__margin;\n}"
},
{
"code": null,
"e": 27833,
"s": 27791,
"text": "Output: The generated CSS output will be:"
},
{
"code": null,
"e": 27853,
"s": 27833,
"text": "Filename: style.css"
},
{
"code": null,
"e": 28181,
"s": 27853,
"text": "div {\n\n /* Global variable called */\n color: #000;\n border: 1px solid #00f034;\n font-family: \"Poppins\";\n\n /* Global variable called */\n max-width: 1280px;\n}\n\np {\n color: #000;\n border: 1px solid #0000ff;\n font-size: 26;\n\n /* Local variable called */\n margin: 10px 5px 20px 0;\n}\n\n/*# sourceMappingURL=style.css.map */"
},
{
"code": null,
"e": 28292,
"s": 28181,
"text": "Example: This example illustrates the SASS variables which is compiled to CSS variables & defining its scopes."
},
{
"code": null,
"e": 28297,
"s": 28292,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Sass Variable</title> <style> div { /* Global variable called */ color: #000; border: 1px solid #00f034; font-family: \"Poppins\"; /* Global variable called */ max-width: 1280px; } p { color: #000; border: 1px solid #0000ff; font-size: 26; /* Local variable called */ margin: 10px 5px 20px 0; } </style></head> <body> <div>Welcome to GeeksforGeeks</div> <p>A Computer Science portal for geeks.</p></body> </html>",
"e": 28919,
"s": 28297,
"text": null
},
{
"code": null,
"e": 28927,
"s": 28919,
"text": "Output:"
},
{
"code": null,
"e": 29092,
"s": 28927,
"text": "Scope of a Sass variable: Like other languages, Sass also has the concept of scope. In Sass, you can declare the scope of variable in two ways those are as follows:"
},
{
"code": null,
"e": 29109,
"s": 29092,
"text": "Global variables"
},
{
"code": null,
"e": 29125,
"s": 29109,
"text": "Local variables"
},
{
"code": null,
"e": 29196,
"s": 29125,
"text": "Examples: Here, we can see how we can use the scope of Sass variables."
},
{
"code": null,
"e": 29390,
"s": 29196,
"text": "Global Variable Scope: Global variables are declared at the top of the file and you can use them anywhere in the code. You can also use !global to declare a local variable as a global variable."
},
{
"code": null,
"e": 29411,
"s": 29390,
"text": "Filename: style.scss"
},
{
"code": null,
"e": 29608,
"s": 29411,
"text": "// It is a global variable\n$clr_primary: #a9a5f4;\n\ndiv {\n\n // Local variable with global scope\n $clr_dark: #000 !global;\n background-color: $clr_primary;\n}\n\np {\n background-color: $clr_dark;\n}"
},
{
"code": null,
"e": 29646,
"s": 29608,
"text": "And the generated CSS output will be:"
},
{
"code": null,
"e": 29666,
"s": 29646,
"text": "Filename: style.css"
},
{
"code": null,
"e": 29817,
"s": 29666,
"text": "div {\n\n // Here, clr_primary variable assigned\n background-color: #a9a5f4;\n}\n\np {\n\n // Here, clr_dark variable assigned\n background-color: #000;\n}"
},
{
"code": null,
"e": 30016,
"s": 29817,
"text": "Local Variable: Variables, which are declared in block or with parenthesis {} ie., inside the curly braces, are local variables and you can’t use them outside of the scope of that particular block. "
},
{
"code": null,
"e": 30158,
"s": 30016,
"text": "If you try to use variable outside scope, this will generate an error saying “Compilation Error: Undefined variable”, as shown below example."
},
{
"code": null,
"e": 30342,
"s": 30158,
"text": "div {\n $clr__dark: #000; // local variable\n background-color: $clr_dark;\n}\n\np {\n\n // We cannot use this variable here.\n // It will throw an error.\n background-color: $clr_dark;\n}"
},
{
"code": null,
"e": 30354,
"s": 30342,
"text": "Style.scss:"
},
{
"code": null,
"e": 30528,
"s": 30354,
"text": "div {\n\n // Local variable scope\n $clr_light: #f9f9f9;\n background-color: $clr_light;\n}\n\np {\n\n // Local variable scope\n $clr_dark: #000;\n background-color: $clr_dark;\n}"
},
{
"code": null,
"e": 30573,
"s": 30528,
"text": "style.css: The generated CSS output will be:"
},
{
"code": null,
"e": 30722,
"s": 30573,
"text": "div {\n\n // Here, clr_light variable assigned\n background-color: #f9f9f9;\n}\n\np {\n\n // Here, clr_dark variable assigned\n background-color: #000;\n}"
},
{
"code": null,
"e": 30820,
"s": 30722,
"text": "Example: This example illustrates the use of the SASS variables by compiling it to CSS variables."
},
{
"code": null,
"e": 30825,
"s": 30820,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Sass Variable</title> <style> div { /* Here, clr_light variable assigned */ background-color: #f9f9f9; } p { /* Here, clr_dark variable assigned */ background-color: #000; } </style></head> <body> <div>Welcome to GeeksforGeeks</div> <p>A Computer Science portal for geeks.</p></body> </html>",
"e": 31253,
"s": 30825,
"text": null
},
{
"code": null,
"e": 31261,
"s": 31253,
"text": "Output:"
},
{
"code": null,
"e": 31311,
"s": 31261,
"text": "Difference between Sass variable & CSS variables:"
},
{
"code": null,
"e": 31351,
"s": 31311,
"text": "All the variables are compiled in Sass."
},
{
"code": null,
"e": 31420,
"s": 31351,
"text": "The variables is included in the CSS output & need not compile them."
},
{
"code": null,
"e": 31473,
"s": 31420,
"text": "The Sass variables contain only one value at a time."
},
{
"code": null,
"e": 31544,
"s": 31473,
"text": "The CSS variables can contain different values for different elements."
},
{
"code": null,
"e": 31696,
"s": 31544,
"text": "The Sass variables are imperative ie., if the values of the variables are changed that we have used then its previous used values will remain the same."
},
{
"code": null,
"e": 31865,
"s": 31696,
"text": "The CSS variables are declarative ie., if we change the value of the variable then it will affect the both the values which is previous used values & later used values."
},
{
"code": null,
"e": 31912,
"s": 31865,
"text": "Reference: https://sass-lang.com/documentation"
},
{
"code": null,
"e": 31926,
"s": 31912,
"text": "CSS-Questions"
},
{
"code": null,
"e": 31933,
"s": 31926,
"text": "Picked"
},
{
"code": null,
"e": 31938,
"s": 31933,
"text": "SASS"
},
{
"code": null,
"e": 31942,
"s": 31938,
"text": "CSS"
},
{
"code": null,
"e": 31959,
"s": 31942,
"text": "Web Technologies"
},
{
"code": null,
"e": 32057,
"s": 31959,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32066,
"s": 32057,
"text": "Comments"
},
{
"code": null,
"e": 32079,
"s": 32066,
"text": "Old Comments"
},
{
"code": null,
"e": 32116,
"s": 32079,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 32145,
"s": 32116,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 32184,
"s": 32145,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 32226,
"s": 32184,
"text": "Search Bar using HTML, CSS and JavaScript"
},
{
"code": null,
"e": 32273,
"s": 32226,
"text": "How to Create Time-Table schedule using HTML ?"
},
{
"code": null,
"e": 32315,
"s": 32273,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 32348,
"s": 32315,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 32391,
"s": 32348,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 32436,
"s": 32391,
"text": "Convert a string to an integer in JavaScript"
}
] |
Run Animation backward first and then forwards with CSS
|
Use the animation-direction property to run animation in first backward and then forward. The property is used with the alternate-reverse animation value to achieve this.
Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
div {
width: 150px;
height: 200px;
position: relative;
background-color: yellow;
animation-name: myanim;
animation-duration: 2s;
animation-direction: alternate-reverse;
animation-iteration-count: 3;
}
@keyframes myanim {
0% {background-color:green; left:0px; top:0px;}
50% {background-color:maroon; left:100px; top:100px;}
100% {background-color:gray; left:0px; top:0px;}
}
</style>
</head>
<body>
<div></div>
</body>
</html>
|
[
{
"code": null,
"e": 1233,
"s": 1062,
"text": "Use the animation-direction property to run animation in first backward and then forward. The property is used with the alternate-reverse animation value to achieve this."
},
{
"code": null,
"e": 1243,
"s": 1233,
"text": "Live Demo"
},
{
"code": null,
"e": 1905,
"s": 1243,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <style>\n div {\n width: 150px;\n height: 200px;\n position: relative;\n background-color: yellow;\n animation-name: myanim;\n animation-duration: 2s;\n animation-direction: alternate-reverse;\n animation-iteration-count: 3;\n }\n @keyframes myanim {\n 0% {background-color:green; left:0px; top:0px;}\n 50% {background-color:maroon; left:100px; top:100px;}\n 100% {background-color:gray; left:0px; top:0px;}\n }\n </style>\n </head>\n <body>\n <div></div>\n </body>\n</html>"
}
] |
Can we return Result sets in JDBC?
|
Yes, just like any other objects in Java we can pass a ResultSet object as a parameter to a method and, return it from a method.
Let us create a table with name MyPlayers in MySQL database using CREATE statement as shown below −
CREATE TABLE MyPlayers(
ID INT,
First_Name VARCHAR(255),
Last_Name VARCHAR(255),
Date_Of_Birth date,
Place_Of_Birth VARCHAR(255),
Country VARCHAR(255),
PRIMARY KEY (ID)
);
Now, we will insert 7 records in MyPlayers table using INSERT statements −
insert into MyPlayers values(1, 'Shikhar', 'Dhawan', DATE('1981-12-05'), 'Delhi', 'India');
insert into MyPlayers values(2, 'Jonathan', 'Trott', DATE('1981-04-22'), 'CapeTown', 'SouthAfrica');
insert into MyPlayers values(3, 'Kumara', 'Sangakkara', DATE('1977-10-27'), 'Matale', 'Srilanka');
insert into MyPlayers values(4, 'Virat', 'Kohli', DATE('1988-11-05'), 'Delhi', 'India');
insert into MyPlayers values(5, 'Rohit', 'Sharma', DATE('1987-04-30'), 'Nagpur', 'India');
insert into MyPlayers values(6, 'Ravindra', 'Jadeja', DATE('1988-12-06'), 'Nagpur', 'India');
insert into MyPlayers values(7, 'James', 'Anderson', DATE('1982-06-30'), 'Burnley', 'England');
In the Following JDBC example the retrieveData() method establishes a connection with the database and retrieve the contents of the table MyPlayers in to a ResultSet object and returns it.
The main method invokes the retrieveData() method and prints the contents of the obtained ResultSet.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class ReturningResultSet {
public static ResultSet retrieveData() throws SQLException{
//Registering the Driver
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
//Getting the connection
String mysqlUrl = "jdbc:mysql://localhost/mydatabase";
Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
System.out.println("Connection established......");
//Creating a Statement object
Statement stmt = con.createStatement();
//Retrieving the data
ResultSet rs = stmt.executeQuery("select * from MyPlayers");
return rs;
}
public static void main(String args[]) throws Exception {
//Getting the ResultSet object from the retrieveData() method
ResultSet rs = retrieveData();
System.out.println("Contents of the Table MyPlayers: ");
while(rs.next()) {
System.out.print(rs.getInt("ID")+", ");
System.out.print(rs.getString("First_Name")+", ");
System.out.print(rs.getString("Last_Name")+", ");
System.out.print(rs.getDate("Date_Of_Birth")+", ");
System.out.print(rs.getString("Place_Of_Birth")+", ");
System.out.print(rs.getString("Country"));
System.out.println();
}
}
}
Connection established......
Contents of the Table MyPlayers:
1, Shikhar, Dhawan, 1981-12-05, Delhi, India
2, Jonathan, Trott, 1981-04-22, CapeTown, SouthAfrica
3, Kumara, Sangakkara, 1977-10-27, Matale, Srilanka
4, Virat, Kohli, 1988-11-05, Mumbai, India
5, Rohit, Sharma, 1987-04-30, Nagpur, India
6, Ravindra, Jadeja, 1988-12-06, Nagpur, India
7, James, Anderson, 1982-06-30, Burnely, England
8, Ryan, McLaren, 1983-02-09, Kumberly, null
|
[
{
"code": null,
"e": 1191,
"s": 1062,
"text": "Yes, just like any other objects in Java we can pass a ResultSet object as a parameter to a method and, return it from a method."
},
{
"code": null,
"e": 1291,
"s": 1191,
"text": "Let us create a table with name MyPlayers in MySQL database using CREATE statement as shown below −"
},
{
"code": null,
"e": 1484,
"s": 1291,
"text": "CREATE TABLE MyPlayers(\n ID INT,\n First_Name VARCHAR(255),\n Last_Name VARCHAR(255),\n Date_Of_Birth date,\n Place_Of_Birth VARCHAR(255),\n Country VARCHAR(255),\n PRIMARY KEY (ID)\n);"
},
{
"code": null,
"e": 1559,
"s": 1484,
"text": "Now, we will insert 7 records in MyPlayers table using INSERT statements −"
},
{
"code": null,
"e": 2221,
"s": 1559,
"text": "insert into MyPlayers values(1, 'Shikhar', 'Dhawan', DATE('1981-12-05'), 'Delhi', 'India');\ninsert into MyPlayers values(2, 'Jonathan', 'Trott', DATE('1981-04-22'), 'CapeTown', 'SouthAfrica');\ninsert into MyPlayers values(3, 'Kumara', 'Sangakkara', DATE('1977-10-27'), 'Matale', 'Srilanka');\ninsert into MyPlayers values(4, 'Virat', 'Kohli', DATE('1988-11-05'), 'Delhi', 'India');\ninsert into MyPlayers values(5, 'Rohit', 'Sharma', DATE('1987-04-30'), 'Nagpur', 'India');\ninsert into MyPlayers values(6, 'Ravindra', 'Jadeja', DATE('1988-12-06'), 'Nagpur', 'India');\ninsert into MyPlayers values(7, 'James', 'Anderson', DATE('1982-06-30'), 'Burnley', 'England');"
},
{
"code": null,
"e": 2410,
"s": 2221,
"text": "In the Following JDBC example the retrieveData() method establishes a connection with the database and retrieve the contents of the table MyPlayers in to a ResultSet object and returns it."
},
{
"code": null,
"e": 2511,
"s": 2410,
"text": "The main method invokes the retrieveData() method and prints the contents of the obtained ResultSet."
},
{
"code": null,
"e": 3923,
"s": 2511,
"text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.ResultSet;\nimport java.sql.SQLException;\nimport java.sql.Statement;\npublic class ReturningResultSet {\n public static ResultSet retrieveData() throws SQLException{\n //Registering the Driver\n DriverManager.registerDriver(new com.mysql.jdbc.Driver());\n //Getting the connection\n String mysqlUrl = \"jdbc:mysql://localhost/mydatabase\";\n Connection con = DriverManager.getConnection(mysqlUrl, \"root\", \"password\");\n System.out.println(\"Connection established......\");\n //Creating a Statement object\n Statement stmt = con.createStatement();\n //Retrieving the data\n ResultSet rs = stmt.executeQuery(\"select * from MyPlayers\");\n return rs;\n }\n public static void main(String args[]) throws Exception {\n //Getting the ResultSet object from the retrieveData() method\n ResultSet rs = retrieveData();\n System.out.println(\"Contents of the Table MyPlayers: \");\n while(rs.next()) {\n System.out.print(rs.getInt(\"ID\")+\", \");\n System.out.print(rs.getString(\"First_Name\")+\", \");\n System.out.print(rs.getString(\"Last_Name\")+\", \");\n System.out.print(rs.getDate(\"Date_Of_Birth\")+\", \");\n System.out.print(rs.getString(\"Place_Of_Birth\")+\", \");\n System.out.print(rs.getString(\"Country\"));\n System.out.println();\n }\n }\n}"
},
{
"code": null,
"e": 4364,
"s": 3923,
"text": "Connection established......\nContents of the Table MyPlayers:\n1, Shikhar, Dhawan, 1981-12-05, Delhi, India\n2, Jonathan, Trott, 1981-04-22, CapeTown, SouthAfrica\n3, Kumara, Sangakkara, 1977-10-27, Matale, Srilanka\n4, Virat, Kohli, 1988-11-05, Mumbai, India\n5, Rohit, Sharma, 1987-04-30, Nagpur, India\n6, Ravindra, Jadeja, 1988-12-06, Nagpur, India\n7, James, Anderson, 1982-06-30, Burnely, England\n8, Ryan, McLaren, 1983-02-09, Kumberly, null"
}
] |
How to convert Long array list to long array in Java?
|
Firstly, declare a Long array list and add some elements to it:
ArrayList < Long > arrList = new ArrayList < Long > ();
arrList.add(100000 L);
arrList.add(200000 L);
arrList.add(300000 L);
arrList.add(400000 L);
arrList.add(500000 L);
Now, set the same size for the newly created long array:
final long[] arr = new long[arrList.size()];
int index = 0;
Each and every element of the Long array list is assigned to the long array:
for (final Long value : arrList) {
arr[index++] = value;
}
import java.util.ArrayList;
public class Demo {
public static void main(String[] args) {
ArrayList<<Long> arrList = new ArrayList<Long>();
arrList.add(100000L);
arrList.add(200000L);
arrList.add(300000L);
arrList.add(400000L);
arrList.add(500000L);
arrList.add(600000L);
arrList.add(700000L);
arrList.add(800000L);
arrList.add(900000L);
arrList.add(1000000L);
final long[] arr = new long[arrList.size()];
int index = 0;
for (final Long value : arrList) {
arr[index++] = value;
}
System.out.println("Elements of Long array...");
for (Long i : arr) {
System.out.println(i);
}
}
}
Elements of Long array...
100000
200000
300000
400000
500000
600000
700000
800000
900000
1000000
|
[
{
"code": null,
"e": 1126,
"s": 1062,
"text": "Firstly, declare a Long array list and add some elements to it:"
},
{
"code": null,
"e": 1297,
"s": 1126,
"text": "ArrayList < Long > arrList = new ArrayList < Long > ();\narrList.add(100000 L);\narrList.add(200000 L);\narrList.add(300000 L);\narrList.add(400000 L);\narrList.add(500000 L);"
},
{
"code": null,
"e": 1354,
"s": 1297,
"text": "Now, set the same size for the newly created long array:"
},
{
"code": null,
"e": 1414,
"s": 1354,
"text": "final long[] arr = new long[arrList.size()];\nint index = 0;"
},
{
"code": null,
"e": 1491,
"s": 1414,
"text": "Each and every element of the Long array list is assigned to the long array:"
},
{
"code": null,
"e": 1553,
"s": 1491,
"text": "for (final Long value : arrList) {\n arr[index++] = value;\n}"
},
{
"code": null,
"e": 2263,
"s": 1553,
"text": "import java.util.ArrayList;\npublic class Demo {\n public static void main(String[] args) {\n ArrayList<<Long> arrList = new ArrayList<Long>();\n arrList.add(100000L);\n arrList.add(200000L);\n arrList.add(300000L);\n arrList.add(400000L);\n arrList.add(500000L);\n arrList.add(600000L);\n arrList.add(700000L);\n arrList.add(800000L);\n arrList.add(900000L);\n arrList.add(1000000L);\n final long[] arr = new long[arrList.size()];\n int index = 0;\n for (final Long value : arrList) {\n arr[index++] = value;\n }\n System.out.println(\"Elements of Long array...\");\n for (Long i : arr) {\n System.out.println(i);\n }\n }\n}"
},
{
"code": null,
"e": 2360,
"s": 2263,
"text": "Elements of Long array...\n100000\n200000\n300000\n400000\n500000\n600000\n700000\n800000\n900000\n1000000"
}
] |
Python Number seed() Method
|
Python number method seed() sets the integer starting value used in generating random numbers. Call this function before calling any other random module function.
Following is the syntax for seed() method −
seed ( [x] )
Note − This function is not accessible directly, so we need to import the random module and then we need to call this function using random static object.
x − This is the seed for the next random number. If omitted, then it takes system time to generate next random number.
x − This is the seed for the next random number. If omitted, then it takes system time to generate next random number.
This method does not return any value.
The following example shows the usage of seed() method.
#!/usr/bin/python
import random
random.seed( 10 )
print "Random number with seed 10 : ", random.random()
# It will generate same random number
random.seed( 10 )
print "Random number with seed 10 : ", random.random()
# It will generate same random number
random.seed( 10 )
print "Random number with seed 10 : ", random.random()
When we run above program, it produces following result −
Random number with seed 10 : 0.57140259469
Random number with seed 10 : 0.57140259469
Random number with seed 10 : 0.57140259469
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2407,
"s": 2244,
"text": "Python number method seed() sets the integer starting value used in generating random numbers. Call this function before calling any other random module function."
},
{
"code": null,
"e": 2451,
"s": 2407,
"text": "Following is the syntax for seed() method −"
},
{
"code": null,
"e": 2465,
"s": 2451,
"text": "seed ( [x] )\n"
},
{
"code": null,
"e": 2620,
"s": 2465,
"text": "Note − This function is not accessible directly, so we need to import the random module and then we need to call this function using random static object."
},
{
"code": null,
"e": 2739,
"s": 2620,
"text": "x − This is the seed for the next random number. If omitted, then it takes system time to generate next random number."
},
{
"code": null,
"e": 2858,
"s": 2739,
"text": "x − This is the seed for the next random number. If omitted, then it takes system time to generate next random number."
},
{
"code": null,
"e": 2897,
"s": 2858,
"text": "This method does not return any value."
},
{
"code": null,
"e": 2953,
"s": 2897,
"text": "The following example shows the usage of seed() method."
},
{
"code": null,
"e": 3283,
"s": 2953,
"text": "#!/usr/bin/python\nimport random\n\nrandom.seed( 10 )\nprint \"Random number with seed 10 : \", random.random()\n\n# It will generate same random number\nrandom.seed( 10 )\nprint \"Random number with seed 10 : \", random.random()\n\n# It will generate same random number\nrandom.seed( 10 )\nprint \"Random number with seed 10 : \", random.random()"
},
{
"code": null,
"e": 3341,
"s": 3283,
"text": "When we run above program, it produces following result −"
},
{
"code": null,
"e": 3474,
"s": 3341,
"text": "Random number with seed 10 : 0.57140259469\nRandom number with seed 10 : 0.57140259469\nRandom number with seed 10 : 0.57140259469\n"
},
{
"code": null,
"e": 3511,
"s": 3474,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 3527,
"s": 3511,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3560,
"s": 3527,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 3579,
"s": 3560,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3614,
"s": 3579,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 3636,
"s": 3614,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 3670,
"s": 3636,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 3698,
"s": 3670,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3733,
"s": 3698,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 3747,
"s": 3733,
"text": " Lets Kode It"
},
{
"code": null,
"e": 3780,
"s": 3747,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3797,
"s": 3780,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 3804,
"s": 3797,
"text": " Print"
},
{
"code": null,
"e": 3815,
"s": 3804,
"text": " Add Notes"
}
] |
How to assign a column value in a data frame based on another column in another R data frame?
|
To assign a column value based on another column, we can use ifelse function. The ifelse function checks whether the value in one column of one data frame matches the value in another column of another data frame by using equal sign (==) and then replace the original value with the new column if there is no match else returns the original value. Check out the below example to understand how it can be done.
Consider the below data frame −
Live Demo
> x1<-rpois(20,2)
> x2<-rpois(20,5)
> df1<-data.frame(x1,x2)
> df1
x1 x2
1 3 5
2 3 7
3 0 6
4 0 5
5 4 6
6 3 8
7 1 5
8 0 8
9 4 6
10 1 2
11 2 3
12 2 6
13 0 0
14 1 9
15 0 0
16 4 2
17 3 5
18 3 8
19 1 3
20 2 7
Live Demo
> y1<-rpois(20,2)
> y2<-rpois(20,5)
> df2<-data.frame(y1,y2)
> df2
y1 y2
1 3 8
2 4 11
3 3 8
4 2 2
5 1 3
6 1 4
7 1 7
8 1 2
9 5 2
10 2 4
11 2 3
12 1 3
13 1 5
14 3 4
15 0 3
16 2 5
17 3 5
18 1 7
19 5 10
20 2 6
Replacing values in x1 of df1, if x2 of df1 is same as y2 of df2 otherwise returning x1 in df1 −
> df1$x1<-ifelse(df1$x2==df2$y2,df2$y2,df1$x1)
> df1
x1 x2
1 3 5
2 3 7
3 0 6
4 0 5
5 4 6
6 3 8
7 1 5
8 0 8
9 4 6
10 1 2
11 3 3
12 2 6
13 0 0
14 1 9
15 0 0
16 4 2
17 5 5
18 3 8
19 1 3
20 2 7
|
[
{
"code": null,
"e": 1472,
"s": 1062,
"text": "To assign a column value based on another column, we can use ifelse function. The ifelse function checks whether the value in one column of one data frame matches the value in another column of another data frame by using equal sign (==) and then replace the original value with the new column if there is no match else returns the original value. Check out the below example to understand how it can be done."
},
{
"code": null,
"e": 1504,
"s": 1472,
"text": "Consider the below data frame −"
},
{
"code": null,
"e": 1514,
"s": 1504,
"text": "Live Demo"
},
{
"code": null,
"e": 1581,
"s": 1514,
"text": "> x1<-rpois(20,2)\n> x2<-rpois(20,5)\n> df1<-data.frame(x1,x2)\n> df1"
},
{
"code": null,
"e": 1749,
"s": 1581,
"text": " x1 x2\n1 3 5\n2 3 7\n3 0 6\n4 0 5\n5 4 6\n6 3 8\n7 1 5\n8 0 8\n9 4 6\n10 1 2\n11 2 3\n12 2 6\n13 0 0\n14 1 9\n15 0 0\n16 4 2\n17 3 5\n18 3 8\n19 1 3\n20 2 7"
},
{
"code": null,
"e": 1759,
"s": 1749,
"text": "Live Demo"
},
{
"code": null,
"e": 1826,
"s": 1759,
"text": "> y1<-rpois(20,2)\n> y2<-rpois(20,5)\n> df2<-data.frame(y1,y2)\n> df2"
},
{
"code": null,
"e": 1997,
"s": 1826,
"text": " y1 y2\n1 3 8\n2 4 11\n3 3 8\n4 2 2\n5 1 3\n6 1 4\n7 1 7\n8 1 2\n9 5 2\n10 2 4\n11 2 3\n12 1 3\n13 1 5\n14 3 4\n15 0 3\n16 2 5\n17 3 5\n18 1 7\n19 5 10\n20 2 6"
},
{
"code": null,
"e": 2094,
"s": 1997,
"text": "Replacing values in x1 of df1, if x2 of df1 is same as y2 of df2 otherwise returning x1 in df1 −"
},
{
"code": null,
"e": 2147,
"s": 2094,
"text": "> df1$x1<-ifelse(df1$x2==df2$y2,df2$y2,df1$x1)\n> df1"
},
{
"code": null,
"e": 2316,
"s": 2147,
"text": " x1 x2\n1 3 5\n2 3 7\n3 0 6\n4 0 5\n5 4 6\n6 3 8\n7 1 5\n8 0 8\n9 4 6\n10 1 2\n11 3 3\n12 2 6\n13 0 0\n14 1 9\n15 0 0\n16 4 2\n17 5 5\n18 3 8\n19 1 3\n20 2 7"
}
] |
Building Kriging Models in R. Utilizing Spatial Statistics Algorithms... | by Aisha Sikder, PhD | Towards Data Science
|
In our world today, we have access to enormous amounts of geo-tagged data. Instead of letting it sit in a database or text file, we have the ability to utilize that information in various ways enabling us to create new information for better decision making.
One of the benefits to spatial statistics models is being able to analyze any point is space by calculating the correlation between nearby points and the point of interest. There are a number of spatial models that can be used, but my favorite is Kriging. While other methods such as Geographically Weighted Regression (GWR) or Inverse Distance Weighting (IDW) can be useful exploratory tools, in my experience, Kriging tends to scale better as the data increases and, in many cases, makes more accurate predictions.
In this article, I show how Kriging in R can be utilized to make predictions and provide Tip & Tricks using the police station data from the City of Chicago (data found here). The goal is to make interpolations of the frequency of crime in the city of Chicago at any given point. This spatial statistics technique allows us to harness the data we have, build a model to explain the spatial structure of the area, and make predictions at any other latitudinal/longitudinal point in space based on that spatial structure.
Before we begin, I’d like to discuss the data set so that we understand what is being predicted. The data can be found here and I downloaded the csv onto my local drive. The file has 22 variables and over 7 million rows, but for this tutorial we will only be utilizing the coordinate points (Latitude and Longitude), the Primary Type of crime, and the Description of the crime.
[Tips & Tricks] It’s important to Krige only the value of a specific category type. This means that we can interpolate points for only one type of crime at a time, otherwise the interpolated points won’t make any sense. Thus, the specific crime that will be focused on is Criminal Damage To Vehicle and we will use Kriging to interpolate the frequency of this type of crime in the city of Chicago.
library(data.table)# fast read/write functionlibrary(dplyr)df_1 <- reported_crimes %>% filter(PrimaryType=='CRIMINAL DAMAGE') %>% filter(Description=='TO VEHICLE')df_2 <- df_1 %>% group_by(Latitude, Longitude) %>% count() %>% ungroup() %>% inner_join(df_1, by=c('Latitude', 'Longitude')) %>% distinct(Latitude, Longitude, .keep_all = TRUE) %>% select(Latitude, Longitude, n) %>% mutate(location_id = group_indices(., Latitude, Longitude))
Once we filter the data, count the frequency of that crime (with variable name n) at every unique location (Latitude and Longitude), and add an index for each unique location (location_id), the data will look similar to Figure 1.
The idea behind kriging is to use a limited set of data points to predict other nearby points in a given area. This method allows scientists in the field to only sample of small number of data points and interpolate the rest which saves time and money. Therefore, to simulate this approach, we can randomly take 10,000 points as the training set to build the model (shown in Figure 2(a)) .
random_generator <- sample(1:nrow(df_2), round(nrow(df_2)*.3), replace=F)train_df <- df_2 %>% filter(!location_id %in% random_generator) %>% slice(1:10000)
We then can use the model on a grid of points around the area of interest as shown in Figure 2(b). The grid of points were autogenerated by building a polygon and creating over 76,000 latitudinal/longitudinal points within the polygon (the code has been excluded from this article for brevity).
Once the data is prepped, the first step is to build a variogram and fit a curve function to it which can then be used to interpolate values for the grid of points. Thankfully, with the gstat package in R, this can be done easily using the variogram function.
coordinates(train_df) <- c("Longitude", "Latitude")proj4string(train_df) <- CRS("+proj=longlat +datum=WGS84")lzn.vgm <- variogram(log(n) ~ Latitude + Longitude, train_df, width=0.1)lzn.fit = fit.variogram(lzn.vgm, vgm(c("Gau", "Sph", "Mat", "Exp")), fit.kappa = TRUE)
[Tips & Tricks] The log function was used to ensure that all interpolated values remain positive. The exp function will be used to normalize the results in the ‘Let’s Krige’ section of this article.
The variogram and the curve function can be plotted to understand the spatial structure of our area and can be shown in Figure 3. Visually speaking, we can see that the curve function (Matern) can describe the autocorrelation between points relatively well. We can see that around 1.1 km, the point pairs are no longer spatially correlated.
We can now use this information to krige the grid of points using the krige function from the gstat package. As mentioned previously, the grid of points have already been generated and have been omitted from this article for brevity. However, any of the other points in the data that have not been included in the training set can be used to interpolate points and test the accuracy.
coordinates(grid) <- c("Longitude", "Latitude")proj4string(grid) <- CRS("+proj=longlat +datum=WGS84")lzn.kriged <-krige(log(n) ~ Latitude + Longitude, train_df, grid, model = lzn.fit, maxdist=10, nmax=50)# Retrieve interpolated valuespredicted <- lzn.kriged@data$var1.pred %>% as.data.frame() %>% rename(krige_pred = 1) %>% mutate(krige= exp(krige))variance <- lzn.kriged@data$var1.var %>% as.data.frame() %>% mutate(variance = exp(variance))
Figure 4(a) shows the points that were used to build the model and is zoomed into uptown Chicago to see the data points better. Once the code has been applied and the grid points have been kriged, we can see the predictions shown in Figure 4(b). Displayed are the hot spots of where the model calculates the highest frequencies for Criminal Damage To Vehicle as well as the areas that may have lower frequencies of that crime. Kriging fills in the blanks of the data we don’t have. While we may have many data points to choose from in Figure 4(a), not every point in this area is covered. For all those points that we don’t have, Kriging comes into play and fills in the holes adding coverage to the area as shown in Figure 4(b).
Eloquently stated by Esri,
Spatial analysis allows you to solve complex location-oriented problems and better understand where and what is occurring in your world. It goes beyond mere mapping to let you study the characteristics of places and the relationships between them. Spatial analysis lends new perspectives to your decision-making.
Understanding our data spatially is an important step in making predictions. This is one of the reasons I like kriging. When we build our variogram (shown in Figure 3), it is clear when the autocorrelation between points stops which tells us at what distance, the data is no longer relevant. The variogram is then utilized to make interpolations on new data.
While the visuals are always exciting, testing the accuracy of the model is vital before implementing it in the real world. Although it was not discussed in this article, tests were conducted to measure the accuracy of the model using the train/test split method on the data (14% training and 86% testing) with an RMSE of 1.81 and MAE of 0.80.
With spatial statistics, we can turn our intuition of how spatially correlated the data might be and mathematically calculate exactly at what point that correlation ends. I hope this article helps you to brainstorm what other data sets might be spatially correlated and how Kriging can help you understand it better!
|
[
{
"code": null,
"e": 430,
"s": 171,
"text": "In our world today, we have access to enormous amounts of geo-tagged data. Instead of letting it sit in a database or text file, we have the ability to utilize that information in various ways enabling us to create new information for better decision making."
},
{
"code": null,
"e": 947,
"s": 430,
"text": "One of the benefits to spatial statistics models is being able to analyze any point is space by calculating the correlation between nearby points and the point of interest. There are a number of spatial models that can be used, but my favorite is Kriging. While other methods such as Geographically Weighted Regression (GWR) or Inverse Distance Weighting (IDW) can be useful exploratory tools, in my experience, Kriging tends to scale better as the data increases and, in many cases, makes more accurate predictions."
},
{
"code": null,
"e": 1467,
"s": 947,
"text": "In this article, I show how Kriging in R can be utilized to make predictions and provide Tip & Tricks using the police station data from the City of Chicago (data found here). The goal is to make interpolations of the frequency of crime in the city of Chicago at any given point. This spatial statistics technique allows us to harness the data we have, build a model to explain the spatial structure of the area, and make predictions at any other latitudinal/longitudinal point in space based on that spatial structure."
},
{
"code": null,
"e": 1845,
"s": 1467,
"text": "Before we begin, I’d like to discuss the data set so that we understand what is being predicted. The data can be found here and I downloaded the csv onto my local drive. The file has 22 variables and over 7 million rows, but for this tutorial we will only be utilizing the coordinate points (Latitude and Longitude), the Primary Type of crime, and the Description of the crime."
},
{
"code": null,
"e": 2243,
"s": 1845,
"text": "[Tips & Tricks] It’s important to Krige only the value of a specific category type. This means that we can interpolate points for only one type of crime at a time, otherwise the interpolated points won’t make any sense. Thus, the specific crime that will be focused on is Criminal Damage To Vehicle and we will use Kriging to interpolate the frequency of this type of crime in the city of Chicago."
},
{
"code": null,
"e": 2694,
"s": 2243,
"text": "library(data.table)# fast read/write functionlibrary(dplyr)df_1 <- reported_crimes %>% filter(PrimaryType=='CRIMINAL DAMAGE') %>% filter(Description=='TO VEHICLE')df_2 <- df_1 %>% group_by(Latitude, Longitude) %>% count() %>% ungroup() %>% inner_join(df_1, by=c('Latitude', 'Longitude')) %>% distinct(Latitude, Longitude, .keep_all = TRUE) %>% select(Latitude, Longitude, n) %>% mutate(location_id = group_indices(., Latitude, Longitude))"
},
{
"code": null,
"e": 2924,
"s": 2694,
"text": "Once we filter the data, count the frequency of that crime (with variable name n) at every unique location (Latitude and Longitude), and add an index for each unique location (location_id), the data will look similar to Figure 1."
},
{
"code": null,
"e": 3314,
"s": 2924,
"text": "The idea behind kriging is to use a limited set of data points to predict other nearby points in a given area. This method allows scientists in the field to only sample of small number of data points and interpolate the rest which saves time and money. Therefore, to simulate this approach, we can randomly take 10,000 points as the training set to build the model (shown in Figure 2(a)) ."
},
{
"code": null,
"e": 3473,
"s": 3314,
"text": "random_generator <- sample(1:nrow(df_2), round(nrow(df_2)*.3), replace=F)train_df <- df_2 %>% filter(!location_id %in% random_generator) %>% slice(1:10000)"
},
{
"code": null,
"e": 3768,
"s": 3473,
"text": "We then can use the model on a grid of points around the area of interest as shown in Figure 2(b). The grid of points were autogenerated by building a polygon and creating over 76,000 latitudinal/longitudinal points within the polygon (the code has been excluded from this article for brevity)."
},
{
"code": null,
"e": 4028,
"s": 3768,
"text": "Once the data is prepped, the first step is to build a variogram and fit a curve function to it which can then be used to interpolate values for the grid of points. Thankfully, with the gstat package in R, this can be done easily using the variogram function."
},
{
"code": null,
"e": 4296,
"s": 4028,
"text": "coordinates(train_df) <- c(\"Longitude\", \"Latitude\")proj4string(train_df) <- CRS(\"+proj=longlat +datum=WGS84\")lzn.vgm <- variogram(log(n) ~ Latitude + Longitude, train_df, width=0.1)lzn.fit = fit.variogram(lzn.vgm, vgm(c(\"Gau\", \"Sph\", \"Mat\", \"Exp\")), fit.kappa = TRUE)"
},
{
"code": null,
"e": 4495,
"s": 4296,
"text": "[Tips & Tricks] The log function was used to ensure that all interpolated values remain positive. The exp function will be used to normalize the results in the ‘Let’s Krige’ section of this article."
},
{
"code": null,
"e": 4836,
"s": 4495,
"text": "The variogram and the curve function can be plotted to understand the spatial structure of our area and can be shown in Figure 3. Visually speaking, we can see that the curve function (Matern) can describe the autocorrelation between points relatively well. We can see that around 1.1 km, the point pairs are no longer spatially correlated."
},
{
"code": null,
"e": 5220,
"s": 4836,
"text": "We can now use this information to krige the grid of points using the krige function from the gstat package. As mentioned previously, the grid of points have already been generated and have been omitted from this article for brevity. However, any of the other points in the data that have not been included in the training set can be used to interpolate points and test the accuracy."
},
{
"code": null,
"e": 5669,
"s": 5220,
"text": "coordinates(grid) <- c(\"Longitude\", \"Latitude\")proj4string(grid) <- CRS(\"+proj=longlat +datum=WGS84\")lzn.kriged <-krige(log(n) ~ Latitude + Longitude, train_df, grid, model = lzn.fit, maxdist=10, nmax=50)# Retrieve interpolated valuespredicted <- lzn.kriged@data$var1.pred %>% as.data.frame() %>% rename(krige_pred = 1) %>% mutate(krige= exp(krige))variance <- lzn.kriged@data$var1.var %>% as.data.frame() %>% mutate(variance = exp(variance))"
},
{
"code": null,
"e": 6399,
"s": 5669,
"text": "Figure 4(a) shows the points that were used to build the model and is zoomed into uptown Chicago to see the data points better. Once the code has been applied and the grid points have been kriged, we can see the predictions shown in Figure 4(b). Displayed are the hot spots of where the model calculates the highest frequencies for Criminal Damage To Vehicle as well as the areas that may have lower frequencies of that crime. Kriging fills in the blanks of the data we don’t have. While we may have many data points to choose from in Figure 4(a), not every point in this area is covered. For all those points that we don’t have, Kriging comes into play and fills in the holes adding coverage to the area as shown in Figure 4(b)."
},
{
"code": null,
"e": 6426,
"s": 6399,
"text": "Eloquently stated by Esri,"
},
{
"code": null,
"e": 6739,
"s": 6426,
"text": "Spatial analysis allows you to solve complex location-oriented problems and better understand where and what is occurring in your world. It goes beyond mere mapping to let you study the characteristics of places and the relationships between them. Spatial analysis lends new perspectives to your decision-making."
},
{
"code": null,
"e": 7098,
"s": 6739,
"text": "Understanding our data spatially is an important step in making predictions. This is one of the reasons I like kriging. When we build our variogram (shown in Figure 3), it is clear when the autocorrelation between points stops which tells us at what distance, the data is no longer relevant. The variogram is then utilized to make interpolations on new data."
},
{
"code": null,
"e": 7442,
"s": 7098,
"text": "While the visuals are always exciting, testing the accuracy of the model is vital before implementing it in the real world. Although it was not discussed in this article, tests were conducted to measure the accuracy of the model using the train/test split method on the data (14% training and 86% testing) with an RMSE of 1.81 and MAE of 0.80."
}
] |
Binary Tree to BST | Practice | GeeksforGeeks
|
Given a Binary Tree, convert it to Binary Search Tree in such a way that keeps the original structure of Binary Tree intact.
Example 1:
Input:
1
/ \
2 3
Output: 1 2 3
Example 2:
Input:
1
/ \
2 3
/
4
Output: 1 2 3 4
Explanation:
The converted BST will be
3
/ \
2 4
/
1
Your Task:
You don't need to read input or print anything. Your task is to complete the function binaryTreeToBST() which takes the root of the Binary tree as input and returns the root of the BST. The driver code will print inorder traversal of the converted BST.
Expected Time Complexity: O(NLogN).
Expected Auxiliary Space: O(N).
Constraints:
1 <= Number of nodes <= 1000
-1
sikkusaurav1236 days ago
class Solution{ public: // The given root is the root of the Binary Tree // Return the root of the generated BST void solve(Node* root,vector<int>&v) { if(root!=NULL) { solve(root->left,v); v.push_back(root->data); solve(root->right,v); } } void solve2(Node* root,vector<int>&v,int &i) { if(root!=NULL) { solve2(root->left,v,i); root->data=v[i]; i++; solve2(root->right,v,i); } } Node *binaryTreeToBST (Node *root) { //Your code goes here vector<int>v; int i=0; solve(root,v); sort(v.begin(),v.end()); solve2(root,v,i); return root; }};
0
amarrajsmart1972 weeks ago
void inorderTree(Node *root,vector<int> &v) { if(!root) { return ; } inorderTree(root->left,v); v.push_back(root->data); inorderTree(root->right,v); } void inorderBST(Node* root,vector<int>&v,int &i) { if(!root) { return ; } inorderBST(root->left,v,i); root->data=v[i++]; inorderBST(root->right,v,i); } Node *binaryTreeToBST (Node *root) { //Your code goes here vector<int> v; int i=0; if(!root) return NULL; inorderTree(root,v); sort(v.begin(),v.end()); inorderBST(root,v,i); return root; }
+1
jaatgfg111 month ago
very ezz soln
class Solution{ public: void inorder(Node* root,vector<int>&v){ if(root==NULL){ return; } inorder(root->left,v); v.push_back(root->data); inorder(root->right,v); } Node* inorderbst(Node *root1,vector<int>v,int s,int e){ if(s>e){ return NULL; } int mid=(s+e)/2; root1=new Node(v[mid]); root1->left=inorderbst(root1->left,v,s,mid-1); root1->right=inorderbst(root1->right,v,mid+1,e); return root1; } Node *binaryTreeToBST (Node *root) { vector<int>v; inorder(root,v); sort(v.begin(),v.end()); Node* root1=NULL; int s=0; int e=v.size()-1; return inorderbst(root1,v,s,e); }};
+2
sfazal0001 month ago
void inorder_tree(node* root,vector<int> &v){ if(root == NULL) { return; } inorder_tree(root->left,v); v.push_back(root->data); inorder_tree(root->right,v);}
void inorder_BST(node* root , vector<int > &v,int &i){ if(root == NULL) { return ; } inorder_BST(root->left , v , i); root->data = v[i]; i++; inorder_BST(root->right, v, i);}
node* BTtoBST(node* root){ if(root == NULL) { return NULL; } vector<int> v; inorder_tree(root,v); sort(v.begin(),v.end()); int i=0; inorder_BST(root,v,i); return root;}
0
detroix072 months ago
Node* solve(vector<int> InOrder,int n,int InOrderStart,int InOrderEnd){ if(InOrderStart > InOrderEnd) return NULL; int mid = (InOrderStart+InOrderEnd)/2; Node* root = new Node(InOrder[mid]); root->left=solve(InOrder,n,InOrderStart,mid-1); root->right=solve(InOrder,n,mid+1,InOrderEnd); return root;} void InOrderTraversal (Node* root , vector<int> &InOrder) { if(root==NULL) return; InOrderTraversal(root->left,InOrder); InOrder.push_back(root->data); InOrderTraversal(root->right,InOrder);} Node *binaryTreeToBST (Node *root) { vector<int> InOrder; InOrderTraversal(root,InOrder); sort(InOrder.begin(),InOrder.end()); int n = InOrder.size(); Node* ans = solve(InOrder,n,0,n-1); return ans; }
+1
sfazal0002 months ago
void inorder_Tree(node* root , vector<int> &v){ if(root == NULL) { return ; } inorder_Tree(root->left,v); v.push_back(root->data); inorder_Tree(root->right,v); }
void inorder_BST(node* root , vector<int> &v, int &i){ if(root == NULL) { return ; } inorder_BST(root->left,v,i); root->data = v[i]; i++; inorder_BST(root->right,v,i); return ;}
node* binaryTreeToBST(node* root){ vector<int > v; if(root == NULL) { return root; } inorder_Tree(root,v); sort(v.begin(),v.end()); int i=0; inorder_BST(root,v,i); return root;}
+1
golaravi5552 months ago
int i=0; void solve(Node* root,vector<int>&v){ if(!root)return; solve(root->left,v); root->data=v[i++]; solve(root->right,v); } void inorder(Node *root,vector<int>&v){ if(!root)return; inorder(root->left,v); v.push_back(root->data); inorder(root->right,v); } Node *binaryTreeToBST (Node *root) { //Your code goes here vector<int>v; inorder(root,v); sort(v.begin(),v.end()); solve(root,v); return root; }
0
sanketbhagat2 months ago
SIMPLE JAVA SOLUTION
class Solution{
int idx;
void inorder(Node root, ArrayList<Integer> list, boolean write){
if(root==null) return;
inorder(root.left,list,write);
if(write) root.data = list.get(idx++);
else list.add(root.data);
inorder(root.right,list,write);
}
// The given root is the root of the Binary Tree
// Return the root of the generated BST
Node binaryTreeToBST(Node root){
// Your code here
ArrayList<Integer> list = new ArrayList<>();
inorder(root,list,false);
Collections.sort(list);
idx = 0;
inorder(root,list,true);
return root;
}
}
-1
hamidnourashraf2 months ago
class Solution:
# The given root is the root of the Binary Tree
# Return the root of the generated BST
def _inorder(self, root, res, res_val):
if root is None:
return
self._inorder(root.left, res, res_val)
res.append(root)
res_val.append(root.data)
self._inorder(root.right, res, res_val)
def binaryTreeToBST(self, root):
res = []
res_val = []
self._inorder(root, res, res_val)
res_val = sorted(res_val)
for i in range(len(res)):
res[i].data = res_val[i]
return root
0
guruprasadnb14022 months ago
void inorder(Node *root,vector<int>&ans){ if(root==NULL)return; inorder(root->left,ans); ans.push_back(root->data); inorder(root->right,ans); } void solve(Node *root,vector<int>ans,int &i){ if(i>=ans.size()||root==NULL)return; solve(root->left,ans,i); root->data=ans[i++]; solve(root->right,ans,i); } Node *binaryTreeToBST (Node *root) { //Your code goes here vector<int>ans; inorder(root,ans); int i=0; sort(ans.begin(),ans.end()); solve(root,ans,i); return root; }
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
|
[
{
"code": null,
"e": 353,
"s": 226,
"text": "Given a Binary Tree, convert it to Binary Search Tree in such a way that keeps the original structure of Binary Tree intact.\n "
},
{
"code": null,
"e": 364,
"s": 353,
"text": "Example 1:"
},
{
"code": null,
"e": 415,
"s": 364,
"text": "Input:\n 1\n / \\\n 2 3\nOutput: 1 2 3\n"
},
{
"code": null,
"e": 427,
"s": 415,
"text": "\nExample 2:"
},
{
"code": null,
"e": 596,
"s": 427,
"text": "Input:\n 1\n / \\\n 2 3\n / \n 4 \nOutput: 1 2 3 4\nExplanation:\nThe converted BST will be\n\n 3\n / \\\n 2 4\n /\n 1\n"
},
{
"code": null,
"e": 862,
"s": 598,
"text": "Your Task:\nYou don't need to read input or print anything. Your task is to complete the function binaryTreeToBST() which takes the root of the Binary tree as input and returns the root of the BST. The driver code will print inorder traversal of the converted BST."
},
{
"code": null,
"e": 931,
"s": 862,
"text": "\nExpected Time Complexity: O(NLogN).\nExpected Auxiliary Space: O(N)."
},
{
"code": null,
"e": 974,
"s": 931,
"text": "\nConstraints:\n1 <= Number of nodes <= 1000"
},
{
"code": null,
"e": 977,
"s": 974,
"text": "-1"
},
{
"code": null,
"e": 1002,
"s": 977,
"text": "sikkusaurav1236 days ago"
},
{
"code": null,
"e": 1712,
"s": 1002,
"text": "class Solution{ public: // The given root is the root of the Binary Tree // Return the root of the generated BST void solve(Node* root,vector<int>&v) { if(root!=NULL) { solve(root->left,v); v.push_back(root->data); solve(root->right,v); } } void solve2(Node* root,vector<int>&v,int &i) { if(root!=NULL) { solve2(root->left,v,i); root->data=v[i]; i++; solve2(root->right,v,i); } } Node *binaryTreeToBST (Node *root) { //Your code goes here vector<int>v; int i=0; solve(root,v); sort(v.begin(),v.end()); solve2(root,v,i); return root; }};"
},
{
"code": null,
"e": 1714,
"s": 1712,
"text": "0"
},
{
"code": null,
"e": 1741,
"s": 1714,
"text": "amarrajsmart1972 weeks ago"
},
{
"code": null,
"e": 2402,
"s": 1741,
"text": " void inorderTree(Node *root,vector<int> &v) { if(!root) { return ; } inorderTree(root->left,v); v.push_back(root->data); inorderTree(root->right,v); } void inorderBST(Node* root,vector<int>&v,int &i) { if(!root) { return ; } inorderBST(root->left,v,i); root->data=v[i++]; inorderBST(root->right,v,i); } Node *binaryTreeToBST (Node *root) { //Your code goes here vector<int> v; int i=0; if(!root) return NULL; inorderTree(root,v); sort(v.begin(),v.end()); inorderBST(root,v,i); return root; }"
},
{
"code": null,
"e": 2405,
"s": 2402,
"text": "+1"
},
{
"code": null,
"e": 2426,
"s": 2405,
"text": "jaatgfg111 month ago"
},
{
"code": null,
"e": 2441,
"s": 2426,
"text": "very ezz soln "
},
{
"code": null,
"e": 3184,
"s": 2443,
"text": "class Solution{ public: void inorder(Node* root,vector<int>&v){ if(root==NULL){ return; } inorder(root->left,v); v.push_back(root->data); inorder(root->right,v); } Node* inorderbst(Node *root1,vector<int>v,int s,int e){ if(s>e){ return NULL; } int mid=(s+e)/2; root1=new Node(v[mid]); root1->left=inorderbst(root1->left,v,s,mid-1); root1->right=inorderbst(root1->right,v,mid+1,e); return root1; } Node *binaryTreeToBST (Node *root) { vector<int>v; inorder(root,v); sort(v.begin(),v.end()); Node* root1=NULL; int s=0; int e=v.size()-1; return inorderbst(root1,v,s,e); }};"
},
{
"code": null,
"e": 3187,
"s": 3184,
"text": "+2"
},
{
"code": null,
"e": 3208,
"s": 3187,
"text": "sfazal0001 month ago"
},
{
"code": null,
"e": 3387,
"s": 3208,
"text": "void inorder_tree(node* root,vector<int> &v){ if(root == NULL) { return; } inorder_tree(root->left,v); v.push_back(root->data); inorder_tree(root->right,v);}"
},
{
"code": null,
"e": 3607,
"s": 3389,
"text": "void inorder_BST(node* root , vector<int > &v,int &i){ if(root == NULL) { return ; } inorder_BST(root->left , v , i); root->data = v[i]; i++; inorder_BST(root->right, v, i);} "
},
{
"code": null,
"e": 3820,
"s": 3609,
"text": "node* BTtoBST(node* root){ if(root == NULL) { return NULL; } vector<int> v; inorder_tree(root,v); sort(v.begin(),v.end()); int i=0; inorder_BST(root,v,i); return root;} "
},
{
"code": null,
"e": 3822,
"s": 3820,
"text": "0"
},
{
"code": null,
"e": 3844,
"s": 3822,
"text": "detroix072 months ago"
},
{
"code": null,
"e": 4615,
"s": 3844,
"text": "Node* solve(vector<int> InOrder,int n,int InOrderStart,int InOrderEnd){ if(InOrderStart > InOrderEnd) return NULL; int mid = (InOrderStart+InOrderEnd)/2; Node* root = new Node(InOrder[mid]); root->left=solve(InOrder,n,InOrderStart,mid-1); root->right=solve(InOrder,n,mid+1,InOrderEnd); return root;} void InOrderTraversal (Node* root , vector<int> &InOrder) { if(root==NULL) return; InOrderTraversal(root->left,InOrder); InOrder.push_back(root->data); InOrderTraversal(root->right,InOrder);} Node *binaryTreeToBST (Node *root) { vector<int> InOrder; InOrderTraversal(root,InOrder); sort(InOrder.begin(),InOrder.end()); int n = InOrder.size(); Node* ans = solve(InOrder,n,0,n-1); return ans; }"
},
{
"code": null,
"e": 4618,
"s": 4615,
"text": "+1"
},
{
"code": null,
"e": 4640,
"s": 4618,
"text": "sfazal0002 months ago"
},
{
"code": null,
"e": 4838,
"s": 4640,
"text": "void inorder_Tree(node* root , vector<int> &v){ if(root == NULL) { return ; } inorder_Tree(root->left,v); v.push_back(root->data); inorder_Tree(root->right,v); } "
},
{
"code": null,
"e": 5054,
"s": 4838,
"text": "void inorder_BST(node* root , vector<int> &v, int &i){ if(root == NULL) { return ; } inorder_BST(root->left,v,i); root->data = v[i]; i++; inorder_BST(root->right,v,i); return ;} "
},
{
"code": null,
"e": 5270,
"s": 5056,
"text": "node* binaryTreeToBST(node* root){ vector<int > v; if(root == NULL) { return root; } inorder_Tree(root,v); sort(v.begin(),v.end()); int i=0; inorder_BST(root,v,i); return root;}"
},
{
"code": null,
"e": 5275,
"s": 5272,
"text": "+1"
},
{
"code": null,
"e": 5299,
"s": 5275,
"text": "golaravi5552 months ago"
},
{
"code": null,
"e": 5815,
"s": 5299,
"text": "int i=0; void solve(Node* root,vector<int>&v){ if(!root)return; solve(root->left,v); root->data=v[i++]; solve(root->right,v); } void inorder(Node *root,vector<int>&v){ if(!root)return; inorder(root->left,v); v.push_back(root->data); inorder(root->right,v); } Node *binaryTreeToBST (Node *root) { //Your code goes here vector<int>v; inorder(root,v); sort(v.begin(),v.end()); solve(root,v); return root; }"
},
{
"code": null,
"e": 5817,
"s": 5815,
"text": "0"
},
{
"code": null,
"e": 5842,
"s": 5817,
"text": "sanketbhagat2 months ago"
},
{
"code": null,
"e": 5863,
"s": 5842,
"text": "SIMPLE JAVA SOLUTION"
},
{
"code": null,
"e": 6524,
"s": 5863,
"text": "class Solution{\n \n int idx;\n \n void inorder(Node root, ArrayList<Integer> list, boolean write){\n if(root==null) return;\n inorder(root.left,list,write);\n if(write) root.data = list.get(idx++);\n else list.add(root.data);\n inorder(root.right,list,write);\n }\n \n // The given root is the root of the Binary Tree\n // Return the root of the generated BST\n Node binaryTreeToBST(Node root){\n // Your code here\n ArrayList<Integer> list = new ArrayList<>();\n inorder(root,list,false);\n Collections.sort(list);\n idx = 0;\n inorder(root,list,true);\n return root;\n }\n}"
},
{
"code": null,
"e": 6527,
"s": 6524,
"text": "-1"
},
{
"code": null,
"e": 6555,
"s": 6527,
"text": "hamidnourashraf2 months ago"
},
{
"code": null,
"e": 7151,
"s": 6555,
"text": "class Solution:\n # The given root is the root of the Binary Tree\n # Return the root of the generated BST\n def _inorder(self, root, res, res_val):\n if root is None:\n return \n self._inorder(root.left, res, res_val)\n res.append(root)\n res_val.append(root.data)\n self._inorder(root.right, res, res_val)\n def binaryTreeToBST(self, root):\n res = []\n res_val = []\n self._inorder(root, res, res_val)\n res_val = sorted(res_val)\n for i in range(len(res)):\n res[i].data = res_val[i]\n return root"
},
{
"code": null,
"e": 7153,
"s": 7151,
"text": "0"
},
{
"code": null,
"e": 7182,
"s": 7153,
"text": "guruprasadnb14022 months ago"
},
{
"code": null,
"e": 7751,
"s": 7182,
"text": "void inorder(Node *root,vector<int>&ans){ if(root==NULL)return; inorder(root->left,ans); ans.push_back(root->data); inorder(root->right,ans); } void solve(Node *root,vector<int>ans,int &i){ if(i>=ans.size()||root==NULL)return; solve(root->left,ans,i); root->data=ans[i++]; solve(root->right,ans,i); } Node *binaryTreeToBST (Node *root) { //Your code goes here vector<int>ans; inorder(root,ans); int i=0; sort(ans.begin(),ans.end()); solve(root,ans,i); return root; }"
},
{
"code": null,
"e": 7897,
"s": 7751,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 7933,
"s": 7897,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 7943,
"s": 7933,
"text": "\nProblem\n"
},
{
"code": null,
"e": 7953,
"s": 7943,
"text": "\nContest\n"
},
{
"code": null,
"e": 8016,
"s": 7953,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 8164,
"s": 8016,
"text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 8372,
"s": 8164,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints."
},
{
"code": null,
"e": 8478,
"s": 8372,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Remove duplicate rows based on multiple columns using Dplyr in R - GeeksforGeeks
|
28 Jul, 2021
In this article, we will learn how to remove duplicate rows based on multiple columns using dplyr in R programming language.
Dataframe in use:
lang value usage
1 Java 21 21
2 C 21 21
3 Python 3 0
4 GO 5 99
5 RUST 180 44
6 Javascript 9 48
7 Cpp 12 53
8 Java 21 21
9 Julia 6 6
10 Typescript 0 8
11 Python 3 0
12 GO 6 6
distinct() function can be used to filter out the duplicate rows. We just have to pass our R object and the column name as an argument in the distinct() function.
Note: We have used this parameter “.keep_all= TRUE” in the function because by default its FALSE, and it will print only the distinct values of the specified column, but we want all the columns so we have to make it TRUE, such that it will print all the other columns along with the current column.
Syntax: distinct(df, column_name, .keep_all= TRUE)
Parameters:
df: dataframe object
column_name: column name based on which duplicate rows will be removed
Example: R program to remove duplicate rows based on single column
R
library(dplyr) df <- data.frame (lang =c ('Java','C','Python','GO','RUST','Javascript', 'Cpp','Java','Julia','Typescript','Python','GO'), value = c (21,21,3,5,180,9,12,21,6,0,3,6), usage =c(21,21,0,99,44,48,53,21,6,8,0,6)) distinct(df, lang, .keep_all= TRUE)
Output:
lang value usage
1 Java 21 21
2 C 21 21
3 Python 3 0
4 GO 5 99
5 RUST 180 44
6 Javascript 9 48
7 Cpp 12 53
8 Julia 6 6
9 Typescript 0 8
We can remove duplicate values on the basis of ‘value‘ & ‘usage‘ columns, bypassing those column names as an argument in the distinct function.
Syntax: distinct(df, col1,col2, .keep_all= TRUE)
Parameters:
df: dataframe object
col1,col2: column name based on which duplicate rows will be removed
Example: R program to remove duplicate rows based on multiple columns
R
library(dplyr) df <- data.frame (lang =c ('Java','C','Python','GO','RUST','Javascript', 'Cpp','Java','Julia','Typescript','Python','GO'), value = c (21,21,3,5,180,9,12,21,6,0,3,6), usage =c(21,21,0,99,44,48,53,21,6,8,0,6)) distinct(df, value, usage, .keep_all= TRUE)
Output:
lang value usage
1 Java 21 21
2 Python 3 0
3 GO 5 99
4 RUST 180 44
5 Javascript 9 48
6 Cpp 12 53
7 Julia 6 6
8 Typescript 0 8
In this case, we just have to pass the entire dataframe as an argument in distinct() function, it then checks for all the duplicate rows for all variables/columns and removes them.
Syntax: distinct(df)
Parameters:
df: dataframe object
Example: R program to remove all the duplicate rows from the database
R
library(dplyr) df <- data.frame (lang =c ('Java','C','Python','GO','RUST','Javascript', 'Cpp','Java','Julia','Typescript','Python','GO'), value = c (21,21,3,5,180,9,12,21,6,0,3,6), usage =c(21,21,0,99,44,48,53,21,6,8,0,6)) distinct(df)
Output:
lang value usage
1 Java 21 21
2 C 21 21
3 Python 3 0
4 GO 5 99
5 RUST 180 44
6 Javascript 9 48
7 Cpp 12 53
8 Julia 6 6
9 Typescript 0 8
10 GO 6 6
In this approach, we have used duplicated() to remove all the duplicate rows, here duplicated function is used to check for the duplicate rows, then the column names/variables are passed in the duplicated function.
Note: We have used the NOT(!) operator because we want to filter out or remove the duplicate rows since the duplicated function provides the duplicate rows we negate them using ‘!‘ operator.
Syntax:
df %>%
filter(!duplicated(cbind(col1, col2,..)))
Parameters:
col1,col2: Pass the names of columns based on which you want to remove duplicated values
cbind():It is used to bind together column names such that multiple column names can be used for filtering
duplicated(): returns the duplicate rows
Example: R program to remove duplicate using duplicate()
R
library(dplyr) df <- data.frame (lang =c ('Java','C','Python','GO','RUST','Javascript', 'Cpp','Java','Julia','Typescript','Python','GO'), value = c (21,21,3,5,180,9,12,21,6,0,3,6), usage =c(21,21,0,99,44,48,53,21,6,8,0,6)) df %>% filter(!duplicated(cbind(value, usage)))
Output:
lang value usage
1 Java 21 21
2 Python 3 0
3 GO 5 99
4 RUST 180 44
5 Javascript 9 48
6 Cpp 12 53
7 Julia 6 6
8 Typescript 0 8
Picked
R Dplyr
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Change Color of Bars in Barchart using ggplot2 in R
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
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?
R - if statement
How to import an Excel File into R ?
Time Series Analysis in R
|
[
{
"code": null,
"e": 24851,
"s": 24823,
"text": "\n28 Jul, 2021"
},
{
"code": null,
"e": 24976,
"s": 24851,
"text": "In this article, we will learn how to remove duplicate rows based on multiple columns using dplyr in R programming language."
},
{
"code": null,
"e": 24994,
"s": 24976,
"text": "Dataframe in use:"
},
{
"code": null,
"e": 25335,
"s": 24994,
"text": " lang value usage\n1 Java 21 21\n2 C 21 21\n3 Python 3 0\n4 GO 5 99\n5 RUST 180 44\n6 Javascript 9 48\n7 Cpp 12 53\n8 Java 21 21\n9 Julia 6 6\n10 Typescript 0 8\n11 Python 3 0\n12 GO 6 6"
},
{
"code": null,
"e": 25499,
"s": 25335,
"text": "distinct() function can be used to filter out the duplicate rows. We just have to pass our R object and the column name as an argument in the distinct() function. "
},
{
"code": null,
"e": 25799,
"s": 25499,
"text": "Note: We have used this parameter “.keep_all= TRUE” in the function because by default its FALSE, and it will print only the distinct values of the specified column, but we want all the columns so we have to make it TRUE, such that it will print all the other columns along with the current column. "
},
{
"code": null,
"e": 25850,
"s": 25799,
"text": "Syntax: distinct(df, column_name, .keep_all= TRUE)"
},
{
"code": null,
"e": 25862,
"s": 25850,
"text": "Parameters:"
},
{
"code": null,
"e": 25883,
"s": 25862,
"text": "df: dataframe object"
},
{
"code": null,
"e": 25954,
"s": 25883,
"text": "column_name: column name based on which duplicate rows will be removed"
},
{
"code": null,
"e": 26021,
"s": 25954,
"text": "Example: R program to remove duplicate rows based on single column"
},
{
"code": null,
"e": 26023,
"s": 26021,
"text": "R"
},
{
"code": "library(dplyr) df <- data.frame (lang =c ('Java','C','Python','GO','RUST','Javascript', 'Cpp','Java','Julia','Typescript','Python','GO'), value = c (21,21,3,5,180,9,12,21,6,0,3,6), usage =c(21,21,0,99,44,48,53,21,6,8,0,6)) distinct(df, lang, .keep_all= TRUE)",
"e": 26351,
"s": 26023,
"text": null
},
{
"code": null,
"e": 26359,
"s": 26351,
"text": "Output:"
},
{
"code": null,
"e": 26601,
"s": 26359,
"text": "lang value usage\n1 Java 21 21\n2 C 21 21\n3 Python 3 0\n4 GO 5 99\n5 RUST 180 44\n6 Javascript 9 48\n7 Cpp 12 53\n8 Julia 6 6\n9 Typescript 0 8"
},
{
"code": null,
"e": 26746,
"s": 26601,
"text": "We can remove duplicate values on the basis of ‘value‘ & ‘usage‘ columns, bypassing those column names as an argument in the distinct function. "
},
{
"code": null,
"e": 26795,
"s": 26746,
"text": "Syntax: distinct(df, col1,col2, .keep_all= TRUE)"
},
{
"code": null,
"e": 26807,
"s": 26795,
"text": "Parameters:"
},
{
"code": null,
"e": 26828,
"s": 26807,
"text": "df: dataframe object"
},
{
"code": null,
"e": 26897,
"s": 26828,
"text": "col1,col2: column name based on which duplicate rows will be removed"
},
{
"code": null,
"e": 26968,
"s": 26897,
"text": "Example: R program to remove duplicate rows based on multiple columns "
},
{
"code": null,
"e": 26970,
"s": 26968,
"text": "R"
},
{
"code": "library(dplyr) df <- data.frame (lang =c ('Java','C','Python','GO','RUST','Javascript', 'Cpp','Java','Julia','Typescript','Python','GO'), value = c (21,21,3,5,180,9,12,21,6,0,3,6), usage =c(21,21,0,99,44,48,53,21,6,8,0,6)) distinct(df, value, usage, .keep_all= TRUE)",
"e": 27306,
"s": 26970,
"text": null
},
{
"code": null,
"e": 27314,
"s": 27306,
"text": "Output:"
},
{
"code": null,
"e": 27539,
"s": 27314,
"text": " lang value usage\n1 Java 21 21\n2 Python 3 0\n3 GO 5 99\n4 RUST 180 44\n5 Javascript 9 48\n6 Cpp 12 53\n7 Julia 6 6\n8 Typescript 0 8"
},
{
"code": null,
"e": 27721,
"s": 27539,
"text": "In this case, we just have to pass the entire dataframe as an argument in distinct() function, it then checks for all the duplicate rows for all variables/columns and removes them. "
},
{
"code": null,
"e": 27742,
"s": 27721,
"text": "Syntax: distinct(df)"
},
{
"code": null,
"e": 27754,
"s": 27742,
"text": "Parameters:"
},
{
"code": null,
"e": 27775,
"s": 27754,
"text": "df: dataframe object"
},
{
"code": null,
"e": 27845,
"s": 27775,
"text": "Example: R program to remove all the duplicate rows from the database"
},
{
"code": null,
"e": 27847,
"s": 27845,
"text": "R"
},
{
"code": "library(dplyr) df <- data.frame (lang =c ('Java','C','Python','GO','RUST','Javascript', 'Cpp','Java','Julia','Typescript','Python','GO'), value = c (21,21,3,5,180,9,12,21,6,0,3,6), usage =c(21,21,0,99,44,48,53,21,6,8,0,6)) distinct(df)",
"e": 28152,
"s": 27847,
"text": null
},
{
"code": null,
"e": 28160,
"s": 28152,
"text": "Output:"
},
{
"code": null,
"e": 28437,
"s": 28160,
"text": "lang value usage\n1 Java 21 21\n2 C 21 21\n3 Python 3 0\n4 GO 5 99\n5 RUST 180 44\n6 Javascript 9 48\n7 Cpp 12 53\n8 Julia 6 6\n9 Typescript 0 8\n10 GO 6 6"
},
{
"code": null,
"e": 28653,
"s": 28437,
"text": "In this approach, we have used duplicated() to remove all the duplicate rows, here duplicated function is used to check for the duplicate rows, then the column names/variables are passed in the duplicated function. "
},
{
"code": null,
"e": 28844,
"s": 28653,
"text": "Note: We have used the NOT(!) operator because we want to filter out or remove the duplicate rows since the duplicated function provides the duplicate rows we negate them using ‘!‘ operator."
},
{
"code": null,
"e": 28852,
"s": 28844,
"text": "Syntax:"
},
{
"code": null,
"e": 28859,
"s": 28852,
"text": "df %>%"
},
{
"code": null,
"e": 28904,
"s": 28859,
"text": " filter(!duplicated(cbind(col1, col2,..)))"
},
{
"code": null,
"e": 28916,
"s": 28904,
"text": "Parameters:"
},
{
"code": null,
"e": 29005,
"s": 28916,
"text": "col1,col2: Pass the names of columns based on which you want to remove duplicated values"
},
{
"code": null,
"e": 29112,
"s": 29005,
"text": "cbind():It is used to bind together column names such that multiple column names can be used for filtering"
},
{
"code": null,
"e": 29153,
"s": 29112,
"text": "duplicated(): returns the duplicate rows"
},
{
"code": null,
"e": 29211,
"s": 29153,
"text": "Example: R program to remove duplicate using duplicate() "
},
{
"code": null,
"e": 29213,
"s": 29211,
"text": "R"
},
{
"code": "library(dplyr) df <- data.frame (lang =c ('Java','C','Python','GO','RUST','Javascript', 'Cpp','Java','Julia','Typescript','Python','GO'), value = c (21,21,3,5,180,9,12,21,6,0,3,6), usage =c(21,21,0,99,44,48,53,21,6,8,0,6)) df %>% filter(!duplicated(cbind(value, usage)))",
"e": 29554,
"s": 29213,
"text": null
},
{
"code": null,
"e": 29562,
"s": 29554,
"text": "Output:"
},
{
"code": null,
"e": 29787,
"s": 29562,
"text": " lang value usage\n1 Java 21 21\n2 Python 3 0\n3 GO 5 99\n4 RUST 180 44\n5 Javascript 9 48\n6 Cpp 12 53\n7 Julia 6 6\n8 Typescript 0 8"
},
{
"code": null,
"e": 29794,
"s": 29787,
"text": "Picked"
},
{
"code": null,
"e": 29802,
"s": 29794,
"text": "R Dplyr"
},
{
"code": null,
"e": 29813,
"s": 29802,
"text": "R Language"
},
{
"code": null,
"e": 29911,
"s": 29813,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29920,
"s": 29911,
"text": "Comments"
},
{
"code": null,
"e": 29933,
"s": 29920,
"text": "Old Comments"
},
{
"code": null,
"e": 29985,
"s": 29933,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 30023,
"s": 29985,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 30058,
"s": 30023,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 30116,
"s": 30058,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 30159,
"s": 30116,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 30208,
"s": 30159,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 30258,
"s": 30208,
"text": "How to filter R dataframe by multiple conditions?"
},
{
"code": null,
"e": 30275,
"s": 30258,
"text": "R - if statement"
},
{
"code": null,
"e": 30312,
"s": 30275,
"text": "How to import an Excel File into R ?"
}
] |
while loop in C
|
A while loop in C programming repeatedly executes a target statement as long as a given condition is true.
The syntax of a while loop in C programming language is −
while(condition) {
statement(s);
}
Here, statement(s) may be a single statement or a block of statements. The condition may be any expression, and true is any nonzero value. The loop iterates while the condition is true.
When the condition becomes false, the program control passes to the line immediately following the loop.
Here, the key point to note is that a while loop might not execute at all. When the condition is tested and the result is false, the loop body will be skipped and the first statement after the while loop will be executed.
#include <stdio.h>
int main () {
/* local variable definition */
int a = 10;
/* while loop execution */
while( a < 20 ) {
printf("value of a: %d\n", a);
a++;
}
return 0;
}
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2191,
"s": 2084,
"text": "A while loop in C programming repeatedly executes a target statement as long as a given condition is true."
},
{
"code": null,
"e": 2249,
"s": 2191,
"text": "The syntax of a while loop in C programming language is −"
},
{
"code": null,
"e": 2288,
"s": 2249,
"text": "while(condition) {\n statement(s);\n}\n"
},
{
"code": null,
"e": 2474,
"s": 2288,
"text": "Here, statement(s) may be a single statement or a block of statements. The condition may be any expression, and true is any nonzero value. The loop iterates while the condition is true."
},
{
"code": null,
"e": 2579,
"s": 2474,
"text": "When the condition becomes false, the program control passes to the line immediately following the loop."
},
{
"code": null,
"e": 2801,
"s": 2579,
"text": "Here, the key point to note is that a while loop might not execute at all. When the condition is tested and the result is false, the loop body will be skipped and the first statement after the while loop will be executed."
},
{
"code": null,
"e": 3009,
"s": 2801,
"text": "#include <stdio.h>\n \nint main () {\n\n /* local variable definition */\n int a = 10;\n\n /* while loop execution */\n while( a < 20 ) {\n printf(\"value of a: %d\\n\", a);\n a++;\n }\n \n return 0;\n}"
},
{
"code": null,
"e": 3090,
"s": 3009,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 3241,
"s": 3090,
"text": "value of a: 10\nvalue of a: 11\nvalue of a: 12\nvalue of a: 13\nvalue of a: 14\nvalue of a: 15\nvalue of a: 16\nvalue of a: 17\nvalue of a: 18\nvalue of a: 19\n"
},
{
"code": null,
"e": 3248,
"s": 3241,
"text": " Print"
},
{
"code": null,
"e": 3259,
"s": 3248,
"text": " Add Notes"
}
] |
Java Program to add Period to LocalDate
|
Let us first set a Period with month and days:
Period p = Period.ofMonths(5).plusDays(15);
Now set the LocalDate:
LocalDate date = LocalDate.of(2019, 4, 10);
Add period to LocalDate:
LocalDate res = date.plus(p);
import java.time.LocalDate;
import java.time.Period;
public class Demo {
public static void main(String[] args) {
Period p = Period.ofMonths(5).plusDays(15);
LocalDate date = LocalDate.of(2019, 4, 10);
System.out.println("Date = "+date);
LocalDate res = date.plus(p);
System.out.println("Updated date = "+res);
}
}
Date = 2019-04-10
Updated date = 2019-09-25
|
[
{
"code": null,
"e": 1109,
"s": 1062,
"text": "Let us first set a Period with month and days:"
},
{
"code": null,
"e": 1153,
"s": 1109,
"text": "Period p = Period.ofMonths(5).plusDays(15);"
},
{
"code": null,
"e": 1176,
"s": 1153,
"text": "Now set the LocalDate:"
},
{
"code": null,
"e": 1220,
"s": 1176,
"text": "LocalDate date = LocalDate.of(2019, 4, 10);"
},
{
"code": null,
"e": 1245,
"s": 1220,
"text": "Add period to LocalDate:"
},
{
"code": null,
"e": 1275,
"s": 1245,
"text": "LocalDate res = date.plus(p);"
},
{
"code": null,
"e": 1626,
"s": 1275,
"text": "import java.time.LocalDate;\nimport java.time.Period;\npublic class Demo {\n public static void main(String[] args) {\n Period p = Period.ofMonths(5).plusDays(15);\n LocalDate date = LocalDate.of(2019, 4, 10);\n System.out.println(\"Date = \"+date);\n LocalDate res = date.plus(p);\n System.out.println(\"Updated date = \"+res);\n }\n}"
},
{
"code": null,
"e": 1670,
"s": 1626,
"text": "Date = 2019-04-10\nUpdated date = 2019-09-25"
}
] |
How do I replace “+”(plus sign) with SPACE in MySQL?
|
To replace, use REPLACE() function from MySQL. Let us first create a table −
mysql> create table DemoTable
(
Number varchar(100)
);
Query OK, 0 rows affected (0.86 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('+916578675547');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values('+918976676564');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values('+919800087678');
Query OK, 1 row affected (0.12 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+---------------+
| Number |
+---------------+
| +916578675547 |
| +918976676564 |
| +919800087678 |
+---------------+
3 rows in set (0.00 sec)
Following is the query to replace “+”(plus sign) with SPACE −
mysql> update DemoTable set Number=replace(Number, '+', ' ');
Query OK, 3 rows affected (0.12 sec)
Rows matched: 3 Changed: 3 Warnings: 0
Let us check the table records once again −
mysql> select *from DemoTable
This will produce the following output −
+---------------+
| Number |
+---------------+
| 916578675547 |
| 918976676564 |
| 919800087678 |
+---------------+
3 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1139,
"s": 1062,
"text": "To replace, use REPLACE() function from MySQL. Let us first create a table −"
},
{
"code": null,
"e": 1234,
"s": 1139,
"text": "mysql> create table DemoTable\n(\n Number varchar(100)\n);\nQuery OK, 0 rows affected (0.86 sec)"
},
{
"code": null,
"e": 1290,
"s": 1234,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 1560,
"s": 1290,
"text": "mysql> insert into DemoTable values('+916578675547');\nQuery OK, 1 row affected (0.17 sec)\nmysql> insert into DemoTable values('+918976676564');\nQuery OK, 1 row affected (0.17 sec)\nmysql> insert into DemoTable values('+919800087678');\nQuery OK, 1 row affected (0.12 sec)"
},
{
"code": null,
"e": 1620,
"s": 1560,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 1651,
"s": 1620,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 1692,
"s": 1651,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1843,
"s": 1692,
"text": "+---------------+\n| Number |\n+---------------+\n| +916578675547 |\n| +918976676564 |\n| +919800087678 |\n+---------------+\n3 rows in set (0.00 sec)"
},
{
"code": null,
"e": 1905,
"s": 1843,
"text": "Following is the query to replace “+”(plus sign) with SPACE −"
},
{
"code": null,
"e": 2043,
"s": 1905,
"text": "mysql> update DemoTable set Number=replace(Number, '+', ' ');\nQuery OK, 3 rows affected (0.12 sec)\nRows matched: 3 Changed: 3 Warnings: 0"
},
{
"code": null,
"e": 2087,
"s": 2043,
"text": "Let us check the table records once again −"
},
{
"code": null,
"e": 2117,
"s": 2087,
"text": "mysql> select *from DemoTable"
},
{
"code": null,
"e": 2158,
"s": 2117,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2306,
"s": 2158,
"text": "+---------------+\n| Number |\n+---------------+\n| 916578675547 |\n| 918976676564 |\n| 919800087678 |\n+---------------+\n3 rows in set (0.00 sec)"
}
] |
LocalDate ofInstant() method in Java with Examples - GeeksforGeeks
|
17 May, 2020
The ofInstant(Instant instant, ZoneId zone) method of LocalDate class in Java is used to create an instance of LocalDate from an Instant and zone ID. These two parameters are passed to the method and on the basis of those, an instance of LocalDate is created. The calculation of the LocalDate follows the following step.
The zone Id and instant are used to obtain the offset from UTC/Greenwich as there can be only one valid offset for each instance.Finally, the local date is calculated using the instant and the obtained offset.
The zone Id and instant are used to obtain the offset from UTC/Greenwich as there can be only one valid offset for each instance.
Finally, the local date is calculated using the instant and the obtained offset.
Syntax:
public static LocalDate
ofInstant(Instant instant,
ZoneId zone)
Parameters: This method accepts two parameters:
instant: It is of Instant type and represents the instant passed to create the date.
zone: It is of ZoneId type and represent the offset.
Return Value: This method returns the localdate.
Exceptions: This method throws DateTimeException if the result exceeds the supported range.
Note: This method is included in LocalDate class in the latest version of Java only, therefore it might not run in few of the online compilers.
Below programs illustrate the ofInstant(Instant instant, ZoneId zone) method in Java:Program 1:
// Java program to demonstrate// LocalDate.ofInstant(// Instant instant, ZoneId zone) method import java.time.*;import java.time.temporal.*; public class GFG { public static void main(String[] args) { // Create LocalDate object LocalDate localdate = LocalDate.ofInstant( Instant.now(), ZoneId.systemDefault()); // Print full date System.out.println("Date: " + localdate); }}
Date: 2020-05-13
Program 2:
// Java program to demonstrate// LocalDate ofInstant() method import java.time.*;import java.time.temporal.*; public class GFG { public static void main(String[] args) { // Create LocalDate object LocalDate localdate = LocalDate.ofInstant( Instant.now(), ZoneId.systemDefault()); // Print year only System.out.println( "Year: " + localdate.getYear()); }}
Year: 2020
References:https://docs.oracle.com/javase/10/docs/api/java/time/LocalDate.html#ofInstant(java.time.Instant, java.time.ZoneId)
Java-Functions
Java-LocalDate
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Functional Interfaces in Java
Stream In Java
Constructors in Java
Different ways of Reading a text file in Java
Exceptions in Java
Generics in Java
Comparator Interface in Java with Examples
Strings in Java
How to remove an element from ArrayList in Java?
Difference between Abstract Class and Interface in Java
|
[
{
"code": null,
"e": 23557,
"s": 23529,
"text": "\n17 May, 2020"
},
{
"code": null,
"e": 23878,
"s": 23557,
"text": "The ofInstant(Instant instant, ZoneId zone) method of LocalDate class in Java is used to create an instance of LocalDate from an Instant and zone ID. These two parameters are passed to the method and on the basis of those, an instance of LocalDate is created. The calculation of the LocalDate follows the following step."
},
{
"code": null,
"e": 24088,
"s": 23878,
"text": "The zone Id and instant are used to obtain the offset from UTC/Greenwich as there can be only one valid offset for each instance.Finally, the local date is calculated using the instant and the obtained offset."
},
{
"code": null,
"e": 24218,
"s": 24088,
"text": "The zone Id and instant are used to obtain the offset from UTC/Greenwich as there can be only one valid offset for each instance."
},
{
"code": null,
"e": 24299,
"s": 24218,
"text": "Finally, the local date is calculated using the instant and the obtained offset."
},
{
"code": null,
"e": 24307,
"s": 24299,
"text": "Syntax:"
},
{
"code": null,
"e": 24397,
"s": 24307,
"text": "public static LocalDate \n ofInstant(Instant instant,\n ZoneId zone)\n"
},
{
"code": null,
"e": 24445,
"s": 24397,
"text": "Parameters: This method accepts two parameters:"
},
{
"code": null,
"e": 24530,
"s": 24445,
"text": "instant: It is of Instant type and represents the instant passed to create the date."
},
{
"code": null,
"e": 24583,
"s": 24530,
"text": "zone: It is of ZoneId type and represent the offset."
},
{
"code": null,
"e": 24632,
"s": 24583,
"text": "Return Value: This method returns the localdate."
},
{
"code": null,
"e": 24724,
"s": 24632,
"text": "Exceptions: This method throws DateTimeException if the result exceeds the supported range."
},
{
"code": null,
"e": 24868,
"s": 24724,
"text": "Note: This method is included in LocalDate class in the latest version of Java only, therefore it might not run in few of the online compilers."
},
{
"code": null,
"e": 24964,
"s": 24868,
"text": "Below programs illustrate the ofInstant(Instant instant, ZoneId zone) method in Java:Program 1:"
},
{
"code": "// Java program to demonstrate// LocalDate.ofInstant(// Instant instant, ZoneId zone) method import java.time.*;import java.time.temporal.*; public class GFG { public static void main(String[] args) { // Create LocalDate object LocalDate localdate = LocalDate.ofInstant( Instant.now(), ZoneId.systemDefault()); // Print full date System.out.println(\"Date: \" + localdate); }}",
"e": 25447,
"s": 24964,
"text": null
},
{
"code": null,
"e": 25465,
"s": 25447,
"text": "Date: 2020-05-13\n"
},
{
"code": null,
"e": 25476,
"s": 25465,
"text": "Program 2:"
},
{
"code": "// Java program to demonstrate// LocalDate ofInstant() method import java.time.*;import java.time.temporal.*; public class GFG { public static void main(String[] args) { // Create LocalDate object LocalDate localdate = LocalDate.ofInstant( Instant.now(), ZoneId.systemDefault()); // Print year only System.out.println( \"Year: \" + localdate.getYear()); }}",
"e": 25935,
"s": 25476,
"text": null
},
{
"code": null,
"e": 25947,
"s": 25935,
"text": "Year: 2020\n"
},
{
"code": null,
"e": 26073,
"s": 25947,
"text": "References:https://docs.oracle.com/javase/10/docs/api/java/time/LocalDate.html#ofInstant(java.time.Instant, java.time.ZoneId)"
},
{
"code": null,
"e": 26088,
"s": 26073,
"text": "Java-Functions"
},
{
"code": null,
"e": 26103,
"s": 26088,
"text": "Java-LocalDate"
},
{
"code": null,
"e": 26108,
"s": 26103,
"text": "Java"
},
{
"code": null,
"e": 26113,
"s": 26108,
"text": "Java"
},
{
"code": null,
"e": 26211,
"s": 26113,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26220,
"s": 26211,
"text": "Comments"
},
{
"code": null,
"e": 26233,
"s": 26220,
"text": "Old Comments"
},
{
"code": null,
"e": 26263,
"s": 26233,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 26278,
"s": 26263,
"text": "Stream In Java"
},
{
"code": null,
"e": 26299,
"s": 26278,
"text": "Constructors in Java"
},
{
"code": null,
"e": 26345,
"s": 26299,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 26364,
"s": 26345,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 26381,
"s": 26364,
"text": "Generics in Java"
},
{
"code": null,
"e": 26424,
"s": 26381,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 26440,
"s": 26424,
"text": "Strings in Java"
},
{
"code": null,
"e": 26489,
"s": 26440,
"text": "How to remove an element from ArrayList in Java?"
}
] |
How to use threading in PyQt5?
|
24 Feb, 2021
Prerequisite: PyQt5 and multithreading
Multithreading refers to concurrently executing multiple threads by rapidly switching the control of the CPU between threads (called context switching). The Python Global Interpreter Lock limits one thread to run at a time even if the machine contains multiple processors.
In this article, we will learn, how to use threading in Pyqt5. While Creating a GUI there will be a need to do multiple work/operations at the backend. Suppose we want to perform 4 operations simultaneously. The problem here is, each operation executes one by one. During the execution of one operation, the GUI window will also not move and this is why we need threading. Both implementations are given below which obviously will help understand their differences better.
Approach
Import libraries required
Create a simple Window
Add Button with command
Execute Pyqt5
Without Threading
Working without threads, makes the process delayed. Also, the window will not move until full execution takes place.
Python3
# Import Moduleimport sysfrom PyQt5.QtWidgets import *import time class ListBox(QWidget): def __init__(self): super().__init__() self.Button() def Button(self): # Add Push Button clear_btn = QPushButton('Click Me', self) clear_btn.clicked.connect(self.Operation) # Set geometry self.setGeometry(200, 200, 200, 200) # Display QlistWidget self.show() def Operation(self): print("time start") time.sleep(10) print("time stop") if __name__ == '__main__': app = QApplication(sys.argv) # Call ListBox Class ex = ListBox() # Close the window sys.exit(app.exec_())
Output:
With Threading
Whenever we click on the “Click Me” Button, it will call the thread() method. Inside the thread method, we are creating a Thread Object where we define our function name.
Python3
# Import Moduleimport sysfrom PyQt5.QtWidgets import *import timefrom threading import * class ListBox(QWidget): def __init__(self): super().__init__() self.Button() def Button(self): # Add Push Button clear_btn = QPushButton('Click Me', self) clear_btn.clicked.connect(self.thread) # Set geometry self.setGeometry(200, 200, 200, 200) # Display QlistWidget self.show() def thread(self): t1=Thread(target=self.Operation) t1.start() def Operation(self): print("time start") time.sleep(10) print("time stop") if __name__ == '__main__': app = QApplication(sys.argv) # Call ListBox Class ex = ListBox() # Close the window sys.exit(app.exec_())
Output:
Picked
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n24 Feb, 2021"
},
{
"code": null,
"e": 67,
"s": 28,
"text": "Prerequisite: PyQt5 and multithreading"
},
{
"code": null,
"e": 341,
"s": 67,
"text": "Multithreading refers to concurrently executing multiple threads by rapidly switching the control of the CPU between threads (called context switching). The Python Global Interpreter Lock limits one thread to run at a time even if the machine contains multiple processors."
},
{
"code": null,
"e": 814,
"s": 341,
"text": "In this article, we will learn, how to use threading in Pyqt5. While Creating a GUI there will be a need to do multiple work/operations at the backend. Suppose we want to perform 4 operations simultaneously. The problem here is, each operation executes one by one. During the execution of one operation, the GUI window will also not move and this is why we need threading. Both implementations are given below which obviously will help understand their differences better."
},
{
"code": null,
"e": 823,
"s": 814,
"text": "Approach"
},
{
"code": null,
"e": 849,
"s": 823,
"text": "Import libraries required"
},
{
"code": null,
"e": 872,
"s": 849,
"text": "Create a simple Window"
},
{
"code": null,
"e": 896,
"s": 872,
"text": "Add Button with command"
},
{
"code": null,
"e": 910,
"s": 896,
"text": "Execute Pyqt5"
},
{
"code": null,
"e": 928,
"s": 910,
"text": "Without Threading"
},
{
"code": null,
"e": 1045,
"s": 928,
"text": "Working without threads, makes the process delayed. Also, the window will not move until full execution takes place."
},
{
"code": null,
"e": 1053,
"s": 1045,
"text": "Python3"
},
{
"code": "# Import Moduleimport sysfrom PyQt5.QtWidgets import *import time class ListBox(QWidget): def __init__(self): super().__init__() self.Button() def Button(self): # Add Push Button clear_btn = QPushButton('Click Me', self) clear_btn.clicked.connect(self.Operation) # Set geometry self.setGeometry(200, 200, 200, 200) # Display QlistWidget self.show() def Operation(self): print(\"time start\") time.sleep(10) print(\"time stop\") if __name__ == '__main__': app = QApplication(sys.argv) # Call ListBox Class ex = ListBox() # Close the window sys.exit(app.exec_())",
"e": 1742,
"s": 1053,
"text": null
},
{
"code": null,
"e": 1750,
"s": 1742,
"text": "Output:"
},
{
"code": null,
"e": 1765,
"s": 1750,
"text": "With Threading"
},
{
"code": null,
"e": 1936,
"s": 1765,
"text": "Whenever we click on the “Click Me” Button, it will call the thread() method. Inside the thread method, we are creating a Thread Object where we define our function name."
},
{
"code": null,
"e": 1944,
"s": 1936,
"text": "Python3"
},
{
"code": "# Import Moduleimport sysfrom PyQt5.QtWidgets import *import timefrom threading import * class ListBox(QWidget): def __init__(self): super().__init__() self.Button() def Button(self): # Add Push Button clear_btn = QPushButton('Click Me', self) clear_btn.clicked.connect(self.thread) # Set geometry self.setGeometry(200, 200, 200, 200) # Display QlistWidget self.show() def thread(self): t1=Thread(target=self.Operation) t1.start() def Operation(self): print(\"time start\") time.sleep(10) print(\"time stop\") if __name__ == '__main__': app = QApplication(sys.argv) # Call ListBox Class ex = ListBox() # Close the window sys.exit(app.exec_())",
"e": 2734,
"s": 1944,
"text": null
},
{
"code": null,
"e": 2742,
"s": 2734,
"text": "Output:"
},
{
"code": null,
"e": 2749,
"s": 2742,
"text": "Picked"
},
{
"code": null,
"e": 2760,
"s": 2749,
"text": "Python-gui"
},
{
"code": null,
"e": 2772,
"s": 2760,
"text": "Python-PyQt"
},
{
"code": null,
"e": 2779,
"s": 2772,
"text": "Python"
}
] |
Destructors in Python
|
21 Jan, 2022
Constructors in PythonDestructors are called when an object gets destroyed. In Python, destructors are not needed as much as in C++ because Python has a garbage collector that handles memory management automatically. The __del__() method is a known as a destructor method in Python. It is called when all references to the object have been deleted i.e when an object is garbage collected. Syntax of destructor declaration :
def __del__(self):
# body of destructor
Note : A reference to objects is also deleted when the object goes out of reference or when the program ends. Example 1 : Here is the simple example of destructor. By using del keyword we deleted the all references of object ‘obj’, therefore destructor invoked automatically.
Python3
# Python program to illustrate destructorclass Employee: # Initializing def __init__(self): print('Employee created.') # Deleting (Calling destructor) def __del__(self): print('Destructor called, Employee deleted.') obj = Employee()del obj
Employee created.
Destructor called, Employee deleted.
Note : The destructor was called after the program ended or when all the references to object are deleted i.e when the reference count becomes zero, not when object went out of scope.Example 2 :This example gives the explanation of above mentioned note. Here, notice that the destructor is called after the ‘Program End...’ printed.
Python3
# Python program to illustrate destructor class Employee: # Initializing def __init__(self): print('Employee created') # Calling destructor def __del__(self): print("Destructor called") def Create_obj(): print('Making Object...') obj = Employee() print('function end...') return obj print('Calling Create_obj() function...')obj = Create_obj()print('Program End...')
Calling Create_obj() function...
Making Object...
Employee created
function end...
Program End...
Destructor called
Example 3 : Now, consider the following example :
Python3
# Python program to illustrate destructor class A: def __init__(self, bb): self.b = bb class B: def __init__(self): self.a = A(self) def __del__(self): print("die") def fun(): b = B() fun()
die
In this example when the function fun() is called, it creates an instance of class B which passes itself to class A, which then sets a reference to class B and resulting in a circular reference.Generally, Python’s garbage collector which is used to detect these types of cyclic references would remove it but in this example the use of custom destructor marks this item as “uncollectable”. Simply, it doesn’t know the order in which to destroy the objects, so it leaves them. Therefore, if your instances are involved in circular references they will live in memory for as long as the application run.
gfreundt
Picked
Python-OOP
python-oop-concepts
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
Enumerate() in Python
Different ways to create Pandas Dataframe
Read a file line by line in Python
How to Install PIP on Windows ?
Python String | replace()
Python OOPs Concepts
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n21 Jan, 2022"
},
{
"code": null,
"e": 478,
"s": 52,
"text": "Constructors in PythonDestructors are called when an object gets destroyed. In Python, destructors are not needed as much as in C++ because Python has a garbage collector that handles memory management automatically. The __del__() method is a known as a destructor method in Python. It is called when all references to the object have been deleted i.e when an object is garbage collected. Syntax of destructor declaration : "
},
{
"code": null,
"e": 520,
"s": 478,
"text": "def __del__(self):\n # body of destructor"
},
{
"code": null,
"e": 797,
"s": 520,
"text": "Note : A reference to objects is also deleted when the object goes out of reference or when the program ends. Example 1 : Here is the simple example of destructor. By using del keyword we deleted the all references of object ‘obj’, therefore destructor invoked automatically. "
},
{
"code": null,
"e": 805,
"s": 797,
"text": "Python3"
},
{
"code": "# Python program to illustrate destructorclass Employee: # Initializing def __init__(self): print('Employee created.') # Deleting (Calling destructor) def __del__(self): print('Destructor called, Employee deleted.') obj = Employee()del obj",
"e": 1073,
"s": 805,
"text": null
},
{
"code": null,
"e": 1128,
"s": 1073,
"text": "Employee created.\nDestructor called, Employee deleted."
},
{
"code": null,
"e": 1464,
"s": 1130,
"text": "Note : The destructor was called after the program ended or when all the references to object are deleted i.e when the reference count becomes zero, not when object went out of scope.Example 2 :This example gives the explanation of above mentioned note. Here, notice that the destructor is called after the ‘Program End...’ printed. "
},
{
"code": null,
"e": 1472,
"s": 1464,
"text": "Python3"
},
{
"code": "# Python program to illustrate destructor class Employee: # Initializing def __init__(self): print('Employee created') # Calling destructor def __del__(self): print(\"Destructor called\") def Create_obj(): print('Making Object...') obj = Employee() print('function end...') return obj print('Calling Create_obj() function...')obj = Create_obj()print('Program End...')",
"e": 1878,
"s": 1472,
"text": null
},
{
"code": null,
"e": 1994,
"s": 1878,
"text": "Calling Create_obj() function...\nMaking Object...\nEmployee created\nfunction end...\nProgram End...\nDestructor called"
},
{
"code": null,
"e": 2048,
"s": 1996,
"text": "Example 3 : Now, consider the following example : "
},
{
"code": null,
"e": 2056,
"s": 2048,
"text": "Python3"
},
{
"code": "# Python program to illustrate destructor class A: def __init__(self, bb): self.b = bb class B: def __init__(self): self.a = A(self) def __del__(self): print(\"die\") def fun(): b = B() fun()",
"e": 2279,
"s": 2056,
"text": null
},
{
"code": null,
"e": 2283,
"s": 2279,
"text": "die"
},
{
"code": null,
"e": 2888,
"s": 2285,
"text": "In this example when the function fun() is called, it creates an instance of class B which passes itself to class A, which then sets a reference to class B and resulting in a circular reference.Generally, Python’s garbage collector which is used to detect these types of cyclic references would remove it but in this example the use of custom destructor marks this item as “uncollectable”. Simply, it doesn’t know the order in which to destroy the objects, so it leaves them. Therefore, if your instances are involved in circular references they will live in memory for as long as the application run. "
},
{
"code": null,
"e": 2897,
"s": 2888,
"text": "gfreundt"
},
{
"code": null,
"e": 2904,
"s": 2897,
"text": "Picked"
},
{
"code": null,
"e": 2915,
"s": 2904,
"text": "Python-OOP"
},
{
"code": null,
"e": 2935,
"s": 2915,
"text": "python-oop-concepts"
},
{
"code": null,
"e": 2942,
"s": 2935,
"text": "Python"
},
{
"code": null,
"e": 3040,
"s": 2942,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3068,
"s": 3040,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 3118,
"s": 3068,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 3140,
"s": 3118,
"text": "Python map() function"
},
{
"code": null,
"e": 3184,
"s": 3140,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 3206,
"s": 3184,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3248,
"s": 3206,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 3283,
"s": 3248,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 3315,
"s": 3283,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3341,
"s": 3315,
"text": "Python String | replace()"
}
] |
Output of C++ programs | Set 50
|
07 Jul, 2021
Question 1:
CPP
#include <cstdlib>#include <iostream>using namespace std;int main(){ int ran = rand(); cout << ran << endl; return 0;}
Output:
1804289383
Explanation: As the declared number is an integer, It will produce the random number from 0 to RAND_MAX. The value of RAND_MAX is library-dependent but is guaranteed to be at least 32767 on any standard library implementation.
Question 2:
CPP
#include <cstdlib>#include <iostream>using namespace std; int main(){ cout << RAND_MAX << endl; return 0;}
Output:
2147483647
Explanation: The output is Compiler Dependent. RAND_MAX is a function used by the compiler to create a maximum random number.
Question 3:
CPP
#include <iostream>using namespace std;int main(){ void a = 10, b = 10; int c; c = a + b; cout << c; return 0;}
Output:
Compile time error
Explanation: void will not accept any values to its type.
Question 4:
CPP
#include <iostream> using namespace std; int array1[] = { 1200, 200, 2300, 1230, 1543 };int array2[] = { 12, 14, 16, 18, 20 };int temp, result = 0;int main(){ for (temp = 0; temp < 5; temp++) { result += array1[temp]; } for (temp = 0; temp < 5; temp++) { result += array2[temp]; } cout << result; return 0;}
Output:
6553
Explanation: In this program we are adding the every element of two arrays. All the elements of array1[] and array2[] will be added and the sum will be stored in result and hence output is 6553.
Question 5:
CPP
#include <iostream>using namespace std;int main(){ int a = 5, b = 10, c = 15; int arr[3] = { &a, &b, &c }; cout << *arr[*arr[1] - 8]; return 0;}
Output:
Compile time error!
Explanation: The conversion is invalid in this array. The array arr[] is declared to hold integer type value but we are trying to assign references(addresses) to the array so it will arise error. The following compilation error will be raised:
cannot convert from ‘int *’ to ‘int’
Question 6:
CPP
#include <iostream>using namespace std;int main(){ int array[] = { 10, 20, 30 }; cout << -2 [array]; return 0;}
Output:
-30
Explanation: -2[array]: this statement is equivalent to -(array[2]). At the zero index 30 is stored hence negation of 30 will be printed due to unary operator (-).
Question 7:
CPP
#include <iostream>using namespace std;int main(){ int const p = 5; cout << ++p; return 0;}
Output:
Compile time Error!
Explanation: Constant variables are those whose value can’t be changed throughout the execution. ++p statement try to change the value hence compiler will raise an error.
Question 8:
CPP
#include <iostream>using namespace std;int main(){ char arr[20]; int i; for (i = 0; i < 10; i++) *(arr + i) = 65 + i; *(arr + i) = '\0'; cout << arr; return (0);}
Output:
ABCDEFGHIJ
Explanation: Each time we are assigning 65 + i. In first iteration i = 0 and 65 is assigned. So it will print from A to J.
Question 9:
CPP
#include <iostream>using namespace std;int Add(int X, int Y, int Z){ return X + Y;}double Add(double X, double Y, double Z){ return X + Y;}int main(){ cout << Add(5, 6); cout << Add(5.5, 6.6); return 0;}
Output:
Compile time error!
Explanation: Here we want to add two element but in the given functions we take 3 arguments.So compiler doesn’t get the required function(function with 2 arguments)
Question 10:
CPP
#include <iostream>using namespace std;#define PR(id) cout << "The value of " #id " is " << idint main(){ int i = 10; PR(i); return 0;}
Output:
The value of i is 10
Explanation: In this program, we are just printing the declared value through a macro. Carefully observe that in macro there is no semicolon(;) used as a termination statement.
This article is contributed by Avinash Kumar Singh email: [email protected]. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Milan1999
DemoDustin
saurabh1990aror
akshaysingh98088
CPP-Output
Program Output
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n07 Jul, 2021"
},
{
"code": null,
"e": 66,
"s": 52,
"text": "Question 1: "
},
{
"code": null,
"e": 70,
"s": 66,
"text": "CPP"
},
{
"code": "#include <cstdlib>#include <iostream>using namespace std;int main(){ int ran = rand(); cout << ran << endl; return 0;}",
"e": 198,
"s": 70,
"text": null
},
{
"code": null,
"e": 208,
"s": 198,
"text": "Output: "
},
{
"code": null,
"e": 219,
"s": 208,
"text": "1804289383"
},
{
"code": null,
"e": 446,
"s": 219,
"text": "Explanation: As the declared number is an integer, It will produce the random number from 0 to RAND_MAX. The value of RAND_MAX is library-dependent but is guaranteed to be at least 32767 on any standard library implementation."
},
{
"code": null,
"e": 459,
"s": 446,
"text": "Question 2: "
},
{
"code": null,
"e": 463,
"s": 459,
"text": "CPP"
},
{
"code": "#include <cstdlib>#include <iostream>using namespace std; int main(){ cout << RAND_MAX << endl; return 0;}",
"e": 576,
"s": 463,
"text": null
},
{
"code": null,
"e": 586,
"s": 576,
"text": "Output: "
},
{
"code": null,
"e": 597,
"s": 586,
"text": "2147483647"
},
{
"code": null,
"e": 723,
"s": 597,
"text": "Explanation: The output is Compiler Dependent. RAND_MAX is a function used by the compiler to create a maximum random number."
},
{
"code": null,
"e": 736,
"s": 723,
"text": "Question 3: "
},
{
"code": null,
"e": 740,
"s": 736,
"text": "CPP"
},
{
"code": "#include <iostream>using namespace std;int main(){ void a = 10, b = 10; int c; c = a + b; cout << c; return 0;}",
"e": 867,
"s": 740,
"text": null
},
{
"code": null,
"e": 877,
"s": 867,
"text": "Output: "
},
{
"code": null,
"e": 896,
"s": 877,
"text": "Compile time error"
},
{
"code": null,
"e": 956,
"s": 896,
"text": "Explanation: void will not accept any values to its type. "
},
{
"code": null,
"e": 969,
"s": 956,
"text": "Question 4: "
},
{
"code": null,
"e": 973,
"s": 969,
"text": "CPP"
},
{
"code": "#include <iostream> using namespace std; int array1[] = { 1200, 200, 2300, 1230, 1543 };int array2[] = { 12, 14, 16, 18, 20 };int temp, result = 0;int main(){ for (temp = 0; temp < 5; temp++) { result += array1[temp]; } for (temp = 0; temp < 5; temp++) { result += array2[temp]; } cout << result; return 0;}",
"e": 1313,
"s": 973,
"text": null
},
{
"code": null,
"e": 1323,
"s": 1313,
"text": "Output: "
},
{
"code": null,
"e": 1328,
"s": 1323,
"text": "6553"
},
{
"code": null,
"e": 1523,
"s": 1328,
"text": "Explanation: In this program we are adding the every element of two arrays. All the elements of array1[] and array2[] will be added and the sum will be stored in result and hence output is 6553."
},
{
"code": null,
"e": 1536,
"s": 1523,
"text": "Question 5: "
},
{
"code": null,
"e": 1540,
"s": 1536,
"text": "CPP"
},
{
"code": "#include <iostream>using namespace std;int main(){ int a = 5, b = 10, c = 15; int arr[3] = { &a, &b, &c }; cout << *arr[*arr[1] - 8]; return 0;}",
"e": 1697,
"s": 1540,
"text": null
},
{
"code": null,
"e": 1707,
"s": 1697,
"text": "Output: "
},
{
"code": null,
"e": 1727,
"s": 1707,
"text": "Compile time error!"
},
{
"code": null,
"e": 1973,
"s": 1727,
"text": "Explanation: The conversion is invalid in this array. The array arr[] is declared to hold integer type value but we are trying to assign references(addresses) to the array so it will arise error. The following compilation error will be raised: "
},
{
"code": null,
"e": 2010,
"s": 1973,
"text": "cannot convert from ‘int *’ to ‘int’"
},
{
"code": null,
"e": 2023,
"s": 2010,
"text": "Question 6: "
},
{
"code": null,
"e": 2027,
"s": 2023,
"text": "CPP"
},
{
"code": "#include <iostream>using namespace std;int main(){ int array[] = { 10, 20, 30 }; cout << -2 [array]; return 0;}",
"e": 2148,
"s": 2027,
"text": null
},
{
"code": null,
"e": 2158,
"s": 2148,
"text": "Output: "
},
{
"code": null,
"e": 2162,
"s": 2158,
"text": "-30"
},
{
"code": null,
"e": 2326,
"s": 2162,
"text": "Explanation: -2[array]: this statement is equivalent to -(array[2]). At the zero index 30 is stored hence negation of 30 will be printed due to unary operator (-)."
},
{
"code": null,
"e": 2339,
"s": 2326,
"text": "Question 7: "
},
{
"code": null,
"e": 2343,
"s": 2339,
"text": "CPP"
},
{
"code": "#include <iostream>using namespace std;int main(){ int const p = 5; cout << ++p; return 0;}",
"e": 2444,
"s": 2343,
"text": null
},
{
"code": null,
"e": 2454,
"s": 2444,
"text": "Output: "
},
{
"code": null,
"e": 2474,
"s": 2454,
"text": "Compile time Error!"
},
{
"code": null,
"e": 2645,
"s": 2474,
"text": "Explanation: Constant variables are those whose value can’t be changed throughout the execution. ++p statement try to change the value hence compiler will raise an error."
},
{
"code": null,
"e": 2658,
"s": 2645,
"text": "Question 8: "
},
{
"code": null,
"e": 2662,
"s": 2658,
"text": "CPP"
},
{
"code": "#include <iostream>using namespace std;int main(){ char arr[20]; int i; for (i = 0; i < 10; i++) *(arr + i) = 65 + i; *(arr + i) = '\\0'; cout << arr; return (0);}",
"e": 2850,
"s": 2662,
"text": null
},
{
"code": null,
"e": 2860,
"s": 2850,
"text": "Output: "
},
{
"code": null,
"e": 2871,
"s": 2860,
"text": "ABCDEFGHIJ"
},
{
"code": null,
"e": 2996,
"s": 2871,
"text": "Explanation: Each time we are assigning 65 + i. In first iteration i = 0 and 65 is assigned. So it will print from A to J. "
},
{
"code": null,
"e": 3009,
"s": 2996,
"text": "Question 9: "
},
{
"code": null,
"e": 3013,
"s": 3009,
"text": "CPP"
},
{
"code": "#include <iostream>using namespace std;int Add(int X, int Y, int Z){ return X + Y;}double Add(double X, double Y, double Z){ return X + Y;}int main(){ cout << Add(5, 6); cout << Add(5.5, 6.6); return 0;}",
"e": 3232,
"s": 3013,
"text": null
},
{
"code": null,
"e": 3242,
"s": 3232,
"text": "Output: "
},
{
"code": null,
"e": 3262,
"s": 3242,
"text": "Compile time error!"
},
{
"code": null,
"e": 3427,
"s": 3262,
"text": "Explanation: Here we want to add two element but in the given functions we take 3 arguments.So compiler doesn’t get the required function(function with 2 arguments)"
},
{
"code": null,
"e": 3441,
"s": 3427,
"text": "Question 10: "
},
{
"code": null,
"e": 3445,
"s": 3441,
"text": "CPP"
},
{
"code": "#include <iostream>using namespace std;#define PR(id) cout << \"The value of \" #id \" is \" << idint main(){ int i = 10; PR(i); return 0;}",
"e": 3590,
"s": 3445,
"text": null
},
{
"code": null,
"e": 3600,
"s": 3590,
"text": "Output: "
},
{
"code": null,
"e": 3621,
"s": 3600,
"text": "The value of i is 10"
},
{
"code": null,
"e": 3798,
"s": 3621,
"text": "Explanation: In this program, we are just printing the declared value through a macro. Carefully observe that in macro there is no semicolon(;) used as a termination statement."
},
{
"code": null,
"e": 4262,
"s": 3798,
"text": "This article is contributed by Avinash Kumar Singh email: [email protected]. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 4272,
"s": 4262,
"text": "Milan1999"
},
{
"code": null,
"e": 4283,
"s": 4272,
"text": "DemoDustin"
},
{
"code": null,
"e": 4299,
"s": 4283,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 4316,
"s": 4299,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 4327,
"s": 4316,
"text": "CPP-Output"
},
{
"code": null,
"e": 4342,
"s": 4327,
"text": "Program Output"
}
] |
Inline function in C
|
03 Dec, 2018
Inline Function are those function whose definitions are small and be substituted at the place where its function call is happened. Function substitution is totally compiler choice.
Let’s take below example:
#include <stdio.h> // Inline function in Cinline int foo(){ return 2;} // Driver codeint main(){ int ret; // inline function call ret = foo(); printf("Output is: %d\n", ret); return 0;}
Compiler Error:
In function `main':
undefined reference to `foo'
Why this error happened?
This is one of the side effect of GCC the way it handle inline function. When compiled, GCC performs inline substitution as the part of optimisation. So there is no function call present (foo) inside main. Please check below assembly code which compiler will generate.
Normally GCC’s file scope is “not extern linkage”. That means inline function is never ever provided to the linker which is causing linker error, mentioned above.
How to remove this error?
To resolve this problem use “static” before inline. Using static keyword forces the compiler to consider this inline function in the linker, and hence the program compiles and run successfully.
Example:
#include <stdio.h> // Inline function in Cstatic inline int foo(){ return 2;} // Driver codeint main(){ int ret; // inline function call ret = foo(); printf("Output is: %d\n", ret); return 0;}
Output is: 2
C Basics
C-Functions
Technical Scripter 2018
C Language
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n03 Dec, 2018"
},
{
"code": null,
"e": 236,
"s": 54,
"text": "Inline Function are those function whose definitions are small and be substituted at the place where its function call is happened. Function substitution is totally compiler choice."
},
{
"code": null,
"e": 262,
"s": 236,
"text": "Let’s take below example:"
},
{
"code": "#include <stdio.h> // Inline function in Cinline int foo(){ return 2;} // Driver codeint main(){ int ret; // inline function call ret = foo(); printf(\"Output is: %d\\n\", ret); return 0;}",
"e": 474,
"s": 262,
"text": null
},
{
"code": null,
"e": 490,
"s": 474,
"text": "Compiler Error:"
},
{
"code": null,
"e": 540,
"s": 490,
"text": "In function `main':\nundefined reference to `foo'\n"
},
{
"code": null,
"e": 565,
"s": 540,
"text": "Why this error happened?"
},
{
"code": null,
"e": 834,
"s": 565,
"text": "This is one of the side effect of GCC the way it handle inline function. When compiled, GCC performs inline substitution as the part of optimisation. So there is no function call present (foo) inside main. Please check below assembly code which compiler will generate."
},
{
"code": null,
"e": 997,
"s": 834,
"text": "Normally GCC’s file scope is “not extern linkage”. That means inline function is never ever provided to the linker which is causing linker error, mentioned above."
},
{
"code": null,
"e": 1023,
"s": 997,
"text": "How to remove this error?"
},
{
"code": null,
"e": 1217,
"s": 1023,
"text": "To resolve this problem use “static” before inline. Using static keyword forces the compiler to consider this inline function in the linker, and hence the program compiles and run successfully."
},
{
"code": null,
"e": 1226,
"s": 1217,
"text": "Example:"
},
{
"code": "#include <stdio.h> // Inline function in Cstatic inline int foo(){ return 2;} // Driver codeint main(){ int ret; // inline function call ret = foo(); printf(\"Output is: %d\\n\", ret); return 0;}",
"e": 1445,
"s": 1226,
"text": null
},
{
"code": null,
"e": 1459,
"s": 1445,
"text": "Output is: 2\n"
},
{
"code": null,
"e": 1468,
"s": 1459,
"text": "C Basics"
},
{
"code": null,
"e": 1480,
"s": 1468,
"text": "C-Functions"
},
{
"code": null,
"e": 1504,
"s": 1480,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 1515,
"s": 1504,
"text": "C Language"
},
{
"code": null,
"e": 1534,
"s": 1515,
"text": "Technical Scripter"
}
] |
Understanding storage of static methods and static variables in Java
|
23 Mar, 2022
In every programming language, memory is a vital resource and is also scarce in nature. Hence it’s essential that the memory is managed thoroughly without any leaks. Allocation and deallocation of memory is a critical task and requires a lot of care and consideration. In this article, we will understand the storage of static methods and static variables in Java. Java Virtual Machine(JVM) is an engine that provides a run time environment to drive the java code. It converts the java byte code into machine language. The JVM has two primary functions. They are:
It allows java programs to run on any device or OS to fulfil WORA (Write Once Run Anywhere) principle.It manages and optimizes program memory.
It allows java programs to run on any device or OS to fulfil WORA (Write Once Run Anywhere) principle.
It manages and optimizes program memory.
The JVM memory manager creates memory pools during the runtime of the program. Let’s understand the concept of memory pools in java. There are two types of memory pools namely the stack memory and the heap memory. The main difference between stack memory and the heap memory is that the stack is used to store only the small datatypes whereas heap stores all the instances of the class. And, since java either implicitly or explicitly extends the class from Object.class, every class we create is a collection of objects. This also means that we cannot use a method or a variable unless we instantiate it with a new keyword. As soon as we instantiate the methods, JVM allocates some memory on the heap and it stores the address of the instance on the stack. After this, the methods and variables can be used. In order to get a better understanding of how the new keyword works, let’s take an example. Let’s take a bird class. Whenever a new bird is found, the number of birds need to be incremented. Let’s try to implement this code:
Java
// Java program to demonstrate the above example public class Bird { private String name; private int number; Bird(String name) { this.name = name; number++; } public void fly() { System.out.println( "This bird flies"); } public int getNumber() { return number; } public String getName() { return name; }} class GFG { public static void main(String args[]) { Bird b1 = new Bird("Parrot"); Bird b2 = new Bird("Sparrow"); Bird b3 = new Bird("Pigeon"); System.out.println(b1.getNumber()); }}
1
Clearly, this method cannot be used to count the number of birds because at every instance, a new heap is being allocated and for all the instances, the number of birds is being initialized from 0 and is incremented to 1. Therefore, we are creating three independent birds where, in every bird object, the number of birds is 1. In order to avoid this, we initialize the methods and variables as static. This means that the variable or method is not changed for every new object creation. Since these methods and variables cannot be stored in a normal heap, they are stored in a special area called permanent generation(PermGen).
The main difference is that the heap is the auto growing space, with RAM memory as its constraints, whereas this PermGen has a fixed space allocation, and this is shared with all the instances.
Let’s implement this by changing the number to a static variable.
Java
// Java program to demonstrate the above example public class Bird { private String name; private static int number; Bird(String name) { this.name = name; number++; } public void fly() { System.out.println("This bird flies"); } public int getNumber() { return number; } public String getName() { return name; }} class GFG { public static void main(String args[]) { Bird b1 = new Bird("Parrot"); Bird b2 = new Bird("Sparrow"); Bird b3 = new Bird("Pigeon"); System.out.println(b1.getNumber()); }}
3
Note: In Java 5 and 6, PermGen space was used. But due to major changes in memory model in Java 8, storage specification has also been changed. Now a new memory space “MetaSpace” has been introduced where all the names fields of the class, methods of a class with the byte code of methods, constant pool, JIT optimizations are stored. The main reason for this change of PermGen in Java 8.0 is that it is tough to predict the size of PermGen, and it helps in improving garbage collection performance.
mayankdudeja17
java-JVM
memory-management
Static Keyword
Java
Write From Home
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
HashMap in Java with Examples
ArrayList in Java
Multidimensional Arrays in Java
Convert integer to string in Python
Convert string to integer in Python
How to set input type date in dd-mm-yyyy format using HTML ?
Python infinity
Factory method design pattern in Java
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n23 Mar, 2022"
},
{
"code": null,
"e": 616,
"s": 52,
"text": "In every programming language, memory is a vital resource and is also scarce in nature. Hence it’s essential that the memory is managed thoroughly without any leaks. Allocation and deallocation of memory is a critical task and requires a lot of care and consideration. In this article, we will understand the storage of static methods and static variables in Java. Java Virtual Machine(JVM) is an engine that provides a run time environment to drive the java code. It converts the java byte code into machine language. The JVM has two primary functions. They are:"
},
{
"code": null,
"e": 759,
"s": 616,
"text": "It allows java programs to run on any device or OS to fulfil WORA (Write Once Run Anywhere) principle.It manages and optimizes program memory."
},
{
"code": null,
"e": 862,
"s": 759,
"text": "It allows java programs to run on any device or OS to fulfil WORA (Write Once Run Anywhere) principle."
},
{
"code": null,
"e": 903,
"s": 862,
"text": "It manages and optimizes program memory."
},
{
"code": null,
"e": 1938,
"s": 903,
"text": "The JVM memory manager creates memory pools during the runtime of the program. Let’s understand the concept of memory pools in java. There are two types of memory pools namely the stack memory and the heap memory. The main difference between stack memory and the heap memory is that the stack is used to store only the small datatypes whereas heap stores all the instances of the class. And, since java either implicitly or explicitly extends the class from Object.class, every class we create is a collection of objects. This also means that we cannot use a method or a variable unless we instantiate it with a new keyword. As soon as we instantiate the methods, JVM allocates some memory on the heap and it stores the address of the instance on the stack. After this, the methods and variables can be used. In order to get a better understanding of how the new keyword works, let’s take an example. Let’s take a bird class. Whenever a new bird is found, the number of birds need to be incremented. Let’s try to implement this code: "
},
{
"code": null,
"e": 1943,
"s": 1938,
"text": "Java"
},
{
"code": "// Java program to demonstrate the above example public class Bird { private String name; private int number; Bird(String name) { this.name = name; number++; } public void fly() { System.out.println( \"This bird flies\"); } public int getNumber() { return number; } public String getName() { return name; }} class GFG { public static void main(String args[]) { Bird b1 = new Bird(\"Parrot\"); Bird b2 = new Bird(\"Sparrow\"); Bird b3 = new Bird(\"Pigeon\"); System.out.println(b1.getNumber()); }}",
"e": 2562,
"s": 1943,
"text": null
},
{
"code": null,
"e": 2564,
"s": 2562,
"text": "1"
},
{
"code": null,
"e": 3193,
"s": 2564,
"text": "Clearly, this method cannot be used to count the number of birds because at every instance, a new heap is being allocated and for all the instances, the number of birds is being initialized from 0 and is incremented to 1. Therefore, we are creating three independent birds where, in every bird object, the number of birds is 1. In order to avoid this, we initialize the methods and variables as static. This means that the variable or method is not changed for every new object creation. Since these methods and variables cannot be stored in a normal heap, they are stored in a special area called permanent generation(PermGen)."
},
{
"code": null,
"e": 3387,
"s": 3193,
"text": "The main difference is that the heap is the auto growing space, with RAM memory as its constraints, whereas this PermGen has a fixed space allocation, and this is shared with all the instances."
},
{
"code": null,
"e": 3454,
"s": 3387,
"text": "Let’s implement this by changing the number to a static variable. "
},
{
"code": null,
"e": 3459,
"s": 3454,
"text": "Java"
},
{
"code": "// Java program to demonstrate the above example public class Bird { private String name; private static int number; Bird(String name) { this.name = name; number++; } public void fly() { System.out.println(\"This bird flies\"); } public int getNumber() { return number; } public String getName() { return name; }} class GFG { public static void main(String args[]) { Bird b1 = new Bird(\"Parrot\"); Bird b2 = new Bird(\"Sparrow\"); Bird b3 = new Bird(\"Pigeon\"); System.out.println(b1.getNumber()); }}",
"e": 4073,
"s": 3459,
"text": null
},
{
"code": null,
"e": 4075,
"s": 4073,
"text": "3"
},
{
"code": null,
"e": 4575,
"s": 4075,
"text": "Note: In Java 5 and 6, PermGen space was used. But due to major changes in memory model in Java 8, storage specification has also been changed. Now a new memory space “MetaSpace” has been introduced where all the names fields of the class, methods of a class with the byte code of methods, constant pool, JIT optimizations are stored. The main reason for this change of PermGen in Java 8.0 is that it is tough to predict the size of PermGen, and it helps in improving garbage collection performance."
},
{
"code": null,
"e": 4590,
"s": 4575,
"text": "mayankdudeja17"
},
{
"code": null,
"e": 4599,
"s": 4590,
"text": "java-JVM"
},
{
"code": null,
"e": 4617,
"s": 4599,
"text": "memory-management"
},
{
"code": null,
"e": 4632,
"s": 4617,
"text": "Static Keyword"
},
{
"code": null,
"e": 4637,
"s": 4632,
"text": "Java"
},
{
"code": null,
"e": 4653,
"s": 4637,
"text": "Write From Home"
},
{
"code": null,
"e": 4658,
"s": 4653,
"text": "Java"
},
{
"code": null,
"e": 4756,
"s": 4658,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4807,
"s": 4756,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 4838,
"s": 4807,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 4868,
"s": 4838,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 4886,
"s": 4868,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 4918,
"s": 4886,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 4954,
"s": 4918,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 4990,
"s": 4954,
"text": "Convert string to integer in Python"
},
{
"code": null,
"e": 5051,
"s": 4990,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 5067,
"s": 5051,
"text": "Python infinity"
}
] |
Tensorflow tf.sub() Function
|
07 Jun, 2022
The tf.sub() function returns the subtraction of two tf.Tensor objects element wise. The tf.Tensor object represents the multidimensional array of numbers.
Syntax:
tf.sub( a, b )
Parameters:
a: It contains the first tf.Tensor object. The value of this parameter can be tf.TensorTypedArray|Array.
b: It contains the second tf.Tensor object that subtract from first tf.Tensor object. The value of this parameter can be (tf.Tensor|TypedArray|Array). The type of this parameter is same as type of a.
Return Value: This function returns the tf.Tensor object.
Example 1:
Javascript
// Importing the tensorflow.js libraryimport * as tf from "@tensorflow/tfjs" // Declare the Tensor arrayconst arr1 = tf.tensor1d([10, 20, 30, 40, 50]);const arr2 = tf.tensor1d([5, 10, 15, 20, 25]); // Use sub() function to subtract// two Tensor objectsarr1.sub(arr2).print();
Output:
Tensor
[5, 10, 15, 20, 25]
Example 2:
Javascript
// Importing the tensorflow.js libraryimport * as tf from "@tensorflow/tfjs" // Declare the Tensor arrayconst arr1 = tf.tensor1d([30, 40, 50]);const arr2 = tf.tensor1d([5, 10, 15, 20, 25]); // Use sub() function to subtract// two Tensor objectsarr1.sub(arr2).print();
Output:
An error occurred on line: 7
Operands could not be broadcast together with shapes 3 and 5.
Example 3:
Javascript
// Importing the tensorflow.js libraryimport * as tf from "@tensorflow/tfjs" // Declare the Tensor arrayconst arr = tf.tensor1d([15, 10, 25, 20, 35]); // Declare a numberconst num = tf.scalar(30); // Use sub() function to subtract number// from Tensor objectarr.sub(num).print();
Output:
Tensor
[-15, -20, -5, -10, 5]
Reference: https://js.tensorflow.org/api/latest/#sub
nikhatkhan11
Tensorflow
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n07 Jun, 2022"
},
{
"code": null,
"e": 184,
"s": 28,
"text": "The tf.sub() function returns the subtraction of two tf.Tensor objects element wise. The tf.Tensor object represents the multidimensional array of numbers."
},
{
"code": null,
"e": 192,
"s": 184,
"text": "Syntax:"
},
{
"code": null,
"e": 207,
"s": 192,
"text": "tf.sub( a, b )"
},
{
"code": null,
"e": 219,
"s": 207,
"text": "Parameters:"
},
{
"code": null,
"e": 324,
"s": 219,
"text": "a: It contains the first tf.Tensor object. The value of this parameter can be tf.TensorTypedArray|Array."
},
{
"code": null,
"e": 524,
"s": 324,
"text": "b: It contains the second tf.Tensor object that subtract from first tf.Tensor object. The value of this parameter can be (tf.Tensor|TypedArray|Array). The type of this parameter is same as type of a."
},
{
"code": null,
"e": 582,
"s": 524,
"text": "Return Value: This function returns the tf.Tensor object."
},
{
"code": null,
"e": 593,
"s": 582,
"text": "Example 1:"
},
{
"code": null,
"e": 604,
"s": 593,
"text": "Javascript"
},
{
"code": "// Importing the tensorflow.js libraryimport * as tf from \"@tensorflow/tfjs\" // Declare the Tensor arrayconst arr1 = tf.tensor1d([10, 20, 30, 40, 50]);const arr2 = tf.tensor1d([5, 10, 15, 20, 25]); // Use sub() function to subtract// two Tensor objectsarr1.sub(arr2).print();",
"e": 880,
"s": 604,
"text": null
},
{
"code": null,
"e": 888,
"s": 880,
"text": "Output:"
},
{
"code": null,
"e": 919,
"s": 888,
"text": "Tensor\n [5, 10, 15, 20, 25]"
},
{
"code": null,
"e": 930,
"s": 919,
"text": "Example 2:"
},
{
"code": null,
"e": 941,
"s": 930,
"text": "Javascript"
},
{
"code": "// Importing the tensorflow.js libraryimport * as tf from \"@tensorflow/tfjs\" // Declare the Tensor arrayconst arr1 = tf.tensor1d([30, 40, 50]);const arr2 = tf.tensor1d([5, 10, 15, 20, 25]); // Use sub() function to subtract// two Tensor objectsarr1.sub(arr2).print();",
"e": 1209,
"s": 941,
"text": null
},
{
"code": null,
"e": 1217,
"s": 1209,
"text": "Output:"
},
{
"code": null,
"e": 1308,
"s": 1217,
"text": "An error occurred on line: 7\nOperands could not be broadcast together with shapes 3 and 5."
},
{
"code": null,
"e": 1319,
"s": 1308,
"text": "Example 3:"
},
{
"code": null,
"e": 1330,
"s": 1319,
"text": "Javascript"
},
{
"code": "// Importing the tensorflow.js libraryimport * as tf from \"@tensorflow/tfjs\" // Declare the Tensor arrayconst arr = tf.tensor1d([15, 10, 25, 20, 35]); // Declare a numberconst num = tf.scalar(30); // Use sub() function to subtract number// from Tensor objectarr.sub(num).print();",
"e": 1610,
"s": 1330,
"text": null
},
{
"code": null,
"e": 1619,
"s": 1610,
"text": "Output: "
},
{
"code": null,
"e": 1653,
"s": 1619,
"text": "Tensor\n [-15, -20, -5, -10, 5]"
},
{
"code": null,
"e": 1706,
"s": 1653,
"text": "Reference: https://js.tensorflow.org/api/latest/#sub"
},
{
"code": null,
"e": 1719,
"s": 1706,
"text": "nikhatkhan11"
},
{
"code": null,
"e": 1730,
"s": 1719,
"text": "Tensorflow"
},
{
"code": null,
"e": 1741,
"s": 1730,
"text": "JavaScript"
},
{
"code": null,
"e": 1758,
"s": 1741,
"text": "Web Technologies"
}
] |
Python Dictionary pop() method
|
01 Jul, 2022
Python dictionary pop() method removes and returns the specified element from the dictionary.
Syntax : dict.pop(key, def)
Parameters :
key : The key whose key-value pair has to be returned and removed.
def : The default value to return if specified key is not present.
Returns : Value associated to deleted key-value pair, if key is present. Default value if specified if key is not present. KeyError, if key not present and default value not specified.
Python3
# Python 3 code to demonstrate# working of pop() # initializing dictionarytest_dict = {"Nikhil": 7, "Akshat": 1, "Akash": 2} # Printing initial dictprint("The dictionary before deletion : " + str(test_dict)) # using pop to return and remove key-value pair.pop_ele = test_dict.pop('Akash') # Printing the value associated to popped keyprint("Value associated to popped key is : " + str(pop_ele)) # Printing dictionary after deletionprint("Dictionary after deletion is : " + str(test_dict))
Output :
The dictionary before deletion : {'Nikhil': 7, 'Akshat': 1, 'Akash': 2}
Value associated to popped key is : 2
Dictionary after deletion is : {'Nikhil': 7, 'Akshat': 1}
Python3
# Python 3 code to demonstrate# working of pop() # initializing dictionarytest_dict = {"Nikhil": 7, "Akshat": 1, "Akash": 2} # Printing initial dictprint("The dictionary before deletion : " + str(test_dict)) # using pop to return and remove key-value pair.pop_first = test_dict.pop("Nikhil") # Printing the value associated to popped keyprint("Value associated to popped key is : " + str(pop_first)) # Printing dictionary after deletionprint("Dictionary after deletion is : " + str(test_dict))
Output:
The dictionary before deletion : {'Nikhil': 7, 'Akshat': 1, 'Akash': 2}
Value associated to popped key is : 7
Dictionary after deletion is : {'Akshat': 1, 'Akash': 2}
The behavior of pop() function is different when the key is not present in dictionary. In this case, it returns the default provided value or KeyError in case even default is not provided.
Python3
# Python 3 code to demonstrate# working of pop() without key # initializing dictionarytest_dict = {"Nikhil": 7, "Akshat": 1, "Akash": 2} # Printing initial dictprint("The dictionary before deletion : " + str(test_dict)) # using pop to return and remove key-value pair# provided defaultpop_ele = test_dict.pop('Manjeet', 4) # Printing the value associated to popped key# Prints 4print("Value associated to popped key is : " + str(pop_ele)) # using pop to return and remove key-value pair# not provided defaultpop_ele = test_dict.pop('Manjeet') # Printing the value associated to popped key# KeyErrorprint("Value associated to popped key is : " + str(pop_ele))
Output :
The dictionary before deletion : {'Nikhil': 7, 'Akshat': 1, 'Akash': 2}
Value associated to popped key is : 4
Traceback (most recent call last):
File "main.py", line 20, in
pop_ele = test_dict.pop('Manjeet')
KeyError: 'Manjeet'
kumar_satyam
vinayedula
rkbhola5
python-dict
Python-dict-functions
Python
python-dict
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
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Taking input in Python
Read a file line by line in Python
Python String | replace()
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n01 Jul, 2022"
},
{
"code": null,
"e": 147,
"s": 53,
"text": "Python dictionary pop() method removes and returns the specified element from the dictionary."
},
{
"code": null,
"e": 175,
"s": 147,
"text": "Syntax : dict.pop(key, def)"
},
{
"code": null,
"e": 189,
"s": 175,
"text": "Parameters : "
},
{
"code": null,
"e": 256,
"s": 189,
"text": "key : The key whose key-value pair has to be returned and removed."
},
{
"code": null,
"e": 323,
"s": 256,
"text": "def : The default value to return if specified key is not present."
},
{
"code": null,
"e": 509,
"s": 323,
"text": "Returns : Value associated to deleted key-value pair, if key is present. Default value if specified if key is not present. KeyError, if key not present and default value not specified. "
},
{
"code": null,
"e": 517,
"s": 509,
"text": "Python3"
},
{
"code": "# Python 3 code to demonstrate# working of pop() # initializing dictionarytest_dict = {\"Nikhil\": 7, \"Akshat\": 1, \"Akash\": 2} # Printing initial dictprint(\"The dictionary before deletion : \" + str(test_dict)) # using pop to return and remove key-value pair.pop_ele = test_dict.pop('Akash') # Printing the value associated to popped keyprint(\"Value associated to popped key is : \" + str(pop_ele)) # Printing dictionary after deletionprint(\"Dictionary after deletion is : \" + str(test_dict))",
"e": 1006,
"s": 517,
"text": null
},
{
"code": null,
"e": 1016,
"s": 1006,
"text": "Output : "
},
{
"code": null,
"e": 1184,
"s": 1016,
"text": "The dictionary before deletion : {'Nikhil': 7, 'Akshat': 1, 'Akash': 2}\nValue associated to popped key is : 2\nDictionary after deletion is : {'Nikhil': 7, 'Akshat': 1}"
},
{
"code": null,
"e": 1192,
"s": 1184,
"text": "Python3"
},
{
"code": "# Python 3 code to demonstrate# working of pop() # initializing dictionarytest_dict = {\"Nikhil\": 7, \"Akshat\": 1, \"Akash\": 2} # Printing initial dictprint(\"The dictionary before deletion : \" + str(test_dict)) # using pop to return and remove key-value pair.pop_first = test_dict.pop(\"Nikhil\") # Printing the value associated to popped keyprint(\"Value associated to popped key is : \" + str(pop_first)) # Printing dictionary after deletionprint(\"Dictionary after deletion is : \" + str(test_dict))",
"e": 1686,
"s": 1192,
"text": null
},
{
"code": null,
"e": 1694,
"s": 1686,
"text": "Output:"
},
{
"code": null,
"e": 1861,
"s": 1694,
"text": "The dictionary before deletion : {'Nikhil': 7, 'Akshat': 1, 'Akash': 2}\nValue associated to popped key is : 7\nDictionary after deletion is : {'Akshat': 1, 'Akash': 2}"
},
{
"code": null,
"e": 2050,
"s": 1861,
"text": "The behavior of pop() function is different when the key is not present in dictionary. In this case, it returns the default provided value or KeyError in case even default is not provided."
},
{
"code": null,
"e": 2058,
"s": 2050,
"text": "Python3"
},
{
"code": "# Python 3 code to demonstrate# working of pop() without key # initializing dictionarytest_dict = {\"Nikhil\": 7, \"Akshat\": 1, \"Akash\": 2} # Printing initial dictprint(\"The dictionary before deletion : \" + str(test_dict)) # using pop to return and remove key-value pair# provided defaultpop_ele = test_dict.pop('Manjeet', 4) # Printing the value associated to popped key# Prints 4print(\"Value associated to popped key is : \" + str(pop_ele)) # using pop to return and remove key-value pair# not provided defaultpop_ele = test_dict.pop('Manjeet') # Printing the value associated to popped key# KeyErrorprint(\"Value associated to popped key is : \" + str(pop_ele))",
"e": 2717,
"s": 2058,
"text": null
},
{
"code": null,
"e": 2727,
"s": 2717,
"text": "Output : "
},
{
"code": null,
"e": 2962,
"s": 2727,
"text": "The dictionary before deletion : {'Nikhil': 7, 'Akshat': 1, 'Akash': 2}\nValue associated to popped key is : 4\nTraceback (most recent call last):\n File \"main.py\", line 20, in \n pop_ele = test_dict.pop('Manjeet')\nKeyError: 'Manjeet'"
},
{
"code": null,
"e": 2975,
"s": 2962,
"text": "kumar_satyam"
},
{
"code": null,
"e": 2986,
"s": 2975,
"text": "vinayedula"
},
{
"code": null,
"e": 2995,
"s": 2986,
"text": "rkbhola5"
},
{
"code": null,
"e": 3007,
"s": 2995,
"text": "python-dict"
},
{
"code": null,
"e": 3029,
"s": 3007,
"text": "Python-dict-functions"
},
{
"code": null,
"e": 3036,
"s": 3029,
"text": "Python"
},
{
"code": null,
"e": 3048,
"s": 3036,
"text": "python-dict"
},
{
"code": null,
"e": 3146,
"s": 3048,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3174,
"s": 3146,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 3224,
"s": 3174,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 3246,
"s": 3224,
"text": "Python map() function"
},
{
"code": null,
"e": 3290,
"s": 3246,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 3308,
"s": 3290,
"text": "Python Dictionary"
},
{
"code": null,
"e": 3350,
"s": 3308,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 3372,
"s": 3350,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3395,
"s": 3372,
"text": "Taking input in Python"
},
{
"code": null,
"e": 3430,
"s": 3395,
"text": "Read a file line by line in Python"
}
] |
Zoho Software Developer Interview Experience
|
11 Dec, 2019
I was interviewed in Zoho’s Chennai office in November 2019. The whole process took two weeks.
Round 1: First round was a written round of 20 questions for 75 minutes. 10 questions from C and 10 based on aptitude. The C questions tested your knowledge on basic C concepts like functions, recursion, string manipulations etc. Aptitude questions were from ratio, average, simple puzzles, ages etc. But aptitude was simple than expected. You need to write all the answers at least only then there is a possibility that you can get into it.
Round 2: I got call from HR after three days to attend the second round. I also received a mail for second round which held next week. In this round I was given three programming questions for 75 minutes.
Questions were:
1. -1 represents ocean and 1 represents land find the number of islands in the given matrix.
Input: n*n matrix
1 -1 -1 1
-1 1 -1 1
-1 -1 1 -1
-1 -1 -1 1
Output: 2 (two islands that I have
bold in matrix at 1, 1 and 2, 2)
2. Print all the possible subsets of array which adds up to give a sum.
Input: array{2, 3, 5, 8, 10}
sum=10
Output: {2, 3, 5}
{2, 8}
{10}
3. There is a circular queue of processes. Every time there will be certain no of process skipped and a particular start position. Find the safe position.
Input: Number of process:5
Start position:3
Skip: 2nd
Output: 1 will be the safest position
(Logic: 1 2 3 4 5 starting from 3, 5th process will be skipped
1 2 3 4 5 process 2 will be skipped
1 2 3 4 5 process 4 will be skipped
1 2 3 4 5 process 3 will be skipped, so safest process is 1.
Here I was able to solve two questions and was selected for third round. Those who were not able to solve but are still good at explaining logic then they were considered for debugging team and went for further rounds. But this won’t happen every time. Only if they see any potential inside you to work for them sincerely they may consider you for other teams or else you are rejected at that point itself.Round 3: Third round was application development round. Question which I got was “Event Management”. There were around 20 events which are about to happen. Manage all the events according to the given conditions.List of events are given below none of them has any specific order to be followed.Conditionsare :1. Event should start from 9.00 AM2. No overlapping or any time gap between two events.3. The last event should complete by 4 or to maximum by 5. There is a compulsory eventcalled “Networking hands-on” which has to be started not earlier than 4.00 PM nor laterthan 5.00 PM. The remaining events should be scheduled following day until all theevents are covered.4. Every event has specific duration mentioned along with it and some events contain akeyword “lightning” which means that particular event’s duration is 5 minutes.5. There should be no event scheduled between 12 to 1 PM and kept for lunch.
Input:
Welcome event 30 minsC programming 45 minsWorking with Java Beans 30 minsRuby on Rails programming 60 minsIntroduction to Groovy 60 minsRails Debugging 45 minsTips and tricks in C 30 minsBack-end development in MySQL 50 minsSit down and Take notes lightningClojure Introduction 45 minsTeam Management Concepts 30 minsIntroduction to Java Frameworks lightningWorking with Angular JS 45 minsRuby on Rails programming web development concepts 60 minsIntroduction to Kotlin Java 60 minsDebugging and Testing products 60 minsDocumenting a software 40 minsServer side development 60 mins
Output:Schedule for Day 109:00 AM Welcome event 30 mins09:30 AM C programming 45 mins10:15 AM Ruby on Rails programming 60 mins11:15 AM Rails Debugging 45 mins12:00 PM LUNCH01:00 PM Working with Java Beans 30 mins01:30 PM Introduction to Groovy 60 mins02:30 PM Tips and tricks in C 30 mins03:00 PM Back-end development in MySQL 50 mins03:50 PM Sit down and Take notes lightning03:55 PM Clojure Introduction 45 mins04:40 PM Networking Hands-on
Schedule for Day 209:30 AM Team Management Concepts 30 mins09:30 AM Introduction to Java Frameworks lightning09:35 AM Working with Angular JS 45 mins10:20 AM Ruby on Rails programming web development concepts 60 mins11:20 AM Documenting a software 40 mins12:00 PM LUNCH01:00 PM Introduction to Kotlin Java 60 mins02:00 PM Debugging and Testing products 60 mins03:00 PM Server side development 60 mins04:00 PM Networking Hands-on
Round 4 and 5: These are HR rounds. Technical hr might check your basic understanding of concepts in programming and ask you to explain about your 3rd round question and how you can enhance your code. Common HR will ask basic questions about yourself, your strength and weaknesses, why zoho etc like that. All the best!
Marketing
Zoho
Interview Experiences
Zoho
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n11 Dec, 2019"
},
{
"code": null,
"e": 149,
"s": 54,
"text": "I was interviewed in Zoho’s Chennai office in November 2019. The whole process took two weeks."
},
{
"code": null,
"e": 592,
"s": 149,
"text": "Round 1: First round was a written round of 20 questions for 75 minutes. 10 questions from C and 10 based on aptitude. The C questions tested your knowledge on basic C concepts like functions, recursion, string manipulations etc. Aptitude questions were from ratio, average, simple puzzles, ages etc. But aptitude was simple than expected. You need to write all the answers at least only then there is a possibility that you can get into it."
},
{
"code": null,
"e": 797,
"s": 592,
"text": "Round 2: I got call from HR after three days to attend the second round. I also received a mail for second round which held next week. In this round I was given three programming questions for 75 minutes."
},
{
"code": null,
"e": 813,
"s": 797,
"text": "Questions were:"
},
{
"code": null,
"e": 906,
"s": 813,
"text": "1. -1 represents ocean and 1 represents land find the number of islands in the given matrix."
},
{
"code": null,
"e": 926,
"s": 906,
"text": "Input: n*n matrix"
},
{
"code": null,
"e": 1068,
"s": 926,
"text": " 1 -1 -1 1\n -1 1 -1 1\n -1 -1 1 -1\n -1 -1 -1 1\nOutput: 2 (two islands that I have \nbold in matrix at 1, 1 and 2, 2)\n"
},
{
"code": null,
"e": 1140,
"s": 1068,
"text": "2. Print all the possible subsets of array which adds up to give a sum."
},
{
"code": null,
"e": 1228,
"s": 1140,
"text": "Input: array{2, 3, 5, 8, 10}\n sum=10\nOutput: {2, 3, 5}\n {2, 8}\n {10}\n"
},
{
"code": null,
"e": 1383,
"s": 1228,
"text": "3. There is a circular queue of processes. Every time there will be certain no of process skipped and a particular start position. Find the safe position."
},
{
"code": null,
"e": 1709,
"s": 1383,
"text": "Input: Number of process:5\n Start position:3\n Skip: 2nd\nOutput: 1 will be the safest position\n(Logic: 1 2 3 4 5 starting from 3, 5th process will be skipped\n 1 2 3 4 5 process 2 will be skipped\n 1 2 3 4 5 process 4 will be skipped\n 1 2 3 4 5 process 3 will be skipped, so safest process is 1."
},
{
"code": null,
"e": 3026,
"s": 1709,
"text": "Here I was able to solve two questions and was selected for third round. Those who were not able to solve but are still good at explaining logic then they were considered for debugging team and went for further rounds. But this won’t happen every time. Only if they see any potential inside you to work for them sincerely they may consider you for other teams or else you are rejected at that point itself.Round 3: Third round was application development round. Question which I got was “Event Management”. There were around 20 events which are about to happen. Manage all the events according to the given conditions.List of events are given below none of them has any specific order to be followed.Conditionsare :1. Event should start from 9.00 AM2. No overlapping or any time gap between two events.3. The last event should complete by 4 or to maximum by 5. There is a compulsory eventcalled “Networking hands-on” which has to be started not earlier than 4.00 PM nor laterthan 5.00 PM. The remaining events should be scheduled following day until all theevents are covered.4. Every event has specific duration mentioned along with it and some events contain akeyword “lightning” which means that particular event’s duration is 5 minutes.5. There should be no event scheduled between 12 to 1 PM and kept for lunch."
},
{
"code": null,
"e": 3033,
"s": 3026,
"text": "Input:"
},
{
"code": null,
"e": 3615,
"s": 3033,
"text": "Welcome event 30 minsC programming 45 minsWorking with Java Beans 30 minsRuby on Rails programming 60 minsIntroduction to Groovy 60 minsRails Debugging 45 minsTips and tricks in C 30 minsBack-end development in MySQL 50 minsSit down and Take notes lightningClojure Introduction 45 minsTeam Management Concepts 30 minsIntroduction to Java Frameworks lightningWorking with Angular JS 45 minsRuby on Rails programming web development concepts 60 minsIntroduction to Kotlin Java 60 minsDebugging and Testing products 60 minsDocumenting a software 40 minsServer side development 60 mins"
},
{
"code": null,
"e": 4058,
"s": 3615,
"text": "Output:Schedule for Day 109:00 AM Welcome event 30 mins09:30 AM C programming 45 mins10:15 AM Ruby on Rails programming 60 mins11:15 AM Rails Debugging 45 mins12:00 PM LUNCH01:00 PM Working with Java Beans 30 mins01:30 PM Introduction to Groovy 60 mins02:30 PM Tips and tricks in C 30 mins03:00 PM Back-end development in MySQL 50 mins03:50 PM Sit down and Take notes lightning03:55 PM Clojure Introduction 45 mins04:40 PM Networking Hands-on"
},
{
"code": null,
"e": 4487,
"s": 4058,
"text": "Schedule for Day 209:30 AM Team Management Concepts 30 mins09:30 AM Introduction to Java Frameworks lightning09:35 AM Working with Angular JS 45 mins10:20 AM Ruby on Rails programming web development concepts 60 mins11:20 AM Documenting a software 40 mins12:00 PM LUNCH01:00 PM Introduction to Kotlin Java 60 mins02:00 PM Debugging and Testing products 60 mins03:00 PM Server side development 60 mins04:00 PM Networking Hands-on"
},
{
"code": null,
"e": 4807,
"s": 4487,
"text": "Round 4 and 5: These are HR rounds. Technical hr might check your basic understanding of concepts in programming and ask you to explain about your 3rd round question and how you can enhance your code. Common HR will ask basic questions about yourself, your strength and weaknesses, why zoho etc like that. All the best!"
},
{
"code": null,
"e": 4817,
"s": 4807,
"text": "Marketing"
},
{
"code": null,
"e": 4822,
"s": 4817,
"text": "Zoho"
},
{
"code": null,
"e": 4844,
"s": 4822,
"text": "Interview Experiences"
},
{
"code": null,
"e": 4849,
"s": 4844,
"text": "Zoho"
}
] |
Check if all bits of a number are set
|
22 Jun, 2022
Given a number n. The problem is to check whether every bit in the binary representation of the given number is set or not. Here 0 <= n.Examples :
Input : 7
Output : Yes
(7)10 = (111)2
Input : 14
Output : No
Method 1: If n = 0, then answer is ‘No’. Else perform the two operations until n becomes 0.
While (n > 0)
If n & 1 == 0,
return 'No'
n >> 1
If the loop terminates without returning ‘No’, then all bits are set in the binary representation of n.
C++
C
Java
Python3
C#
PHP
Javascript
// C++ implementation to check whether every digit in the// binary representation of the given number is set or not#include <bits/stdc++.h>using namespace std; // function to check if all the bits are set or not in the// binary representation of 'n'string areAllBitsSet(int n){ // all bits are not set if (n == 0) return "No"; // loop till n becomes '0' while (n > 0) { // if the last bit is not set if ((n & 1) == 0) return "No"; // right shift 'n' by 1 n = n >> 1; } // all bits are set return "Yes";} // Driver program to test aboveint main(){ int n = 7; cout << areAllBitsSet(n); return 0;} // This code is contributed by Sania Kumari Gupta (kriSania804)
// C implementation to check whether every digit in the// binary representation of the given number is set or not#include <stdio.h> // function to check if all the bits are set or not in the// binary representation of 'n'void areAllBitsSet(int n){ // all bits are not set if (n == 0) printf("No"); // loop till n becomes '0' while (n > 0) { // if the last bit is not set if ((n & 1) == 0) printf("No"); // right shift 'n' by 1 n = n >> 1; } // all bits are set printf("Yes");} // Driver program to test aboveint main(){ int n = 7; areAllBitsSet(n); return 0;} // This code is contributed by Sania Kumari Gupta (kriSania804)
// java implementation to check// whether every digit in the// binary representation of the// given number is set or notimport java.io.*; class GFG { // function to check if all the bits // are setthe bits are set or not // in the binary representation of 'n' static String areAllBitsSet(int n) { // all bits are not set if (n == 0) return "No"; // loop till n becomes '0' while (n > 0) { // if the last bit is not set if ((n & 1) == 0) return "No"; // right shift 'n' by 1 n = n >> 1; } // all bits are set return "Yes"; } // Driver program to test above public static void main (String[] args) { int n = 7; System.out.println(areAllBitsSet(n)); }} // This code is contributed by vt_m
# Python implementation# to check whether every# digit in the binary# representation of the# given number is set or not # function to check if# all the bits are set# or not in the binary# representation of 'n'def areAllBitsSet(n): # all bits are not set if (n == 0): return "No" # loop till n becomes '0' while (n > 0): # if the last bit is not set if ((n & 1) == 0): return "No" # right shift 'n' by 1 n = n >> 1 # all bits are set return "Yes" # Driver program to test above n = 7print(areAllBitsSet(n)) # This code is contributed# by Anant Agarwal.
// C# implementation to check// whether every digit in the// binary representation of the// given number is set or notusing System; class GFG{ // function to check if // all the bits are set // or not in the binary // representation of 'n' static String areAllBitsSet(int n) { // all bits are not set if (n == 0) return "No"; // loop till n becomes '0' while (n > 0) { // if the last bit // is not set if ((n & 1) == 0) return "No"; // right shift 'n' by 1 n = n >> 1; } // all bits are set return "Yes"; } // Driver Code static public void Main () { int n = 7; Console.WriteLine(areAllBitsSet(n)); }} // This code is contributed by ajit
<?php// PHP implementation to check// whether every digit in the// binary representation of the// given number is set or not // function to check if all the// bits are set or not in the// binary representation of 'n'function areAllBitsSet($n){ // all bits are not set if ($n == 0) return "No"; // loop till n becomes '0' while ($n > 0) { // if the last bit is not set if (($n & 1) == 0) return "No"; // right shift 'n' by 1 $n = $n >> 1; } // all bits are set return "Yes";} // Driver Code$n = 7;echo areAllBitsSet($n); // This code is contributed by aj_36?>
<script> // javascript implementation to check// whether every digit in the// binary representation of the// given number is set or not // function to check if all the bits// are setthe bits are set or not// in the binary representation of 'n'function areAllBitsSet(n){ // all bits are not set if (n == 0) return "No"; // loop till n becomes '0' while (n > 0) { // if the last bit is not set if ((n & 1) == 0) return "No"; // right shift 'n' by 1 n = n >> 1; } // all bits are set return "Yes";} // Driver program to test abovevar n = 7;document.write(areAllBitsSet(n)); // This code contributed by Princi Singh </script>
Output :
Yes
Time Complexity: O(d), where ‘d’ is the number of bits in the binary representation of n.Auxiliary Space: O(1) Method 2: If n = 0, then answer is ‘No’. Else add 1 to n. Let it be num = n + 1. If num & (num – 1) == 0, then all bits are set, else all bits are not set. Explanation: If all bits in the binary representation of n are set, then adding ‘1’ to it will produce a number that will be a perfect power of 2. Now, check whether the new number is a perfect power of 2 or not.
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation to check whether every// digit in the binary representation of the// given number is set or not#include <bits/stdc++.h>using namespace std; // function to check if all the bits are set// or not in the binary representation of 'n'string areAllBitsSet(int n){ // all bits are not set if (n == 0) return "No"; // if true, then all bits are set if (((n + 1) & n) == 0) return "Yes"; // else all bits are not set return "No";} // Driver program to test aboveint main(){ int n = 7; cout << areAllBitsSet(n); return 0;}
// JAVA implementation to check whether// every digit in the binary representation// of the given number is set or notimport java.io.*; class GFG { // function to check if all the // bits are set or not in the // binary representation of 'n' static String areAllBitsSet(int n) { // all bits are not set if (n == 0) return "No"; // if true, then all bits are set if (((n + 1) & n) == 0) return "Yes"; // else all bits are not set return "No"; } // Driver program to test above public static void main (String[] args) { int n = 7; System.out.println(areAllBitsSet(n)); }} // This code is contributed by vt_m
# Python implementation to# check whether every# digit in the binary# representation of the# given number is set or not # function to check if# all the bits are set# or not in the binary# representation of 'n'def areAllBitsSet(n): # all bits are not set if (n == 0): return "No" # if true, then all bits are set if (((n + 1) & n) == 0): return "Yes" # else all bits are not set return "No" # Driver program to test above n = 7print(areAllBitsSet(n)) # This code is contributed# by Anant Agarwal.
// C# implementation to check// whether every digit in the// binary representation of// the given number is set or notusing System; class GFG{ // function to check if all the // bits are set or not in the // binary representation of 'n' static String areAllBitsSet(int n) { // all bits are not set if (n == 0) return "No"; // if true, then all // bits are set if (((n + 1) & n) == 0) return "Yes"; // else all bits are not set return "No"; } // Driver Code static public void Main () { int n = 7; Console.WriteLine(areAllBitsSet(n)); }} // This code is contributed by m_kit
<?php// PHP implementation to check// whether every digit in the// binary representation of the// given number is set or not // function to check if all// the bits are set or not in// the binary representation of 'n'function areAllBitsSet($n){ // all bits are not set if ($n == 0) return "No"; // if true, then all // bits are set if ((($n + 1) & $n) == 0) return "Yes"; // else all bits // are not set return "No";} // Driver Code$n = 7;echo areAllBitsSet($n); // This code is contributed by ajit?>
<script>// javascript implementation to check whether// every digit in the binary representation// of the given number is set or not // function to check if all the// bits are set or not in the// binary representation of 'n'function areAllBitsSet(n){ // all bits are not set if (n == 0) return "No"; // if true, then all bits are set if (((n + 1) & n) == 0) return "Yes"; // else all bits are not set return "No";} // Driver program to test abovevar n = 7;document.write(areAllBitsSet(n)); // This code contributed by Princi Singh</script>
Yes
Time Complexity: O(1)Auxiliary Space: O(1)
Method 3: We can simply count the total set bits present in the binary representation of the number and based on this, we can check if the number is equal to pow(2, __builtin_popcount(n)). If it happens to be equal, then we return 1, else return 0;
C++
Java
Python3
C#
Javascript
#include <bits/stdc++.h>using namespace std; void isBitSet(int N){ if (N == pow(2, __builtin_popcount(N)) - 1) cout << "Yes\n"; else cout << "No\n";} int main(){ int N = 7; isBitSet(N); return 0;}
import java.util.*; class GFG{ static void isBitSet(int N){ if (N == Math.pow(2, Integer.bitCount(N)) - 1) System.out.print("Yes\n"); else System.out.print("No\n");} public static void main(String[] args){ int N = 7; isBitSet(N);}} // This code is contributed by umadevi9616
def bitCount(n): n = n - ((n >> 1) & 0x55555555); n = (n & 0x33333333) + ((n >> 2) & 0x33333333); return ((n + (n >> 4) & 0xF0F0F0F) * 0x1010101) >> 24; def isBitSet(N): if (N == pow(2, bitCount(N)) - 1): print("Yes"); else: print("No"); if __name__ == '__main__': N = 7; isBitSet(N); # This code is contributed by gauravrajput1
using System; public class GFG{ static int bitCount (int n) { n = n - ((n >> 1) & 0x55555555); n = (n & 0x33333333) + ((n >> 2) & 0x33333333); return ((n + (n >> 4) & 0xF0F0F0F) * 0x1010101) >> 24; } static void isBitSet(int N){ if (N == Math.Pow(2, bitCount(N)) - 1) Console.Write("Yes\n"); else Console.Write("No\n");} public static void Main(String[] args){ int N = 7; isBitSet(N);}} // This code is contributed by umadevi9616
<script> function bitCount (n) { n = n - ((n >> 1) & 0x55555555); n = (n & 0x33333333) + ((n >> 2) & 0x33333333); return ((n + (n >> 4) & 0xF0F0F0F) * 0x1010101) >> 24; } function isBitSet(N) { if (N == Math.pow(2, bitCount(N)) - 1) document.write("Yes\n"); else document.write("No\n"); } var N = 7; isBitSet(N); // This code is contributed by umadevi9616</script>
Output:
Yes
Time Complexity: O(1)Auxiliary Space: O(1)
References: https://www.careercup.com/question?id=9503107This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
jit_t
princi singh
bhargabnath691
umadevi9616
GauravRajput1
krisania804
ranjanrohit840
Amazon
Bit Magic
Amazon
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n22 Jun, 2022"
},
{
"code": null,
"e": 200,
"s": 52,
"text": "Given a number n. The problem is to check whether every bit in the binary representation of the given number is set or not. Here 0 <= n.Examples : "
},
{
"code": null,
"e": 262,
"s": 200,
"text": "Input : 7\nOutput : Yes\n(7)10 = (111)2\n\nInput : 14\nOutput : No"
},
{
"code": null,
"e": 355,
"s": 262,
"text": "Method 1: If n = 0, then answer is ‘No’. Else perform the two operations until n becomes 0. "
},
{
"code": null,
"e": 411,
"s": 355,
"text": "While (n > 0)\n If n & 1 == 0, \n return 'No'\n n >> 1"
},
{
"code": null,
"e": 516,
"s": 411,
"text": "If the loop terminates without returning ‘No’, then all bits are set in the binary representation of n. "
},
{
"code": null,
"e": 520,
"s": 516,
"text": "C++"
},
{
"code": null,
"e": 522,
"s": 520,
"text": "C"
},
{
"code": null,
"e": 527,
"s": 522,
"text": "Java"
},
{
"code": null,
"e": 535,
"s": 527,
"text": "Python3"
},
{
"code": null,
"e": 538,
"s": 535,
"text": "C#"
},
{
"code": null,
"e": 542,
"s": 538,
"text": "PHP"
},
{
"code": null,
"e": 553,
"s": 542,
"text": "Javascript"
},
{
"code": "// C++ implementation to check whether every digit in the// binary representation of the given number is set or not#include <bits/stdc++.h>using namespace std; // function to check if all the bits are set or not in the// binary representation of 'n'string areAllBitsSet(int n){ // all bits are not set if (n == 0) return \"No\"; // loop till n becomes '0' while (n > 0) { // if the last bit is not set if ((n & 1) == 0) return \"No\"; // right shift 'n' by 1 n = n >> 1; } // all bits are set return \"Yes\";} // Driver program to test aboveint main(){ int n = 7; cout << areAllBitsSet(n); return 0;} // This code is contributed by Sania Kumari Gupta (kriSania804)",
"e": 1288,
"s": 553,
"text": null
},
{
"code": "// C implementation to check whether every digit in the// binary representation of the given number is set or not#include <stdio.h> // function to check if all the bits are set or not in the// binary representation of 'n'void areAllBitsSet(int n){ // all bits are not set if (n == 0) printf(\"No\"); // loop till n becomes '0' while (n > 0) { // if the last bit is not set if ((n & 1) == 0) printf(\"No\"); // right shift 'n' by 1 n = n >> 1; } // all bits are set printf(\"Yes\");} // Driver program to test aboveint main(){ int n = 7; areAllBitsSet(n); return 0;} // This code is contributed by Sania Kumari Gupta (kriSania804)",
"e": 1988,
"s": 1288,
"text": null
},
{
"code": "// java implementation to check// whether every digit in the// binary representation of the// given number is set or notimport java.io.*; class GFG { // function to check if all the bits // are setthe bits are set or not // in the binary representation of 'n' static String areAllBitsSet(int n) { // all bits are not set if (n == 0) return \"No\"; // loop till n becomes '0' while (n > 0) { // if the last bit is not set if ((n & 1) == 0) return \"No\"; // right shift 'n' by 1 n = n >> 1; } // all bits are set return \"Yes\"; } // Driver program to test above public static void main (String[] args) { int n = 7; System.out.println(areAllBitsSet(n)); }} // This code is contributed by vt_m",
"e": 2872,
"s": 1988,
"text": null
},
{
"code": "# Python implementation# to check whether every# digit in the binary# representation of the# given number is set or not # function to check if# all the bits are set# or not in the binary# representation of 'n'def areAllBitsSet(n): # all bits are not set if (n == 0): return \"No\" # loop till n becomes '0' while (n > 0): # if the last bit is not set if ((n & 1) == 0): return \"No\" # right shift 'n' by 1 n = n >> 1 # all bits are set return \"Yes\" # Driver program to test above n = 7print(areAllBitsSet(n)) # This code is contributed# by Anant Agarwal.",
"e": 3507,
"s": 2872,
"text": null
},
{
"code": "// C# implementation to check// whether every digit in the// binary representation of the// given number is set or notusing System; class GFG{ // function to check if // all the bits are set // or not in the binary // representation of 'n' static String areAllBitsSet(int n) { // all bits are not set if (n == 0) return \"No\"; // loop till n becomes '0' while (n > 0) { // if the last bit // is not set if ((n & 1) == 0) return \"No\"; // right shift 'n' by 1 n = n >> 1; } // all bits are set return \"Yes\"; } // Driver Code static public void Main () { int n = 7; Console.WriteLine(areAllBitsSet(n)); }} // This code is contributed by ajit",
"e": 4363,
"s": 3507,
"text": null
},
{
"code": "<?php// PHP implementation to check// whether every digit in the// binary representation of the// given number is set or not // function to check if all the// bits are set or not in the// binary representation of 'n'function areAllBitsSet($n){ // all bits are not set if ($n == 0) return \"No\"; // loop till n becomes '0' while ($n > 0) { // if the last bit is not set if (($n & 1) == 0) return \"No\"; // right shift 'n' by 1 $n = $n >> 1; } // all bits are set return \"Yes\";} // Driver Code$n = 7;echo areAllBitsSet($n); // This code is contributed by aj_36?>",
"e": 4995,
"s": 4363,
"text": null
},
{
"code": "<script> // javascript implementation to check// whether every digit in the// binary representation of the// given number is set or not // function to check if all the bits// are setthe bits are set or not// in the binary representation of 'n'function areAllBitsSet(n){ // all bits are not set if (n == 0) return \"No\"; // loop till n becomes '0' while (n > 0) { // if the last bit is not set if ((n & 1) == 0) return \"No\"; // right shift 'n' by 1 n = n >> 1; } // all bits are set return \"Yes\";} // Driver program to test abovevar n = 7;document.write(areAllBitsSet(n)); // This code contributed by Princi Singh </script>",
"e": 5705,
"s": 4995,
"text": null
},
{
"code": null,
"e": 5716,
"s": 5705,
"text": "Output : "
},
{
"code": null,
"e": 5720,
"s": 5716,
"text": "Yes"
},
{
"code": null,
"e": 6202,
"s": 5720,
"text": "Time Complexity: O(d), where ‘d’ is the number of bits in the binary representation of n.Auxiliary Space: O(1) Method 2: If n = 0, then answer is ‘No’. Else add 1 to n. Let it be num = n + 1. If num & (num – 1) == 0, then all bits are set, else all bits are not set. Explanation: If all bits in the binary representation of n are set, then adding ‘1’ to it will produce a number that will be a perfect power of 2. Now, check whether the new number is a perfect power of 2 or not. "
},
{
"code": null,
"e": 6206,
"s": 6202,
"text": "C++"
},
{
"code": null,
"e": 6211,
"s": 6206,
"text": "Java"
},
{
"code": null,
"e": 6219,
"s": 6211,
"text": "Python3"
},
{
"code": null,
"e": 6222,
"s": 6219,
"text": "C#"
},
{
"code": null,
"e": 6226,
"s": 6222,
"text": "PHP"
},
{
"code": null,
"e": 6237,
"s": 6226,
"text": "Javascript"
},
{
"code": "// C++ implementation to check whether every// digit in the binary representation of the// given number is set or not#include <bits/stdc++.h>using namespace std; // function to check if all the bits are set// or not in the binary representation of 'n'string areAllBitsSet(int n){ // all bits are not set if (n == 0) return \"No\"; // if true, then all bits are set if (((n + 1) & n) == 0) return \"Yes\"; // else all bits are not set return \"No\";} // Driver program to test aboveint main(){ int n = 7; cout << areAllBitsSet(n); return 0;}",
"e": 6815,
"s": 6237,
"text": null
},
{
"code": "// JAVA implementation to check whether// every digit in the binary representation// of the given number is set or notimport java.io.*; class GFG { // function to check if all the // bits are set or not in the // binary representation of 'n' static String areAllBitsSet(int n) { // all bits are not set if (n == 0) return \"No\"; // if true, then all bits are set if (((n + 1) & n) == 0) return \"Yes\"; // else all bits are not set return \"No\"; } // Driver program to test above public static void main (String[] args) { int n = 7; System.out.println(areAllBitsSet(n)); }} // This code is contributed by vt_m",
"e": 7538,
"s": 6815,
"text": null
},
{
"code": "# Python implementation to# check whether every# digit in the binary# representation of the# given number is set or not # function to check if# all the bits are set# or not in the binary# representation of 'n'def areAllBitsSet(n): # all bits are not set if (n == 0): return \"No\" # if true, then all bits are set if (((n + 1) & n) == 0): return \"Yes\" # else all bits are not set return \"No\" # Driver program to test above n = 7print(areAllBitsSet(n)) # This code is contributed# by Anant Agarwal.",
"e": 8073,
"s": 7538,
"text": null
},
{
"code": "// C# implementation to check// whether every digit in the// binary representation of// the given number is set or notusing System; class GFG{ // function to check if all the // bits are set or not in the // binary representation of 'n' static String areAllBitsSet(int n) { // all bits are not set if (n == 0) return \"No\"; // if true, then all // bits are set if (((n + 1) & n) == 0) return \"Yes\"; // else all bits are not set return \"No\"; } // Driver Code static public void Main () { int n = 7; Console.WriteLine(areAllBitsSet(n)); }} // This code is contributed by m_kit",
"e": 8782,
"s": 8073,
"text": null
},
{
"code": "<?php// PHP implementation to check// whether every digit in the// binary representation of the// given number is set or not // function to check if all// the bits are set or not in// the binary representation of 'n'function areAllBitsSet($n){ // all bits are not set if ($n == 0) return \"No\"; // if true, then all // bits are set if ((($n + 1) & $n) == 0) return \"Yes\"; // else all bits // are not set return \"No\";} // Driver Code$n = 7;echo areAllBitsSet($n); // This code is contributed by ajit?>",
"e": 9322,
"s": 8782,
"text": null
},
{
"code": "<script>// javascript implementation to check whether// every digit in the binary representation// of the given number is set or not // function to check if all the// bits are set or not in the// binary representation of 'n'function areAllBitsSet(n){ // all bits are not set if (n == 0) return \"No\"; // if true, then all bits are set if (((n + 1) & n) == 0) return \"Yes\"; // else all bits are not set return \"No\";} // Driver program to test abovevar n = 7;document.write(areAllBitsSet(n)); // This code contributed by Princi Singh</script>",
"e": 9899,
"s": 9322,
"text": null
},
{
"code": null,
"e": 9903,
"s": 9899,
"text": "Yes"
},
{
"code": null,
"e": 9947,
"s": 9903,
"text": "Time Complexity: O(1)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 10196,
"s": 9947,
"text": "Method 3: We can simply count the total set bits present in the binary representation of the number and based on this, we can check if the number is equal to pow(2, __builtin_popcount(n)). If it happens to be equal, then we return 1, else return 0;"
},
{
"code": null,
"e": 10200,
"s": 10196,
"text": "C++"
},
{
"code": null,
"e": 10205,
"s": 10200,
"text": "Java"
},
{
"code": null,
"e": 10213,
"s": 10205,
"text": "Python3"
},
{
"code": null,
"e": 10216,
"s": 10213,
"text": "C#"
},
{
"code": null,
"e": 10227,
"s": 10216,
"text": "Javascript"
},
{
"code": "#include <bits/stdc++.h>using namespace std; void isBitSet(int N){ if (N == pow(2, __builtin_popcount(N)) - 1) cout << \"Yes\\n\"; else cout << \"No\\n\";} int main(){ int N = 7; isBitSet(N); return 0;}",
"e": 10446,
"s": 10227,
"text": null
},
{
"code": "import java.util.*; class GFG{ static void isBitSet(int N){ if (N == Math.pow(2, Integer.bitCount(N)) - 1) System.out.print(\"Yes\\n\"); else System.out.print(\"No\\n\");} public static void main(String[] args){ int N = 7; isBitSet(N);}} // This code is contributed by umadevi9616",
"e": 10740,
"s": 10446,
"text": null
},
{
"code": "def bitCount(n): n = n - ((n >> 1) & 0x55555555); n = (n & 0x33333333) + ((n >> 2) & 0x33333333); return ((n + (n >> 4) & 0xF0F0F0F) * 0x1010101) >> 24; def isBitSet(N): if (N == pow(2, bitCount(N)) - 1): print(\"Yes\"); else: print(\"No\"); if __name__ == '__main__': N = 7; isBitSet(N); # This code is contributed by gauravrajput1",
"e": 11110,
"s": 10740,
"text": null
},
{
"code": "using System; public class GFG{ static int bitCount (int n) { n = n - ((n >> 1) & 0x55555555); n = (n & 0x33333333) + ((n >> 2) & 0x33333333); return ((n + (n >> 4) & 0xF0F0F0F) * 0x1010101) >> 24; } static void isBitSet(int N){ if (N == Math.Pow(2, bitCount(N)) - 1) Console.Write(\"Yes\\n\"); else Console.Write(\"No\\n\");} public static void Main(String[] args){ int N = 7; isBitSet(N);}} // This code is contributed by umadevi9616",
"e": 11607,
"s": 11110,
"text": null
},
{
"code": "<script> function bitCount (n) { n = n - ((n >> 1) & 0x55555555); n = (n & 0x33333333) + ((n >> 2) & 0x33333333); return ((n + (n >> 4) & 0xF0F0F0F) * 0x1010101) >> 24; } function isBitSet(N) { if (N == Math.pow(2, bitCount(N)) - 1) document.write(\"Yes\\n\"); else document.write(\"No\\n\"); } var N = 7; isBitSet(N); // This code is contributed by umadevi9616</script>",
"e": 12057,
"s": 11607,
"text": null
},
{
"code": null,
"e": 12065,
"s": 12057,
"text": "Output:"
},
{
"code": null,
"e": 12069,
"s": 12065,
"text": "Yes"
},
{
"code": null,
"e": 12112,
"s": 12069,
"text": "Time Complexity: O(1)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 12591,
"s": 12112,
"text": "References: https://www.careercup.com/question?id=9503107This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 12597,
"s": 12591,
"text": "jit_t"
},
{
"code": null,
"e": 12610,
"s": 12597,
"text": "princi singh"
},
{
"code": null,
"e": 12625,
"s": 12610,
"text": "bhargabnath691"
},
{
"code": null,
"e": 12637,
"s": 12625,
"text": "umadevi9616"
},
{
"code": null,
"e": 12651,
"s": 12637,
"text": "GauravRajput1"
},
{
"code": null,
"e": 12663,
"s": 12651,
"text": "krisania804"
},
{
"code": null,
"e": 12678,
"s": 12663,
"text": "ranjanrohit840"
},
{
"code": null,
"e": 12685,
"s": 12678,
"text": "Amazon"
},
{
"code": null,
"e": 12695,
"s": 12685,
"text": "Bit Magic"
},
{
"code": null,
"e": 12702,
"s": 12695,
"text": "Amazon"
},
{
"code": null,
"e": 12712,
"s": 12702,
"text": "Bit Magic"
}
] |
Input and Output
|
07 Jun, 2022
Let us discuss what is Console in Python. Console (also called Shell) is basically a command-line interpreter that takes input from the user i.e one command at a time and interprets it. If it is error-free then it runs the command and gives the required output otherwise shows the error message. A Python Console looks like this.
Here we write a command and to execute the command just press enter key and your command will be interpreted. For coding in Python, you must know the basics of the console used in Python. The primary prompt of the python console is the three greater than symbols:
>>>
You are free to write the next command on the shell only when after executing the first command these prompts have appeared. The Python Console accepts commands in Python that you write after the prompt.
Accepting Input from Console User enters the values in the Console and that value is then used in the program as it was required. To take input from the user we make use of a built-in function input().
Example
Python
# inputinput1 = input() # outputprint(input1)
Output:
>>>Geeks for Geeks
'Geeks for Geeks'
We can also type cast this input to integer, float or string by specifying the input() function inside the type.
Typecasting the input to Integer: There might be conditions when you might require integer input from user/Console, the following code takes two input(integer/float) from console and typecasts them to integer then prints the sum.
Python
# inputnum1 = int(input())num2 = int(input()) # printing the sum in integerprint(num1 + num2)
Output:
>>>10
>>>20
30
Typecasting the input to Float: To convert the input to float the following code will work out.
Python
# inputnum1 = float(input())num2 = float(input()) # printing the sum in floatprint(num1 + num2)
Output:
>>>10
>>>20
30.0
Typecasting the input to String: All kinds of input can be converted to string type whether they are float or integer. We make use of keyword str for typecasting.
Python
# inputstring = str(input()) # outputprint(string)
Output:
>>>20.0
'20.0'
How to Input Multiple Values From User in One Line: For instance, in C we can do something like this:
C
// Reads two values in one linescanf("%d %d", &x, &y)
One solution is to use input() function two times.
Python3
x, y = input(), input()print("x=",x,"y=",y)
Output:
>>>geeks
>>>for geeks
x= geeks y= forgeeks
Another solution is to use split() function.
Python3
x, y = input().split()print("x=",x,"y=",y)
Output:
>>>10 20
x= 10 y= 20
Note that we don’t have to explicitly specify split(‘ ‘) because split() uses whitespace characters as a delimiter as default. One thing to note in the above Python code is, that both x and y would be of string. We can convert them to int using another line.
>>>x, y = [int(x), int(y)]
>>>print(x,y)
10 20
# We can also use list comprehension
>>>x, y = [int(x) for x in [x, y]]
>>>print(x,y)
10 20
Below is a complete one-line code to read two integer variables from standard input using split and list comprehension.
Python3
# Read two numbers from input and typecasts them to int using# list comprehensionx, y = [int(x) for x in input().split()]
Python3
# Reads two numbers from input and typecasts them to int using# map functionx, y = map(int, input().split())
END Parameter: By default python’s print() function ends with a newline. A programmer with C/C++ background may wonder how to print without a newline. Python’s print() function comes with a parameter called ‘end’. By default, the value of this parameter is ‘\n’, i.e., the new line character. You can end a print statement with any character/string using this parameter.
Python3
# This Python program must be run with# Python 3 as it won't work with 2.7. # ends the output with a <space>print("Welcome to" , end = ' ')print("GeeksforGeeks", end = ' ')
Output:
Welcome to GeeksforGeeks
One more program to demonstrate the working of end parameter.
Python3
# This Python program must be run with# Python 3 as it won't work with 2.7. # ends the output with '@'print("Python" , end = '@')print("GeeksforGeeks")
Output:
Python@GeeksforGeeks
sheetal18june
Picked
python-input-output
Python
School Programming
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, 2022"
},
{
"code": null,
"e": 383,
"s": 53,
"text": "Let us discuss what is Console in Python. Console (also called Shell) is basically a command-line interpreter that takes input from the user i.e one command at a time and interprets it. If it is error-free then it runs the command and gives the required output otherwise shows the error message. A Python Console looks like this."
},
{
"code": null,
"e": 650,
"s": 386,
"text": "Here we write a command and to execute the command just press enter key and your command will be interpreted. For coding in Python, you must know the basics of the console used in Python. The primary prompt of the python console is the three greater than symbols:"
},
{
"code": null,
"e": 654,
"s": 650,
"text": ">>>"
},
{
"code": null,
"e": 858,
"s": 654,
"text": "You are free to write the next command on the shell only when after executing the first command these prompts have appeared. The Python Console accepts commands in Python that you write after the prompt."
},
{
"code": null,
"e": 1064,
"s": 861,
"text": "Accepting Input from Console User enters the values in the Console and that value is then used in the program as it was required. To take input from the user we make use of a built-in function input(). "
},
{
"code": null,
"e": 1072,
"s": 1064,
"text": "Example"
},
{
"code": null,
"e": 1079,
"s": 1072,
"text": "Python"
},
{
"code": "# inputinput1 = input() # outputprint(input1)",
"e": 1125,
"s": 1079,
"text": null
},
{
"code": null,
"e": 1134,
"s": 1125,
"text": "Output: "
},
{
"code": null,
"e": 1171,
"s": 1134,
"text": ">>>Geeks for Geeks\n'Geeks for Geeks'"
},
{
"code": null,
"e": 1284,
"s": 1171,
"text": "We can also type cast this input to integer, float or string by specifying the input() function inside the type."
},
{
"code": null,
"e": 1515,
"s": 1284,
"text": "Typecasting the input to Integer: There might be conditions when you might require integer input from user/Console, the following code takes two input(integer/float) from console and typecasts them to integer then prints the sum. "
},
{
"code": null,
"e": 1522,
"s": 1515,
"text": "Python"
},
{
"code": "# inputnum1 = int(input())num2 = int(input()) # printing the sum in integerprint(num1 + num2)",
"e": 1616,
"s": 1522,
"text": null
},
{
"code": null,
"e": 1624,
"s": 1616,
"text": "Output:"
},
{
"code": null,
"e": 1639,
"s": 1624,
"text": ">>>10\n>>>20\n30"
},
{
"code": null,
"e": 1736,
"s": 1639,
"text": "Typecasting the input to Float: To convert the input to float the following code will work out. "
},
{
"code": null,
"e": 1743,
"s": 1736,
"text": "Python"
},
{
"code": "# inputnum1 = float(input())num2 = float(input()) # printing the sum in floatprint(num1 + num2)",
"e": 1839,
"s": 1743,
"text": null
},
{
"code": null,
"e": 1847,
"s": 1839,
"text": "Output:"
},
{
"code": null,
"e": 1864,
"s": 1847,
"text": ">>>10\n>>>20\n30.0"
},
{
"code": null,
"e": 2028,
"s": 1864,
"text": "Typecasting the input to String: All kinds of input can be converted to string type whether they are float or integer. We make use of keyword str for typecasting. "
},
{
"code": null,
"e": 2035,
"s": 2028,
"text": "Python"
},
{
"code": "# inputstring = str(input()) # outputprint(string)",
"e": 2086,
"s": 2035,
"text": null
},
{
"code": null,
"e": 2094,
"s": 2086,
"text": "Output:"
},
{
"code": null,
"e": 2109,
"s": 2094,
"text": ">>>20.0\n'20.0'"
},
{
"code": null,
"e": 2212,
"s": 2109,
"text": "How to Input Multiple Values From User in One Line: For instance, in C we can do something like this: "
},
{
"code": null,
"e": 2214,
"s": 2212,
"text": "C"
},
{
"code": "// Reads two values in one linescanf(\"%d %d\", &x, &y)",
"e": 2268,
"s": 2214,
"text": null
},
{
"code": null,
"e": 2320,
"s": 2268,
"text": "One solution is to use input() function two times. "
},
{
"code": null,
"e": 2328,
"s": 2320,
"text": "Python3"
},
{
"code": "x, y = input(), input()print(\"x=\",x,\"y=\",y)",
"e": 2372,
"s": 2328,
"text": null
},
{
"code": null,
"e": 2380,
"s": 2372,
"text": "Output:"
},
{
"code": null,
"e": 2425,
"s": 2380,
"text": ">>>geeks \n>>>for geeks\nx= geeks y= forgeeks "
},
{
"code": null,
"e": 2470,
"s": 2425,
"text": "Another solution is to use split() function."
},
{
"code": null,
"e": 2478,
"s": 2470,
"text": "Python3"
},
{
"code": "x, y = input().split()print(\"x=\",x,\"y=\",y)",
"e": 2521,
"s": 2478,
"text": null
},
{
"code": null,
"e": 2529,
"s": 2521,
"text": "Output:"
},
{
"code": null,
"e": 2550,
"s": 2529,
"text": ">>>10 20\nx= 10 y= 20"
},
{
"code": null,
"e": 2809,
"s": 2550,
"text": "Note that we don’t have to explicitly specify split(‘ ‘) because split() uses whitespace characters as a delimiter as default. One thing to note in the above Python code is, that both x and y would be of string. We can convert them to int using another line."
},
{
"code": null,
"e": 2950,
"s": 2809,
"text": ">>>x, y = [int(x), int(y)]\n>>>print(x,y)\n10 20\n\n# We can also use list comprehension\n>>>x, y = [int(x) for x in [x, y]]\n>>>print(x,y)\n10 20"
},
{
"code": null,
"e": 3070,
"s": 2950,
"text": "Below is a complete one-line code to read two integer variables from standard input using split and list comprehension."
},
{
"code": null,
"e": 3078,
"s": 3070,
"text": "Python3"
},
{
"code": "# Read two numbers from input and typecasts them to int using# list comprehensionx, y = [int(x) for x in input().split()] ",
"e": 3201,
"s": 3078,
"text": null
},
{
"code": null,
"e": 3209,
"s": 3201,
"text": "Python3"
},
{
"code": "# Reads two numbers from input and typecasts them to int using# map functionx, y = map(int, input().split())",
"e": 3318,
"s": 3209,
"text": null
},
{
"code": null,
"e": 3690,
"s": 3318,
"text": "END Parameter: By default python’s print() function ends with a newline. A programmer with C/C++ background may wonder how to print without a newline. Python’s print() function comes with a parameter called ‘end’. By default, the value of this parameter is ‘\\n’, i.e., the new line character. You can end a print statement with any character/string using this parameter. "
},
{
"code": null,
"e": 3698,
"s": 3690,
"text": "Python3"
},
{
"code": "# This Python program must be run with# Python 3 as it won't work with 2.7. # ends the output with a <space>print(\"Welcome to\" , end = ' ')print(\"GeeksforGeeks\", end = ' ')",
"e": 3871,
"s": 3698,
"text": null
},
{
"code": null,
"e": 3879,
"s": 3871,
"text": "Output:"
},
{
"code": null,
"e": 3904,
"s": 3879,
"text": "Welcome to GeeksforGeeks"
},
{
"code": null,
"e": 3967,
"s": 3904,
"text": "One more program to demonstrate the working of end parameter. "
},
{
"code": null,
"e": 3975,
"s": 3967,
"text": "Python3"
},
{
"code": "# This Python program must be run with# Python 3 as it won't work with 2.7. # ends the output with '@'print(\"Python\" , end = '@')print(\"GeeksforGeeks\")",
"e": 4127,
"s": 3975,
"text": null
},
{
"code": null,
"e": 4135,
"s": 4127,
"text": "Output:"
},
{
"code": null,
"e": 4156,
"s": 4135,
"text": "Python@GeeksforGeeks"
},
{
"code": null,
"e": 4170,
"s": 4156,
"text": "sheetal18june"
},
{
"code": null,
"e": 4177,
"s": 4170,
"text": "Picked"
},
{
"code": null,
"e": 4197,
"s": 4177,
"text": "python-input-output"
},
{
"code": null,
"e": 4204,
"s": 4197,
"text": "Python"
},
{
"code": null,
"e": 4223,
"s": 4204,
"text": "School Programming"
}
] |
Python – Get number of characters, words, spaces and lines in a file
|
29 Dec, 2020
Prerequisite: File Handling in Python
Given a text file fname, the task is to count the total number of characters, words, spaces and lines in the file.
As we know, Python provides multiple in-built features and modules for handling files. Let’s discuss different ways to calculate total number of characters, words, spaces and lines in a file using Python.
Below is the implementation of the above approach.
# Python implementation to compute# number of characters, words, spaces# and lines in a file # Function to count number # of characters, words, spaces # and lines in a filedef counter(fname): # variable to store total word count num_words = 0 # variable to store total line count num_lines = 0 # variable to store total character count num_charc = 0 # variable to store total space count num_spaces = 0 # opening file using with() method # so that file gets closed # after completion of work with open(fname, 'r') as f: # loop to iterate file # line by line for line in f: # incrementing value of # num_lines with each # iteration of loop to # store total line count num_lines += 1 # declaring a variable word # and assigning its value as Y # because every file is # supposed to start with # a word or a character word = 'Y' # loop to iterate every # line letter by letter for letter in line: # condition to check # that the encountered character # is not white space and a word if (letter != ' ' and word == 'Y'): # incrementing the word # count by 1 num_words += 1 # assigning value N to # variable word because until # space will not encounter # a word can not be completed word = 'N' # condition to check # that the encountered character # is a white space elif (letter == ' '): # incrementing the space # count by 1 num_spaces += 1 # assigning value Y to # variable word because after # white space a word # is supposed to occur word = 'Y' # loop to iterate every # letter character by # character for i in letter: # condition to check # that the encountered character # is not white space and not # a newline character if(i !=" " and i !="\n"): # incrementing character # count by 1 num_charc += 1 # printing total word count print("Number of words in text file: ", num_words) # printing total line count print("Number of lines in text file: ", num_lines) # printing total character count print('Number of characters in text file: ', num_charc) # printing total space count print('Number of spaces in text file: ', num_spaces) # Driver Code: if __name__ == '__main__': fname = 'File1.txt' try: counter(fname) except: print('File not found')
Output:
Number of words in text file: 25
Number of lines in text file: 4
Number of characters in text file: 91
Number of spaces in text file: 21
Method #2: Using some built-in functions and OS module functionsIn this approach, the idea is to use the os.linesep() method of OS module to separate the lines on the current platform. When the interpreter’s scanner encounter os.linesep it replaces it with \n character. After that strip() and split() functions will be used to carry out the task.Get more idea about strip() and split() functions.
Below is the implementation of the above approach.
# Python implementation to compute# number of characters, words, spaces# and lines in a file # importing os moduleimport os # Function to count number # of characters, words, spaces # and lines in a filedef counter(fname): # variable to store total word count num_words = 0 # variable to store total line count num_lines = 0 # variable to store total character count num_charc = 0 # variable to store total space count num_spaces = 0 # opening file using with() method # so that file gets closed # after completion of work with open(fname, 'r') as f: # loop to iterate file # line by line for line in f: # separating a line # from \n character # and storing again in line # variable for further operations line = line.strip(os.linesep) # splitting the line # to make a list of # all the words present # in that line and storing # that list in # wordlist variable wordslist = line.split() # incrementing value of # num_lines with each # iteration of loop to # store total line count num_lines = num_lines + 1 # incrementing value of # num_words by the # number of items in the # list wordlist num_words = num_words + len(wordslist) # incrementing value of # num_charc by 1 whenever # value of variable c is other # than white space in the separated line num_charc = num_charc + sum(1 for c in line if c not in (os.linesep, ' ')) # incrementing value of # num_spaces by 1 whenever # value of variable s is # white space in the separated line num_spaces = num_spaces + sum(1 for s in line if s in (os.linesep, ' ')) # printing total word count print("Number of words in text file: ", num_words) # printing total line count print("Number of lines in text file: ", num_lines) # printing total character count print("Number of characters in text file: ", num_charc) # printing total space count print("Number of spaces in text file: ", num_spaces) # Driver Code: if __name__ == '__main__': fname = 'File1.txt' try: counter(fname) except: print('File not found')
Output:
Number of words in text file: 25
Number of lines in text file: 4
Number of characters in text file: 91
Number of spaces in text file: 21
nidhi_biet
Python file-handling-programs
Python os-module-programs
python-file-handling
python-os-module
Python
Python Programs
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n29 Dec, 2020"
},
{
"code": null,
"e": 91,
"s": 53,
"text": "Prerequisite: File Handling in Python"
},
{
"code": null,
"e": 206,
"s": 91,
"text": "Given a text file fname, the task is to count the total number of characters, words, spaces and lines in the file."
},
{
"code": null,
"e": 411,
"s": 206,
"text": "As we know, Python provides multiple in-built features and modules for handling files. Let’s discuss different ways to calculate total number of characters, words, spaces and lines in a file using Python."
},
{
"code": null,
"e": 462,
"s": 411,
"text": "Below is the implementation of the above approach."
},
{
"code": "# Python implementation to compute# number of characters, words, spaces# and lines in a file # Function to count number # of characters, words, spaces # and lines in a filedef counter(fname): # variable to store total word count num_words = 0 # variable to store total line count num_lines = 0 # variable to store total character count num_charc = 0 # variable to store total space count num_spaces = 0 # opening file using with() method # so that file gets closed # after completion of work with open(fname, 'r') as f: # loop to iterate file # line by line for line in f: # incrementing value of # num_lines with each # iteration of loop to # store total line count num_lines += 1 # declaring a variable word # and assigning its value as Y # because every file is # supposed to start with # a word or a character word = 'Y' # loop to iterate every # line letter by letter for letter in line: # condition to check # that the encountered character # is not white space and a word if (letter != ' ' and word == 'Y'): # incrementing the word # count by 1 num_words += 1 # assigning value N to # variable word because until # space will not encounter # a word can not be completed word = 'N' # condition to check # that the encountered character # is a white space elif (letter == ' '): # incrementing the space # count by 1 num_spaces += 1 # assigning value Y to # variable word because after # white space a word # is supposed to occur word = 'Y' # loop to iterate every # letter character by # character for i in letter: # condition to check # that the encountered character # is not white space and not # a newline character if(i !=\" \" and i !=\"\\n\"): # incrementing character # count by 1 num_charc += 1 # printing total word count print(\"Number of words in text file: \", num_words) # printing total line count print(\"Number of lines in text file: \", num_lines) # printing total character count print('Number of characters in text file: ', num_charc) # printing total space count print('Number of spaces in text file: ', num_spaces) # Driver Code: if __name__ == '__main__': fname = 'File1.txt' try: counter(fname) except: print('File not found')",
"e": 3860,
"s": 462,
"text": null
},
{
"code": null,
"e": 3868,
"s": 3860,
"text": "Output:"
},
{
"code": null,
"e": 4010,
"s": 3868,
"text": "Number of words in text file: 25\nNumber of lines in text file: 4\nNumber of characters in text file: 91\nNumber of spaces in text file: 21\n"
},
{
"code": null,
"e": 4409,
"s": 4010,
"text": " Method #2: Using some built-in functions and OS module functionsIn this approach, the idea is to use the os.linesep() method of OS module to separate the lines on the current platform. When the interpreter’s scanner encounter os.linesep it replaces it with \\n character. After that strip() and split() functions will be used to carry out the task.Get more idea about strip() and split() functions."
},
{
"code": null,
"e": 4460,
"s": 4409,
"text": "Below is the implementation of the above approach."
},
{
"code": "# Python implementation to compute# number of characters, words, spaces# and lines in a file # importing os moduleimport os # Function to count number # of characters, words, spaces # and lines in a filedef counter(fname): # variable to store total word count num_words = 0 # variable to store total line count num_lines = 0 # variable to store total character count num_charc = 0 # variable to store total space count num_spaces = 0 # opening file using with() method # so that file gets closed # after completion of work with open(fname, 'r') as f: # loop to iterate file # line by line for line in f: # separating a line # from \\n character # and storing again in line # variable for further operations line = line.strip(os.linesep) # splitting the line # to make a list of # all the words present # in that line and storing # that list in # wordlist variable wordslist = line.split() # incrementing value of # num_lines with each # iteration of loop to # store total line count num_lines = num_lines + 1 # incrementing value of # num_words by the # number of items in the # list wordlist num_words = num_words + len(wordslist) # incrementing value of # num_charc by 1 whenever # value of variable c is other # than white space in the separated line num_charc = num_charc + sum(1 for c in line if c not in (os.linesep, ' ')) # incrementing value of # num_spaces by 1 whenever # value of variable s is # white space in the separated line num_spaces = num_spaces + sum(1 for s in line if s in (os.linesep, ' ')) # printing total word count print(\"Number of words in text file: \", num_words) # printing total line count print(\"Number of lines in text file: \", num_lines) # printing total character count print(\"Number of characters in text file: \", num_charc) # printing total space count print(\"Number of spaces in text file: \", num_spaces) # Driver Code: if __name__ == '__main__': fname = 'File1.txt' try: counter(fname) except: print('File not found')",
"e": 7098,
"s": 4460,
"text": null
},
{
"code": null,
"e": 7106,
"s": 7098,
"text": "Output:"
},
{
"code": null,
"e": 7248,
"s": 7106,
"text": "Number of words in text file: 25\nNumber of lines in text file: 4\nNumber of characters in text file: 91\nNumber of spaces in text file: 21\n"
},
{
"code": null,
"e": 7259,
"s": 7248,
"text": "nidhi_biet"
},
{
"code": null,
"e": 7289,
"s": 7259,
"text": "Python file-handling-programs"
},
{
"code": null,
"e": 7315,
"s": 7289,
"text": "Python os-module-programs"
},
{
"code": null,
"e": 7336,
"s": 7315,
"text": "python-file-handling"
},
{
"code": null,
"e": 7353,
"s": 7336,
"text": "python-os-module"
},
{
"code": null,
"e": 7360,
"s": 7353,
"text": "Python"
},
{
"code": null,
"e": 7376,
"s": 7360,
"text": "Python Programs"
},
{
"code": null,
"e": 7392,
"s": 7376,
"text": "Write From Home"
}
] |
Infix to Postfix using different Precedence Values for In-Stack and Out-Stack
|
19 Mar, 2022
Conversion of infix to postfix expression can be done elegantly using two precedence function. Each operator is assigned a value (larger value means higher precedence) which depends upon whether the operator is inside or outside the stack. Also the right and left associativity for different operators can be handled by varying it’s values in the two precedence functions. Infix expression example: a+b*c Its corresponding postfix expression: abc*+
Following steps explains how these conversion has done.
Step 1: a + bc* (Here we have two operators: + and * in which * has higher precedence and hence it will be evaluated first).
Step 2: abc*+ (Now we have one operator left which is + so it is evaluated)
To know more about infix and postfix expressions visit the links. Note : In this article, we are assuming that all operators are left to right associative.Examples:
Input: str = “a+b*c-(d/e+f*g*h)” Output: abc*+de/fg*h*+-
Step 1: a+b*c-(de/+f*g*h)
Step 2: a+b*c-(de/+fg* *h)
Step 3: a+b*c-(de/+fg*h*)
Step 4: a+b*c-(de/fg*h*+)
Step 5: a+bc*-de/fg*h*+
Step 6: abc*+-de/fg*h*+
Step 7: abc*+de/fg*h*+-
Input: a+b*c/h Output: abc*h/+
Step 1: a+bc*/h
Step 2: a+bc*h/
Step 3: abc*h/+
Approach:
If the input character is an operand, print it.If the input character is an operator- If stack is empty push it to the stack.If its precedence value is greater than the precedence value of the character on top, push.If its precedence value is lower or equal then pop from stack and print while precedence of top char is more than the precedence value of the input character.If the input character is ‘)’, then pop and print until top is ‘(‘. (Pop ‘(‘ but don’t print it.)If stack becomes empty before encountering ‘(‘, then it’s a invalid expression.Repeat steps 1-4 until input expression is completely read.Pop the remaining elements from stack and print them.
If the input character is an operand, print it.
If the input character is an operator- If stack is empty push it to the stack.If its precedence value is greater than the precedence value of the character on top, push.If its precedence value is lower or equal then pop from stack and print while precedence of top char is more than the precedence value of the input character.
If stack is empty push it to the stack.
If its precedence value is greater than the precedence value of the character on top, push.
If its precedence value is lower or equal then pop from stack and print while precedence of top char is more than the precedence value of the input character.
If the input character is ‘)’, then pop and print until top is ‘(‘. (Pop ‘(‘ but don’t print it.)
If stack becomes empty before encountering ‘(‘, then it’s a invalid expression.
Repeat steps 1-4 until input expression is completely read.
Pop the remaining elements from stack and print them.
The above method handles right associativity of exponentiation operator (here, ^) by assigning it higher precedence value outside stack and lower precedence value inside stack whereas it’s opposite for left associative operators.Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to convert an infix expression to a// postfix expression using two precedence function#include <bits/stdc++.h>using namespace std; // to check if the input character// is an operator or a '('int isOperator(char input){ switch (input) { case '+': return 1; case '-': return 1; case '*': return 1; case '%': return 1; case '/': return 1; case '(': return 1; } return 0;} // to check if the input character is an operandint isOperand(char input){ if (input >= 65 && input <= 90 || input >= 97 && input <= 122) return 1; return 0;} // function to return precedence value// if operator is present in stackint inPrec(char input){ switch (input) { case '+': case '-': return 2; case '*': case '%': case '/': return 4; case '(': return 0; }} // function to return precedence value// if operator is present outside stack.int outPrec(char input){ switch (input) { case '+': case '-': return 1; case '*': case '%': case '/': return 3; case '(': return 100; }} // function to convert infix to postfixvoid inToPost(char* input){ stack<char> s; // while input is not NULL iterate int i = 0; while (input[i] != '\0') { // if character an operand if (isOperand(input[i])) { printf("%c", input[i]); } // if input is an operator, push else if (isOperator(input[i])) { if (s.empty() || outPrec(input[i]) > inPrec(s.top())) s.push(input[i]); else { while (!s.empty() && outPrec(input[i]) < inPrec(s.top())) { printf("%c", s.top()); s.pop(); } s.push(input[i]); } } // condition for opening bracket else if (input[i] == ')') { while (s.top() != '(') { printf("%c", s.top()); s.pop(); // if opening bracket not present if (s.empty()) { printf("Wrong input\n"); exit(1); } } // pop the opening bracket. s.pop(); } i++; } // pop the remaining operators while (!s.empty()) { if (s.top() == '(') { printf("\n Wrong input\n"); exit(1); } printf("%c", s.top()); s.pop(); }} // Driver codeint main(){ char input[] = "a+b*c-(d/e+f*g*h)"; inToPost(input); return 0;}
import static java.lang.System.exit;import java.util.Stack; // Java program to convert an infix expression to a// postfix expression using two precedence functionclass GFG { // to check if the input character // is an operator or a '(' static int isOperator(char input) { switch (input) { case '+': return 1; case '-': return 1; case '*': return 1; case '%': return 1; case '/': return 1; case '(': return 1; } return 0; } // to check if the input character is an operand static int isOperand(char input) { if (input >= 65 && input <= 90 || input >= 97 && input <= 122) { return 1; } return 0; } // function to return precedence value // if operator is present in stack static int inPrec(char input) { switch (input) { case '+': case '-': return 2; case '*': case '%': case '/': return 4; case '(': return 0; } return 0; } // function to return precedence value // if operator is present outside stack. static int outPrec(char input) { switch (input) { case '+': case '-': return 1; case '*': case '%': case '/': return 3; case '(': return 100; } return 0; } // function to convert infix to postfix static void inToPost(char[] input) { Stack<Character> s = new Stack<Character>(); // while input is not NULL iterate int i = 0; while (input.length != i) { // if character an operand if (isOperand(input[i]) == 1) { System.out.printf("%c", input[i]); } // if input is an operator, push else if (isOperator(input[i]) == 1) { if (s.empty() || outPrec(input[i]) > inPrec(s.peek())) { s.push(input[i]); } else { while (!s.empty() && outPrec(input[i]) < inPrec(s.peek())) { System.out.printf("%c", s.peek()); s.pop(); } s.push(input[i]); } } // condition for opening bracket else if (input[i] == ')') { while (s.peek() != '(') { System.out.printf("%c", s.peek()); s.pop(); // if opening bracket not present if (s.empty()) { System.out.printf("Wrong input\n"); exit(1); } } // pop the opening bracket. s.pop(); } i++; } // pop the remaining operators while (!s.empty()) { if (s.peek() == '(') { System.out.printf("\n Wrong input\n"); exit(1); } System.out.printf("%c", s.peek()); s.pop(); } } // Driver code static public void main(String[] args) { char input[] = "a+b*c-(d/e+f*g*h)".toCharArray(); inToPost(input); }} // This code is contributed by Rajput-Ji
# Python3 program to convert an infix# expression to a postfix expression# using two precedence function # To check if the input character# is an operator or a '('def isOperator(input): switch = { '+': 1, '-': 1, '*': 1, '/': 1, '%': 1, '(': 1, } return switch.get(input, False) # To check if the input character is an operanddef isOperand(input): if ((ord(input) >= 65 and ord(input) <= 90) or (ord(input) >= 97 and ord(input) <= 122)): return 1 return 0 # Function to return precedence value# if operator is present in stackdef inPrec(input): switch = { '+': 2, '-': 2, '*': 4, '/': 4, '%': 4, '(': 0, } return switch.get(input, 0) # Function to return precedence value# if operator is present outside stack.def outPrec(input): switch = { '+': 1, '-': 1, '*': 3, '/': 3, '%': 3, '(': 100, } return switch.get(input, 0) # Function to convert infix to postfixdef inToPost(input): i = 0 s = [] # While input is not NULL iterate while (len(input) != i): # If character an operand if (isOperand(input[i]) == 1): print(input[i], end = "") # If input is an operator, push elif (isOperator(input[i]) == 1): if (len(s) == 0 or outPrec(input[i]) > inPrec(s[-1])): s.append(input[i]) else: while(len(s) > 0 and outPrec(input[i]) < inPrec(s[-1])): print(s[-1], end = "") s.pop() s.append(input[i]) # Condition for opening bracket elif(input[i] == ')'): while(s[-1] != '('): print(s[-1], end = "") s.pop() # If opening bracket not present if(len(s) == 0): print('Wrong input') exit(1) # pop the opening bracket. s.pop() i += 1 # pop the remaining operators while(len(s) > 0): if(s[-1] == '('): print('Wrong input') exit(1) print(s[-1], end = "") s.pop() # Driver codeinput = "a+b*c-(d/e+f*g*h)" inToPost(input) # This code is contributed by dheeraj_2801
// C# program to convert an infix expression to a// postfix expression using two precedence functionusing System.Collections.Generic;using System;public class GFG { // to check if the input character // is an operator or a '(' static int isOperator(char input) { switch (input) { case '+': return 1; case '-': return 1; case '*': return 1; case '%': return 1; case '/': return 1; case '(': return 1; } return 0; } // to check if the input character is an operand static int isOperand(char input) { if (input >= 65 && input <= 90 || input >= 97 && input <= 122) { return 1; } return 0; } // function to return precedence value // if operator is present in stack static int inPrec(char input) { switch (input) { case '+': case '-': return 2; case '*': case '%': case '/': return 4; case '(': return 0; } return 0; } // function to return precedence value // if operator is present outside stack. static int outPrec(char input) { switch (input) { case '+': case '-': return 1; case '*': case '%': case '/': return 3; case '(': return 100; } return 0; } // function to convert infix to postfix static void inToPost(char[] input) { Stack<char> s = new Stack<char>(); // while input is not NULL iterate int i = 0; while (input.Length != i) { // if character an operand if (isOperand(input[i]) == 1) { Console.Write(input[i]); } // if input is an operator, push else if (isOperator(input[i]) == 1) { if (s.Count == 0 || outPrec(input[i]) > inPrec(s.Peek())) { s.Push(input[i]); } else { while (s.Count != 0 && outPrec(input[i]) < inPrec(s.Peek())) { Console.Write(s.Peek()); s.Pop(); } s.Push(input[i]); } } // condition for opening bracket else if (input[i] == ')') { while (s.Peek() != '(') { Console.Write(s.Peek()); s.Pop(); // if opening bracket not present if (s.Count == 0) { Console.Write("Wrong input\n"); return; } } // pop the opening bracket. s.Pop(); } i++; } // pop the remaining operators while (s.Count != 0) { if (s.Peek() == '(') { Console.Write("\n Wrong input\n"); return; } Console.Write(s.Peek()); s.Pop(); } } // Driver code static public void Main() { char[] input = "a+b*c-(d/e+f*g*h)".ToCharArray(); inToPost(input); }} // This code is contributed by Rajput-Ji
<script> // Javascript program to convert an infix expression to a // postfix expression using two precedence function // to check if the input character // is an operator or a '(' function isOperator(input) { switch (input) { case '+': return 1; case '-': return 1; case '*': return 1; case '%': return 1; case '/': return 1; case '(': return 1; } return 0; } // to check if the input character is an operand function isOperand(input) { if (input.charCodeAt() >= 65 && input.charCodeAt() <= 90 || input.charCodeAt() >= 97 && input.charCodeAt() <= 122) { return 1; } return 0; } // function to return precedence value // if operator is present in stack function inPrec(input) { switch (input) { case '+': case '-': return 2; case '*': case '%': case '/': return 4; case '(': return 0; } return 0; } // function to return precedence value // if operator is present outside stack. function outPrec(input) { switch (input) { case '+': case '-': return 1; case '*': case '%': case '/': return 3; case '(': return 100; } return 0; } // function to convert infix to postfix function inToPost(input) { let s = []; // while input is not NULL iterate let i = 0; while (input.length != i) { // if character an operand if (isOperand(input[i]) == 1) { document.write(input[i]); } // if input is an operator, push else if (isOperator(input[i]) == 1) { if (s.length == 0 || outPrec(input[i]) > inPrec(s[s.length - 1])) { s.push(input[i]); } else { while (s.length != 0 && outPrec(input[i]) < inPrec(s[s.length - 1])) { document.write(s[s.length - 1]); s.pop(); } s.push(input[i]); } } // condition for opening bracket else if (input[i] == ')') { while (s[s.length - 1] != '(') { document.write(s[s.length - 1]); s.pop(); // if opening bracket not present if (s.length == 0) { document.write("Wrong input" + "</br>"); return; } } // pop the opening bracket. s.pop(); } i++; } // pop the remaining operators while (s.length != 0) { if (s[s.length - 1] == '(') { document.write("</br>" + " Wrong input" + "</br>"); return; } document.write(s[s.length - 1]); s.pop(); } } let input = "a+b*c-(d/e+f*g*h)".split(''); inToPost(input); // This code is contributed by rameshtravel07.</script>
abc*+de/fg*h*+-
How to handle operators with right to left associativity? For example, power operator ^. The postfix of “a^b^c” would be “abc^^”, but the above solution would print postfix as “ab^c^” which is wrong. In the above implementation, when we see an operator with equal precedence, we treat it same as lower. We need to consider the same if the two operators have left to associativity. But in case of right to left associativity, we need to treat it as higher precedence and push it to the stack.Approach:
If the input character is an operand, print it.If the input character is an operator- If stack is empty push it to the stack.If ((its precedence value is greater than the precedence value of the character on top) OR (precedence is same AND associativity is right to left)), push.If ((its precedence value is lower) OR (precedence is same AND associativity is left to right)), then pop from stack and print while precedence of top char is more than the precedence value of the input character.If the input character is ‘)’, then pop and print until top is ‘(‘. (Pop ‘(‘ but don’t print it.)If stack becomes empty before encountering ‘(‘, then it’s a invalid expression.Repeat steps 1-4 until input expression is completely read.Pop the remaining elements from stack and print them.
If the input character is an operand, print it.
If the input character is an operator- If stack is empty push it to the stack.If ((its precedence value is greater than the precedence value of the character on top) OR (precedence is same AND associativity is right to left)), push.If ((its precedence value is lower) OR (precedence is same AND associativity is left to right)), then pop from stack and print while precedence of top char is more than the precedence value of the input character.
If stack is empty push it to the stack.
If ((its precedence value is greater than the precedence value of the character on top) OR (precedence is same AND associativity is right to left)), push.
If ((its precedence value is lower) OR (precedence is same AND associativity is left to right)), then pop from stack and print while precedence of top char is more than the precedence value of the input character.
If the input character is ‘)’, then pop and print until top is ‘(‘. (Pop ‘(‘ but don’t print it.)
If stack becomes empty before encountering ‘(‘, then it’s a invalid expression.
Repeat steps 1-4 until input expression is completely read.
Pop the remaining elements from stack and print them.
Rajput-Ji
aditya_kulkarni
dheeraj_2801
rameshtravel07
toketandpatel
expression-evaluation
Technical Scripter 2018
Stack
Technical Scripter
Stack
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n19 Mar, 2022"
},
{
"code": null,
"e": 501,
"s": 52,
"text": "Conversion of infix to postfix expression can be done elegantly using two precedence function. Each operator is assigned a value (larger value means higher precedence) which depends upon whether the operator is inside or outside the stack. Also the right and left associativity for different operators can be handled by varying it’s values in the two precedence functions. Infix expression example: a+b*c Its corresponding postfix expression: abc*+"
},
{
"code": null,
"e": 557,
"s": 501,
"text": "Following steps explains how these conversion has done."
},
{
"code": null,
"e": 682,
"s": 557,
"text": "Step 1: a + bc* (Here we have two operators: + and * in which * has higher precedence and hence it will be evaluated first)."
},
{
"code": null,
"e": 758,
"s": 682,
"text": "Step 2: abc*+ (Now we have one operator left which is + so it is evaluated)"
},
{
"code": null,
"e": 925,
"s": 758,
"text": " To know more about infix and postfix expressions visit the links. Note : In this article, we are assuming that all operators are left to right associative.Examples:"
},
{
"code": null,
"e": 982,
"s": 925,
"text": "Input: str = “a+b*c-(d/e+f*g*h)” Output: abc*+de/fg*h*+-"
},
{
"code": null,
"e": 1008,
"s": 982,
"text": "Step 1: a+b*c-(de/+f*g*h)"
},
{
"code": null,
"e": 1035,
"s": 1008,
"text": "Step 2: a+b*c-(de/+fg* *h)"
},
{
"code": null,
"e": 1061,
"s": 1035,
"text": "Step 3: a+b*c-(de/+fg*h*)"
},
{
"code": null,
"e": 1087,
"s": 1061,
"text": "Step 4: a+b*c-(de/fg*h*+)"
},
{
"code": null,
"e": 1111,
"s": 1087,
"text": "Step 5: a+bc*-de/fg*h*+"
},
{
"code": null,
"e": 1135,
"s": 1111,
"text": "Step 6: abc*+-de/fg*h*+"
},
{
"code": null,
"e": 1159,
"s": 1135,
"text": "Step 7: abc*+de/fg*h*+-"
},
{
"code": null,
"e": 1190,
"s": 1159,
"text": "Input: a+b*c/h Output: abc*h/+"
},
{
"code": null,
"e": 1206,
"s": 1190,
"text": "Step 1: a+bc*/h"
},
{
"code": null,
"e": 1222,
"s": 1206,
"text": "Step 2: a+bc*h/"
},
{
"code": null,
"e": 1238,
"s": 1222,
"text": "Step 3: abc*h/+"
},
{
"code": null,
"e": 1248,
"s": 1238,
"text": "Approach:"
},
{
"code": null,
"e": 1911,
"s": 1248,
"text": "If the input character is an operand, print it.If the input character is an operator- If stack is empty push it to the stack.If its precedence value is greater than the precedence value of the character on top, push.If its precedence value is lower or equal then pop from stack and print while precedence of top char is more than the precedence value of the input character.If the input character is ‘)’, then pop and print until top is ‘(‘. (Pop ‘(‘ but don’t print it.)If stack becomes empty before encountering ‘(‘, then it’s a invalid expression.Repeat steps 1-4 until input expression is completely read.Pop the remaining elements from stack and print them."
},
{
"code": null,
"e": 1959,
"s": 1911,
"text": "If the input character is an operand, print it."
},
{
"code": null,
"e": 2287,
"s": 1959,
"text": "If the input character is an operator- If stack is empty push it to the stack.If its precedence value is greater than the precedence value of the character on top, push.If its precedence value is lower or equal then pop from stack and print while precedence of top char is more than the precedence value of the input character."
},
{
"code": null,
"e": 2327,
"s": 2287,
"text": "If stack is empty push it to the stack."
},
{
"code": null,
"e": 2419,
"s": 2327,
"text": "If its precedence value is greater than the precedence value of the character on top, push."
},
{
"code": null,
"e": 2578,
"s": 2419,
"text": "If its precedence value is lower or equal then pop from stack and print while precedence of top char is more than the precedence value of the input character."
},
{
"code": null,
"e": 2676,
"s": 2578,
"text": "If the input character is ‘)’, then pop and print until top is ‘(‘. (Pop ‘(‘ but don’t print it.)"
},
{
"code": null,
"e": 2756,
"s": 2676,
"text": "If stack becomes empty before encountering ‘(‘, then it’s a invalid expression."
},
{
"code": null,
"e": 2816,
"s": 2756,
"text": "Repeat steps 1-4 until input expression is completely read."
},
{
"code": null,
"e": 2870,
"s": 2816,
"text": "Pop the remaining elements from stack and print them."
},
{
"code": null,
"e": 3150,
"s": 2870,
"text": "The above method handles right associativity of exponentiation operator (here, ^) by assigning it higher precedence value outside stack and lower precedence value inside stack whereas it’s opposite for left associative operators.Below is the implementation of the above approach:"
},
{
"code": null,
"e": 3154,
"s": 3150,
"text": "C++"
},
{
"code": null,
"e": 3159,
"s": 3154,
"text": "Java"
},
{
"code": null,
"e": 3167,
"s": 3159,
"text": "Python3"
},
{
"code": null,
"e": 3170,
"s": 3167,
"text": "C#"
},
{
"code": null,
"e": 3181,
"s": 3170,
"text": "Javascript"
},
{
"code": "// C++ program to convert an infix expression to a// postfix expression using two precedence function#include <bits/stdc++.h>using namespace std; // to check if the input character// is an operator or a '('int isOperator(char input){ switch (input) { case '+': return 1; case '-': return 1; case '*': return 1; case '%': return 1; case '/': return 1; case '(': return 1; } return 0;} // to check if the input character is an operandint isOperand(char input){ if (input >= 65 && input <= 90 || input >= 97 && input <= 122) return 1; return 0;} // function to return precedence value// if operator is present in stackint inPrec(char input){ switch (input) { case '+': case '-': return 2; case '*': case '%': case '/': return 4; case '(': return 0; }} // function to return precedence value// if operator is present outside stack.int outPrec(char input){ switch (input) { case '+': case '-': return 1; case '*': case '%': case '/': return 3; case '(': return 100; }} // function to convert infix to postfixvoid inToPost(char* input){ stack<char> s; // while input is not NULL iterate int i = 0; while (input[i] != '\\0') { // if character an operand if (isOperand(input[i])) { printf(\"%c\", input[i]); } // if input is an operator, push else if (isOperator(input[i])) { if (s.empty() || outPrec(input[i]) > inPrec(s.top())) s.push(input[i]); else { while (!s.empty() && outPrec(input[i]) < inPrec(s.top())) { printf(\"%c\", s.top()); s.pop(); } s.push(input[i]); } } // condition for opening bracket else if (input[i] == ')') { while (s.top() != '(') { printf(\"%c\", s.top()); s.pop(); // if opening bracket not present if (s.empty()) { printf(\"Wrong input\\n\"); exit(1); } } // pop the opening bracket. s.pop(); } i++; } // pop the remaining operators while (!s.empty()) { if (s.top() == '(') { printf(\"\\n Wrong input\\n\"); exit(1); } printf(\"%c\", s.top()); s.pop(); }} // Driver codeint main(){ char input[] = \"a+b*c-(d/e+f*g*h)\"; inToPost(input); return 0;}",
"e": 5804,
"s": 3181,
"text": null
},
{
"code": "import static java.lang.System.exit;import java.util.Stack; // Java program to convert an infix expression to a// postfix expression using two precedence functionclass GFG { // to check if the input character // is an operator or a '(' static int isOperator(char input) { switch (input) { case '+': return 1; case '-': return 1; case '*': return 1; case '%': return 1; case '/': return 1; case '(': return 1; } return 0; } // to check if the input character is an operand static int isOperand(char input) { if (input >= 65 && input <= 90 || input >= 97 && input <= 122) { return 1; } return 0; } // function to return precedence value // if operator is present in stack static int inPrec(char input) { switch (input) { case '+': case '-': return 2; case '*': case '%': case '/': return 4; case '(': return 0; } return 0; } // function to return precedence value // if operator is present outside stack. static int outPrec(char input) { switch (input) { case '+': case '-': return 1; case '*': case '%': case '/': return 3; case '(': return 100; } return 0; } // function to convert infix to postfix static void inToPost(char[] input) { Stack<Character> s = new Stack<Character>(); // while input is not NULL iterate int i = 0; while (input.length != i) { // if character an operand if (isOperand(input[i]) == 1) { System.out.printf(\"%c\", input[i]); } // if input is an operator, push else if (isOperator(input[i]) == 1) { if (s.empty() || outPrec(input[i]) > inPrec(s.peek())) { s.push(input[i]); } else { while (!s.empty() && outPrec(input[i]) < inPrec(s.peek())) { System.out.printf(\"%c\", s.peek()); s.pop(); } s.push(input[i]); } } // condition for opening bracket else if (input[i] == ')') { while (s.peek() != '(') { System.out.printf(\"%c\", s.peek()); s.pop(); // if opening bracket not present if (s.empty()) { System.out.printf(\"Wrong input\\n\"); exit(1); } } // pop the opening bracket. s.pop(); } i++; } // pop the remaining operators while (!s.empty()) { if (s.peek() == '(') { System.out.printf(\"\\n Wrong input\\n\"); exit(1); } System.out.printf(\"%c\", s.peek()); s.pop(); } } // Driver code static public void main(String[] args) { char input[] = \"a+b*c-(d/e+f*g*h)\".toCharArray(); inToPost(input); }} // This code is contributed by Rajput-Ji",
"e": 9187,
"s": 5804,
"text": null
},
{
"code": "# Python3 program to convert an infix# expression to a postfix expression# using two precedence function # To check if the input character# is an operator or a '('def isOperator(input): switch = { '+': 1, '-': 1, '*': 1, '/': 1, '%': 1, '(': 1, } return switch.get(input, False) # To check if the input character is an operanddef isOperand(input): if ((ord(input) >= 65 and ord(input) <= 90) or (ord(input) >= 97 and ord(input) <= 122)): return 1 return 0 # Function to return precedence value# if operator is present in stackdef inPrec(input): switch = { '+': 2, '-': 2, '*': 4, '/': 4, '%': 4, '(': 0, } return switch.get(input, 0) # Function to return precedence value# if operator is present outside stack.def outPrec(input): switch = { '+': 1, '-': 1, '*': 3, '/': 3, '%': 3, '(': 100, } return switch.get(input, 0) # Function to convert infix to postfixdef inToPost(input): i = 0 s = [] # While input is not NULL iterate while (len(input) != i): # If character an operand if (isOperand(input[i]) == 1): print(input[i], end = \"\") # If input is an operator, push elif (isOperator(input[i]) == 1): if (len(s) == 0 or outPrec(input[i]) > inPrec(s[-1])): s.append(input[i]) else: while(len(s) > 0 and outPrec(input[i]) < inPrec(s[-1])): print(s[-1], end = \"\") s.pop() s.append(input[i]) # Condition for opening bracket elif(input[i] == ')'): while(s[-1] != '('): print(s[-1], end = \"\") s.pop() # If opening bracket not present if(len(s) == 0): print('Wrong input') exit(1) # pop the opening bracket. s.pop() i += 1 # pop the remaining operators while(len(s) > 0): if(s[-1] == '('): print('Wrong input') exit(1) print(s[-1], end = \"\") s.pop() # Driver codeinput = \"a+b*c-(d/e+f*g*h)\" inToPost(input) # This code is contributed by dheeraj_2801",
"e": 11657,
"s": 9187,
"text": null
},
{
"code": "// C# program to convert an infix expression to a// postfix expression using two precedence functionusing System.Collections.Generic;using System;public class GFG { // to check if the input character // is an operator or a '(' static int isOperator(char input) { switch (input) { case '+': return 1; case '-': return 1; case '*': return 1; case '%': return 1; case '/': return 1; case '(': return 1; } return 0; } // to check if the input character is an operand static int isOperand(char input) { if (input >= 65 && input <= 90 || input >= 97 && input <= 122) { return 1; } return 0; } // function to return precedence value // if operator is present in stack static int inPrec(char input) { switch (input) { case '+': case '-': return 2; case '*': case '%': case '/': return 4; case '(': return 0; } return 0; } // function to return precedence value // if operator is present outside stack. static int outPrec(char input) { switch (input) { case '+': case '-': return 1; case '*': case '%': case '/': return 3; case '(': return 100; } return 0; } // function to convert infix to postfix static void inToPost(char[] input) { Stack<char> s = new Stack<char>(); // while input is not NULL iterate int i = 0; while (input.Length != i) { // if character an operand if (isOperand(input[i]) == 1) { Console.Write(input[i]); } // if input is an operator, push else if (isOperator(input[i]) == 1) { if (s.Count == 0 || outPrec(input[i]) > inPrec(s.Peek())) { s.Push(input[i]); } else { while (s.Count != 0 && outPrec(input[i]) < inPrec(s.Peek())) { Console.Write(s.Peek()); s.Pop(); } s.Push(input[i]); } } // condition for opening bracket else if (input[i] == ')') { while (s.Peek() != '(') { Console.Write(s.Peek()); s.Pop(); // if opening bracket not present if (s.Count == 0) { Console.Write(\"Wrong input\\n\"); return; } } // pop the opening bracket. s.Pop(); } i++; } // pop the remaining operators while (s.Count != 0) { if (s.Peek() == '(') { Console.Write(\"\\n Wrong input\\n\"); return; } Console.Write(s.Peek()); s.Pop(); } } // Driver code static public void Main() { char[] input = \"a+b*c-(d/e+f*g*h)\".ToCharArray(); inToPost(input); }} // This code is contributed by Rajput-Ji",
"e": 14980,
"s": 11657,
"text": null
},
{
"code": "<script> // Javascript program to convert an infix expression to a // postfix expression using two precedence function // to check if the input character // is an operator or a '(' function isOperator(input) { switch (input) { case '+': return 1; case '-': return 1; case '*': return 1; case '%': return 1; case '/': return 1; case '(': return 1; } return 0; } // to check if the input character is an operand function isOperand(input) { if (input.charCodeAt() >= 65 && input.charCodeAt() <= 90 || input.charCodeAt() >= 97 && input.charCodeAt() <= 122) { return 1; } return 0; } // function to return precedence value // if operator is present in stack function inPrec(input) { switch (input) { case '+': case '-': return 2; case '*': case '%': case '/': return 4; case '(': return 0; } return 0; } // function to return precedence value // if operator is present outside stack. function outPrec(input) { switch (input) { case '+': case '-': return 1; case '*': case '%': case '/': return 3; case '(': return 100; } return 0; } // function to convert infix to postfix function inToPost(input) { let s = []; // while input is not NULL iterate let i = 0; while (input.length != i) { // if character an operand if (isOperand(input[i]) == 1) { document.write(input[i]); } // if input is an operator, push else if (isOperator(input[i]) == 1) { if (s.length == 0 || outPrec(input[i]) > inPrec(s[s.length - 1])) { s.push(input[i]); } else { while (s.length != 0 && outPrec(input[i]) < inPrec(s[s.length - 1])) { document.write(s[s.length - 1]); s.pop(); } s.push(input[i]); } } // condition for opening bracket else if (input[i] == ')') { while (s[s.length - 1] != '(') { document.write(s[s.length - 1]); s.pop(); // if opening bracket not present if (s.length == 0) { document.write(\"Wrong input\" + \"</br>\"); return; } } // pop the opening bracket. s.pop(); } i++; } // pop the remaining operators while (s.length != 0) { if (s[s.length - 1] == '(') { document.write(\"</br>\" + \" Wrong input\" + \"</br>\"); return; } document.write(s[s.length - 1]); s.pop(); } } let input = \"a+b*c-(d/e+f*g*h)\".split(''); inToPost(input); // This code is contributed by rameshtravel07.</script>",
"e": 18377,
"s": 14980,
"text": null
},
{
"code": null,
"e": 18393,
"s": 18377,
"text": "abc*+de/fg*h*+-"
},
{
"code": null,
"e": 18896,
"s": 18395,
"text": "How to handle operators with right to left associativity? For example, power operator ^. The postfix of “a^b^c” would be “abc^^”, but the above solution would print postfix as “ab^c^” which is wrong. In the above implementation, when we see an operator with equal precedence, we treat it same as lower. We need to consider the same if the two operators have left to associativity. But in case of right to left associativity, we need to treat it as higher precedence and push it to the stack.Approach:"
},
{
"code": null,
"e": 19677,
"s": 18896,
"text": "If the input character is an operand, print it.If the input character is an operator- If stack is empty push it to the stack.If ((its precedence value is greater than the precedence value of the character on top) OR (precedence is same AND associativity is right to left)), push.If ((its precedence value is lower) OR (precedence is same AND associativity is left to right)), then pop from stack and print while precedence of top char is more than the precedence value of the input character.If the input character is ‘)’, then pop and print until top is ‘(‘. (Pop ‘(‘ but don’t print it.)If stack becomes empty before encountering ‘(‘, then it’s a invalid expression.Repeat steps 1-4 until input expression is completely read.Pop the remaining elements from stack and print them."
},
{
"code": null,
"e": 19725,
"s": 19677,
"text": "If the input character is an operand, print it."
},
{
"code": null,
"e": 20171,
"s": 19725,
"text": "If the input character is an operator- If stack is empty push it to the stack.If ((its precedence value is greater than the precedence value of the character on top) OR (precedence is same AND associativity is right to left)), push.If ((its precedence value is lower) OR (precedence is same AND associativity is left to right)), then pop from stack and print while precedence of top char is more than the precedence value of the input character."
},
{
"code": null,
"e": 20211,
"s": 20171,
"text": "If stack is empty push it to the stack."
},
{
"code": null,
"e": 20366,
"s": 20211,
"text": "If ((its precedence value is greater than the precedence value of the character on top) OR (precedence is same AND associativity is right to left)), push."
},
{
"code": null,
"e": 20580,
"s": 20366,
"text": "If ((its precedence value is lower) OR (precedence is same AND associativity is left to right)), then pop from stack and print while precedence of top char is more than the precedence value of the input character."
},
{
"code": null,
"e": 20678,
"s": 20580,
"text": "If the input character is ‘)’, then pop and print until top is ‘(‘. (Pop ‘(‘ but don’t print it.)"
},
{
"code": null,
"e": 20758,
"s": 20678,
"text": "If stack becomes empty before encountering ‘(‘, then it’s a invalid expression."
},
{
"code": null,
"e": 20818,
"s": 20758,
"text": "Repeat steps 1-4 until input expression is completely read."
},
{
"code": null,
"e": 20872,
"s": 20818,
"text": "Pop the remaining elements from stack and print them."
},
{
"code": null,
"e": 20882,
"s": 20872,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 20898,
"s": 20882,
"text": "aditya_kulkarni"
},
{
"code": null,
"e": 20911,
"s": 20898,
"text": "dheeraj_2801"
},
{
"code": null,
"e": 20926,
"s": 20911,
"text": "rameshtravel07"
},
{
"code": null,
"e": 20940,
"s": 20926,
"text": "toketandpatel"
},
{
"code": null,
"e": 20962,
"s": 20940,
"text": "expression-evaluation"
},
{
"code": null,
"e": 20986,
"s": 20962,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 20992,
"s": 20986,
"text": "Stack"
},
{
"code": null,
"e": 21011,
"s": 20992,
"text": "Technical Scripter"
},
{
"code": null,
"e": 21017,
"s": 21011,
"text": "Stack"
}
] |
GWT - Label Widget
|
The Label can contains only arbitrary text and it can not be interpreted as HTML. This widget uses a <div> element, causing it to be displayed with block layout.
Following is the declaration for com.google.gwt.user.client.ui.Label class −
public class Label
extends Widget
implements HasHorizontalAlignment, HasText, HasWordWrap,
HasDirection, HasClickHandlers, SourcesClickEvents,
SourcesMouseEvents, HasAllMouseHandlers
Following default CSS Style rule will be applied to all the labels. You can override it as per your requirements.
.gwt-Label { }
Label()
Creates an empty label.
protected Label(Element element)
This constructor may be used by subclasses to explicitly use an existing element.
Label(java.lang.String text)
Creates a label with the specified text.
Label(java.lang.String text, boolean wordWrap)
Creates a label with the specified text.
void addClickListener(ClickListener listener)
Adds a listener interface to receive click events.
void addMouseListener(MouseListener listener)
Adds a listener interface to receive mouse events.
void addMouseWheelListener(MouseWheelListener listener)
Gets this widget's parent panel.
HasDirection.Direction getDirection()
Gets the directionality of the widget.
HasHorizontalAlignment. HorizontalAlignmentConstant getHorizontalAlignment()
Gets the horizontal alignment.
java.lang.String getText()
Gets this object's text.
boolean getWordWrap()
Gets whether word-wrapping is enabled.
void onBrowserEvent(Event event)
Removes a previously added listener interface.
void removeClickListener(ClickListener listener)
This method is called immediately before a widget will be detached from the browser's document.
void removeMouseListener(MouseListener listener)
Removes a previously added listener interface.
void removeMouseWheelListener(MouseWheelListener listener)
Removes a previously added listener interface.
void setDirection(HasDirection.Direction direction)
Sets the directionality for a widget.
void setHorizontalAlignment(HasHorizontalAlignment. HorizontalAlignmentConstant align)
Sets the horizontal alignment.
void setText(java.lang.String text)
Sets this object's text.
void setWordWrap(boolean wrap)
Sets whether word-wrapping is enabled.
static Label wrap(Element element)
Creates a Label widget that wraps an existing <div> or <span> element.
This class inherits methods from the following classes −
com.google.gwt.user.client.ui.UIObject
com.google.gwt.user.client.ui.UIObject
com.google.gwt.user.client.ui.Widget
com.google.gwt.user.client.ui.Widget
This example will take you through simple steps to show usage of a Label Widget in GWT. Follow the following steps to update the GWT application we created in GWT - Create Application chapter −
Following is the content of the modified module descriptor src/com.tutorialspoint/HelloWorld.gwt.xml.
<?xml version = "1.0" encoding = "UTF-8"?>
<module rename-to = 'helloworld'>
<!-- Inherit the core Web Toolkit stuff. -->
<inherits name = 'com.google.gwt.user.User'/>
<!-- Inherit the default GWT style sheet. -->
<inherits name = 'com.google.gwt.user.theme.clean.Clean'/>
<!-- Specify the app entry point class. -->
<entry-point class = 'com.tutorialspoint.client.HelloWorld'/>
<!-- Specify the paths for translatable code -->
<source path = 'client'/>
<source path = 'shared'/>
</module>
Following is the content of the modified Style Sheet file war/HelloWorld.css.
body {
text-align: center;
font-family: verdana, sans-serif;
}
h1 {
font-size: 2em;
font-weight: bold;
color: #777777;
margin: 40px 0px 70px;
text-align: center;
}
.gwt-Label{
font-size: 150%;
font-weight: bold;
color:red;
padding:5px;
margin:5px;
}
.gwt-Green-Border{
border:1px solid green;
}
.gwt-Blue-Border{
border:1px solid blue;
}
Following is the content of the modified HTML host file war/HelloWorld.html to accomodate two buttons.
<html>
<head>
<title>Hello World</title>
<link rel = "stylesheet" href = "HelloWorld.css"/>
<script language = "javascript" src = "helloworld/helloworld.nocache.js">
</script>
</head>
<body>
<h1>Label Widget Demonstration</h1>
<div id = "gwtContainer"></div>
</body>
</html>
Let us have following content of Java file src/com.tutorialspoint/HelloWorld.java which will demonstrate use of Label widget.
package com.tutorialspoint.client;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.VerticalPanel;
public class HelloWorld implements EntryPoint {
public void onModuleLoad() {
// create two Labels
Label label1 = new Label("This is first GWT Label");
Label label2 = new Label("This is second GWT Label");
// use UIObject methods to set label properties.
label1.setTitle("Title for first Lable");
label1.addStyleName("gwt-Green-Border");
label2.setTitle("Title for second Lable");
label2.addStyleName("gwt-Blue-Border");
// add labels to the root panel.
VerticalPanel panel = new VerticalPanel();
panel.add(label1);
panel.add(label2);
RootPanel.get("gwtContainer").add(panel);
}
}
Once you are ready with all the changes done, let us compile and run the application in development mode as we did in GWT - Create Application chapter. If everything is fine with your application, this will produce following result −
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2185,
"s": 2023,
"text": "The Label can contains only arbitrary text and it can not be interpreted as HTML. This widget uses a <div> element, causing it to be displayed with block layout."
},
{
"code": null,
"e": 2262,
"s": 2185,
"text": "Following is the declaration for com.google.gwt.user.client.ui.Label class −"
},
{
"code": null,
"e": 2479,
"s": 2262,
"text": "public class Label \n extends Widget \n implements HasHorizontalAlignment, HasText, HasWordWrap, \n HasDirection, HasClickHandlers, SourcesClickEvents, \n SourcesMouseEvents, HasAllMouseHandlers"
},
{
"code": null,
"e": 2593,
"s": 2479,
"text": "Following default CSS Style rule will be applied to all the labels. You can override it as per your requirements."
},
{
"code": null,
"e": 2608,
"s": 2593,
"text": ".gwt-Label { }"
},
{
"code": null,
"e": 2616,
"s": 2608,
"text": "Label()"
},
{
"code": null,
"e": 2640,
"s": 2616,
"text": "Creates an empty label."
},
{
"code": null,
"e": 2673,
"s": 2640,
"text": "protected Label(Element element)"
},
{
"code": null,
"e": 2755,
"s": 2673,
"text": "This constructor may be used by subclasses to explicitly use an existing element."
},
{
"code": null,
"e": 2784,
"s": 2755,
"text": "Label(java.lang.String text)"
},
{
"code": null,
"e": 2825,
"s": 2784,
"text": "Creates a label with the specified text."
},
{
"code": null,
"e": 2872,
"s": 2825,
"text": "Label(java.lang.String text, boolean wordWrap)"
},
{
"code": null,
"e": 2913,
"s": 2872,
"text": "Creates a label with the specified text."
},
{
"code": null,
"e": 2959,
"s": 2913,
"text": "void addClickListener(ClickListener listener)"
},
{
"code": null,
"e": 3010,
"s": 2959,
"text": "Adds a listener interface to receive click events."
},
{
"code": null,
"e": 3056,
"s": 3010,
"text": "void addMouseListener(MouseListener listener)"
},
{
"code": null,
"e": 3107,
"s": 3056,
"text": "Adds a listener interface to receive mouse events."
},
{
"code": null,
"e": 3163,
"s": 3107,
"text": "void addMouseWheelListener(MouseWheelListener listener)"
},
{
"code": null,
"e": 3196,
"s": 3163,
"text": "Gets this widget's parent panel."
},
{
"code": null,
"e": 3234,
"s": 3196,
"text": "HasDirection.Direction\tgetDirection()"
},
{
"code": null,
"e": 3273,
"s": 3234,
"text": "Gets the directionality of the widget."
},
{
"code": null,
"e": 3350,
"s": 3273,
"text": "HasHorizontalAlignment. HorizontalAlignmentConstant getHorizontalAlignment()"
},
{
"code": null,
"e": 3381,
"s": 3350,
"text": "Gets the horizontal alignment."
},
{
"code": null,
"e": 3408,
"s": 3381,
"text": "java.lang.String getText()"
},
{
"code": null,
"e": 3433,
"s": 3408,
"text": "Gets this object's text."
},
{
"code": null,
"e": 3455,
"s": 3433,
"text": "boolean getWordWrap()"
},
{
"code": null,
"e": 3494,
"s": 3455,
"text": "Gets whether word-wrapping is enabled."
},
{
"code": null,
"e": 3527,
"s": 3494,
"text": "void onBrowserEvent(Event event)"
},
{
"code": null,
"e": 3575,
"s": 3527,
"text": " Removes a previously added listener interface."
},
{
"code": null,
"e": 3624,
"s": 3575,
"text": "void removeClickListener(ClickListener listener)"
},
{
"code": null,
"e": 3720,
"s": 3624,
"text": "This method is called immediately before a widget will be detached from the browser's document."
},
{
"code": null,
"e": 3769,
"s": 3720,
"text": "void removeMouseListener(MouseListener listener)"
},
{
"code": null,
"e": 3816,
"s": 3769,
"text": "Removes a previously added listener interface."
},
{
"code": null,
"e": 3875,
"s": 3816,
"text": "void removeMouseWheelListener(MouseWheelListener listener)"
},
{
"code": null,
"e": 3922,
"s": 3875,
"text": "Removes a previously added listener interface."
},
{
"code": null,
"e": 3974,
"s": 3922,
"text": "void setDirection(HasDirection.Direction direction)"
},
{
"code": null,
"e": 4012,
"s": 3974,
"text": "Sets the directionality for a widget."
},
{
"code": null,
"e": 4099,
"s": 4012,
"text": "void setHorizontalAlignment(HasHorizontalAlignment. HorizontalAlignmentConstant align)"
},
{
"code": null,
"e": 4131,
"s": 4099,
"text": " Sets the horizontal alignment."
},
{
"code": null,
"e": 4167,
"s": 4131,
"text": "void setText(java.lang.String text)"
},
{
"code": null,
"e": 4192,
"s": 4167,
"text": "Sets this object's text."
},
{
"code": null,
"e": 4223,
"s": 4192,
"text": "void setWordWrap(boolean wrap)"
},
{
"code": null,
"e": 4262,
"s": 4223,
"text": "Sets whether word-wrapping is enabled."
},
{
"code": null,
"e": 4297,
"s": 4262,
"text": "static Label wrap(Element element)"
},
{
"code": null,
"e": 4368,
"s": 4297,
"text": "Creates a Label widget that wraps an existing <div> or <span> element."
},
{
"code": null,
"e": 4425,
"s": 4368,
"text": "This class inherits methods from the following classes −"
},
{
"code": null,
"e": 4464,
"s": 4425,
"text": "com.google.gwt.user.client.ui.UIObject"
},
{
"code": null,
"e": 4503,
"s": 4464,
"text": "com.google.gwt.user.client.ui.UIObject"
},
{
"code": null,
"e": 4540,
"s": 4503,
"text": "com.google.gwt.user.client.ui.Widget"
},
{
"code": null,
"e": 4577,
"s": 4540,
"text": "com.google.gwt.user.client.ui.Widget"
},
{
"code": null,
"e": 4772,
"s": 4577,
"text": "This example will take you through simple steps to show usage of a Label Widget in GWT. Follow the following steps to update the GWT application we created in GWT - Create Application chapter −"
},
{
"code": null,
"e": 4874,
"s": 4772,
"text": "Following is the content of the modified module descriptor src/com.tutorialspoint/HelloWorld.gwt.xml."
},
{
"code": null,
"e": 5483,
"s": 4874,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<module rename-to = 'helloworld'>\n <!-- Inherit the core Web Toolkit stuff. -->\n <inherits name = 'com.google.gwt.user.User'/>\n\n <!-- Inherit the default GWT style sheet. -->\n <inherits name = 'com.google.gwt.user.theme.clean.Clean'/>\n\n <!-- Specify the app entry point class. -->\n <entry-point class = 'com.tutorialspoint.client.HelloWorld'/>\n\n <!-- Specify the paths for translatable code -->\n <source path = 'client'/>\n <source path = 'shared'/>\n\n</module>"
},
{
"code": null,
"e": 5561,
"s": 5483,
"text": "Following is the content of the modified Style Sheet file war/HelloWorld.css."
},
{
"code": null,
"e": 5949,
"s": 5561,
"text": "body {\n text-align: center;\n font-family: verdana, sans-serif;\n}\n\nh1 {\n font-size: 2em;\n font-weight: bold;\n color: #777777;\n margin: 40px 0px 70px;\n text-align: center;\n}\n\n.gwt-Label{ \n font-size: 150%; \n font-weight: bold;\n color:red;\n padding:5px;\n margin:5px;\n}\n\n.gwt-Green-Border{ \n border:1px solid green;\n}\n\n.gwt-Blue-Border{ \n border:1px solid blue;\n}"
},
{
"code": null,
"e": 6052,
"s": 5949,
"text": "Following is the content of the modified HTML host file war/HelloWorld.html to accomodate two buttons."
},
{
"code": null,
"e": 6376,
"s": 6052,
"text": "<html>\n <head>\n <title>Hello World</title>\n <link rel = \"stylesheet\" href = \"HelloWorld.css\"/>\n <script language = \"javascript\" src = \"helloworld/helloworld.nocache.js\">\n </script>\n </head>\n\n <body>\n <h1>Label Widget Demonstration</h1>\n <div id = \"gwtContainer\"></div>\n </body>\n</html>"
},
{
"code": null,
"e": 6502,
"s": 6376,
"text": "Let us have following content of Java file src/com.tutorialspoint/HelloWorld.java which will demonstrate use of Label widget."
},
{
"code": null,
"e": 7396,
"s": 6502,
"text": "package com.tutorialspoint.client;\n\nimport com.google.gwt.core.client.EntryPoint;\nimport com.google.gwt.user.client.ui.Label;\nimport com.google.gwt.user.client.ui.RootPanel;\nimport com.google.gwt.user.client.ui.VerticalPanel;\n\npublic class HelloWorld implements EntryPoint {\n public void onModuleLoad() {\n // create two Labels\n Label label1 = new Label(\"This is first GWT Label\");\n Label label2 = new Label(\"This is second GWT Label\");\n\n // use UIObject methods to set label properties.\n label1.setTitle(\"Title for first Lable\");\n label1.addStyleName(\"gwt-Green-Border\");\n label2.setTitle(\"Title for second Lable\");\n label2.addStyleName(\"gwt-Blue-Border\");\n\n // add labels to the root panel.\n VerticalPanel panel = new VerticalPanel();\n panel.add(label1);\n panel.add(label2);\n\n RootPanel.get(\"gwtContainer\").add(panel);\n }\n}"
},
{
"code": null,
"e": 7630,
"s": 7396,
"text": "Once you are ready with all the changes done, let us compile and run the application in development mode as we did in GWT - Create Application chapter. If everything is fine with your application, this will produce following result −"
},
{
"code": null,
"e": 7637,
"s": 7630,
"text": " Print"
},
{
"code": null,
"e": 7648,
"s": 7637,
"text": " Add Notes"
}
] |
Building UI Using Jetpack Compose in Android - GeeksforGeeks
|
15 Nov, 2021
Jetpack Compose is a modern UI toolkit that is designed to simplify UI development in Android. It consists of a reactive programming model with conciseness and ease of Kotlin programming language. It is fully declarative so that you can describe your UI by calling some series of functions that will transform your data into a UI hierarchy. When the data changes or is updated then the framework automatically recalls these functions and updates the view for you.
Prerequisites:
Familiar with Kotlin and OOP Concepts as wellBasic understanding about Jetpack ComposeAndroid Studio
Familiar with Kotlin and OOP Concepts as well
Basic understanding about Jetpack Compose
Android Studio
So, we are just going to create an application UI using jetpack compose (Kotlin). our final UI will look like it.
Media error: Format(s) not supported or source(s) not found
It’s’ an easy UI to build using jetpack compose but a little bit hard using XML. So, let’s start step by step.
Step 1: Create a new android studio project
To create a new project in Android Studio using Jetpack Compose please refer to:- How to Create a New Project in Android Studio Canary Version with Jetpack Compose.
Step 2: Let’s Add resources to the project
There are some resources like colors, image assets, fonts, and some little things. You can easily find them otherwise just get them from the GitHub repo.
Step 3: Create a Kotlin class HomeScreen.kt
We can do the same task in MainActivity.kt as well, but it’s good practice to create another file. Initially, we start from the top, so creating the first header of the UI. having two texts with an image of a search icon. Things are very easy in this case we just create functions and call them, and that is how we can reuse the code very easily.
Kotlin
package com.cuid.geekscourse.ui.theme import androidx.compose.foundation.backgroundimport androidx.compose.foundation.layout.*import androidx.compose.material.Iconimport androidx.compose.material.MaterialThemeimport androidx.compose.material.Textimport androidx.compose.runtime.Composableimport androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifierimport androidx.compose.ui.graphics.Colorimport androidx.compose.ui.res.painterResourceimport androidx.compose.ui.tooling.preview.Previewimport androidx.compose.ui.unit.dpimport com.cuid.composeui.R // here we have created HomeScreen function// and we will call all functions inside it.// and finally just call this function from mainActivity@Composablefun HomeScreen() { // this is the most outer box that will // contain all the views,buttons,chips,etc. Box( modifier = Modifier .background(DeepBlue) .fillMaxSize() ) { Column { // this is how we call // function adding whole UI GreetingSection() } } @Composable // and this is the function// just for creating header at topfun GreetingSection( name: String = "Geeks") { // here we just arrange the views Row( horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically, modifier = Modifier .fillMaxWidth() .padding(15.dp) ) { Column( verticalArrangement = Arrangement.Center ) { // heading text view Text( text = "Good morning, $name", style = MaterialTheme.typography.h1 ) Text( text = "We wish you have a good day!", style = MaterialTheme.typography.body1 ) } // search icon Icon( painter = painterResource(id = R.drawable.ic_search), contentDescription = "Search", tint = Color.White, modifier = Modifier.size(24.dp) ) }}
Step 4: Create another function for chips
As we have shown above in-app preview that we can change chips. So let’s build it.
Kotlin
// This is how we can create chip seaction at the top of app @Composablefun ChipSection( // function with single argument chips: List<String>) { var selectedChipIndex by remember { // it will not update the string // but save and it will helpful for us mutableStateOf(0) } LazyRow { items(chips.size) { Box( contentAlignment = Alignment.Center, modifier = Modifier .padding(start = 15.dp, top = 15.dp, bottom = 15.dp) .clickable { selectedChipIndex = it } .clip(RoundedCornerShape(10.dp)) .background( // this is basic condition for selected chip index if (selectedChipIndex == it) ButtonGreen else DarkerButtonGreen ) .padding(15.dp) ) { Text(text = chips[it], color = TextWhite) } } }}
Step 5: Create a function for SuggestionSecation
It’s really a very basic part of this app.
Kotlin
// This function is for suggestion secation @Composablefun SuggestionSection( color: Color = LightBlue) { Row( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceBetween, modifier = Modifier .padding(15.dp) .clip(RoundedCornerShape(10.dp)) .background(color) .padding(horizontal = 15.dp, vertical = 20.dp) .fillMaxWidth() ) { Column { // here are two text views or we can say only text Text( text = "Daily Coding", // it can be litile bit confusing but // it is just text style alternate // of fontfamily in XML style = MaterialTheme.typography.h2 ) Text( // same as above text = "do at least • 3-10 problems / day", style = MaterialTheme.typography.body1, color = TextWhite ) } Box( // box containing icon contentAlignment = Alignment.Center, modifier = Modifier .size(40.dp) .clip(CircleShape) .background(ButtonGreen) .padding(10.dp) ) { Icon( painter = painterResource(id = R.drawable.ic_play), contentDescription = "Play", tint = Color.White, modifier = Modifier.size(16.dp) ) } }}
The next step should be the card of courses but that is not easy or we can say the toughest part of the whole UI, so we will do it after the last one.
Let’s Create a BottomSection, but before that, we should create the class for simplicity
because our BottomSection element has two fields or views so let’s do
Step 6: Create Class for ButtomSection (BottomMenuContent.kt)
Kotlin
package com.cuid.geekscourses import androidx.annotation.DrawableRes// having two parameters title and iconiddata class BottomMenuContent( val title: String, @DrawableRes val iconId: Int)
Step 7: Create function for ButtomSection
Kotlin
@Composable// this function tells us that// how menu item should look likefun BottomMenu( items: List<BottomMenuContent>, modifier: Modifier = Modifier, activeHighlightColor: Color = ButtonGreen, activeTextColor: Color = Color.White, inactiveTextColor: Color = AquaBlue, initialSelectedItemIndex: Int = 0) { var selectedItemIndex by remember { mutableStateOf(initialSelectedItemIndex) } Row( horizontalArrangement = Arrangement.SpaceAround, verticalAlignment = Alignment.CenterVertically, modifier = modifier .fillMaxWidth() .background(DeepBlue) .padding(15.dp) ) { // it is basically what we should have // for creating an element of BottomMenuItem items.forEachIndexed { index, item -> BottomMenuItem( item = item, isSelected = index == selectedItemIndex, activeHighlightColor = activeHighlightColor, activeTextColor = activeTextColor, inactiveTextColor = inactiveTextColor ) { selectedItemIndex = index } } }}// it's basically how menu item should look like@Composablefun BottomMenuItem( item: BottomMenuContent, isSelected: Boolean = false, activeHighlightColor: Color = ButtonGreen, activeTextColor: Color = Color.White, inactiveTextColor: Color = AquaBlue, onItemClick: () -> Unit) { Column( horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center, modifier = Modifier.clickable { onItemClick() } ) { // here are some peremetens // for how elements will align Box( contentAlignment = Alignment.Center, modifier = Modifier .clip(RoundedCornerShape(10.dp)) .background(if (isSelected) activeHighlightColor else Color.Transparent) .padding(10.dp) ) { Icon( painter = painterResource(id = item.iconId), contentDescription = item.title, tint = if (isSelected) activeTextColor else inactiveTextColor, modifier = Modifier.size(20.dp) ) } Text( text = item.title, // it's basic condition color = if(isSelected) activeTextColor else inactiveTextColor ) }}
Now, the final part of the app is a little bit tricky, which is nothing but the course item, this one:
course item
Here we have three colors, string and icon as well, then same as above we will create a class, and set data during the function call
Step 8: Creating Class Course.kt
This section has five fields, so create five variables of their types. The fields you can see in the code as well.
Kotlin
package com.cuid.geekscourses import androidx.annotation.DrawableResimport androidx.compose.ui.graphics.Color data class Course( val title: String, @DrawableRes val iconId: Int, val lightColor: Color, val mediumColor: Color, val darkColor: Color)
Now just think about it, that how to make those curves on the card. So basically, we set some points and create a smooth curve by joining points created
Step 9: Creating CourseSection
It’s basically just how our grid will Arrange.
Kotlin
@ExperimentalFoundationApi@Composable// here we have just passed the list of coursesfun CourseSection(courses: List<Course>) { Column(modifier = Modifier.fillMaxWidth()) { Text( text = "courses", style = MaterialTheme.typography.h1, modifier = Modifier.padding(15.dp) ) // we have used lazyVertically grid LazyVerticalGrid( cells = GridCells.Fixed(2), // it basically tells no. of cells in a row contentPadding = PaddingValues(start = 7.5.dp, end = 7.5.dp,bottom = 100.dp), modifier = Modifier.fillMaxHeight() ) { items(courses.size) { // here we have to define how one of these item is look like // we will tell after defining item design // let me comment it for now and after // creating you just have to remove // CourseItem(course = courses[it]) } } }}
Step 10: Creating Course Card Item Design
Kotlin
@Composablefun CourseItem( course: Course) { BoxWithConstraints( // Box with some attributes modifier = Modifier .padding(7.5.dp) .aspectRatio(1f) .clip(RoundedCornerShape(10.dp)) .background(feature.darkColor) ) { val width = constraints.maxWidth val height = constraints.maxHeight // setting 5 points for medium // color or we can say for another // Medium colored path val mediumColoredPoint1 = Offset(0f, height * 0.3f) val mediumColoredPoint2 = Offset(width * 0.1f, height * 0.35f) val mediumColoredPoint3 = Offset(width * 0.4f, height * 0.05f) val mediumColoredPoint4 = Offset(width * 0.75f, height * 0.7f) val mediumColoredPoint5 = Offset(width * 1.4f, -height.toFloat()) // joining points to make curves with the help of path class // path file that we have created earlier // having function that just help to reduce our code // and the function is standardQuadFromTo(m1,m2) taking // two peramente and connect them val mediumColoredPath = Path().apply { moveTo(mediumColoredPoint1.x, mediumColoredPoint1.y) standardQuadFromTo(mediumColoredPoint1, mediumColoredPoint2) standardQuadFromTo(mediumColoredPoint2, mediumColoredPoint3) standardQuadFromTo(mediumColoredPoint3, mediumColoredPoint4) standardQuadFromTo(mediumColoredPoint4, mediumColoredPoint5) lineTo(width.toFloat() + 100f, height.toFloat() + 100f) lineTo(-100f, height.toFloat() + 100f) close() } // it's another part of that // texture with light color // Light colored path val lightPoint1 = Offset(0f, height * 0.35f) val lightPoint2 = Offset(width * 0.1f, height * 0.4f) val lightPoint3 = Offset(width * 0.3f, height * 0.35f) val lightPoint4 = Offset(width * 0.65f, height.toFloat()) val lightPoint5 = Offset(width * 1.4f, -height.toFloat() / 3f) val lightColoredPath = Path().apply { moveTo(lightPoint1.x, lightPoint1.y) standardQuadFromTo(lightPoint1, lightPoint2) standardQuadFromTo(lightPoint2, lightPoint3) standardQuadFromTo(lightPoint3, lightPoint4) standardQuadFromTo(lightPoint4, lightPoint5) lineTo(width.toFloat() + 100f, height.toFloat() + 100f) lineTo(-100f, height.toFloat() + 100f) close() } // canvas is used when we // want to draw something Canvas( modifier = Modifier .fillMaxSize() ) { drawPath( // function for drawing paths // just pass the path path = mediumColoredPath, color = course.mediumColor ) drawPath( // it's for the lighter path path = lightColoredPath, color = course.lightColor ) } // so , we have done with texture and // now just creating box and other things // box containing course elements Box( modifier = Modifier .fillMaxSize() .padding(15.dp) ) { Text( text = course.title, style = MaterialTheme.typography.h2, lineHeight = 26.sp, modifier = Modifier.align(Alignment.TopStart) ) Icon( painter = painterResource(id = course.iconId), contentDescription = course.title, tint = Color.White, modifier = Modifier.align(Alignment.BottomStart) ) Text( text = "Start", color = TextWhite, fontSize = 14.sp, fontWeight = FontWeight.Bold, modifier = Modifier .clickable { // Handle the clicks } .align(Alignment.BottomEnd) .clip(RoundedCornerShape(10.dp)) .background(ButtonGreen) .padding(vertical = 6.dp, horizontal = 15.dp) ) } }}
That’s all about, how our item will look like. So just pass the item in the course section
CourseItem(course = courses[it])
It’s that file that we have discussed above to reduce our code
Kotlin
package com.cuid.geekscourses import androidx.compose.ui.geometry.Offsetimport androidx.compose.ui.graphics.Pathimport kotlin.math.abs// The function is standardQuadFromTo(m1,m2)// taking two peramente those are nothing but points// that we are created and just add.fun Path.standardQuadFromTo(from: Offset, to: Offset) { // this function is basically draw // a line to our second point and // also smooth on that line and make it curve quadraticBezierTo( from.x, from.y, abs(from.x + to.x) / 2f, abs(from.y + to.y) / 2f )}
Now we have all the things ready so just call all the functions and see your result as
Kotlin
@ExperimentalFoundationApi@Composablefun HomeScreen() { // this is the most outer box // having all the views inside it Box( modifier = Modifier .background(DeepBlue) .fillMaxSize() ) { Column { // this is the function for header GreetingSection() // it's for chipsSecation, and pass // as many strings as you want ChipSection(chips = listOf("Data structures", "Algorithms", "competitive programming", "python")) // function for suggestionSection suggestionSection() // this is for course secation CourseSection( // function require list of courses and // one course contain 5 attributes courses = listOf( Course( title = "geek of the year", R.drawable.ic_headphone, // these are colors....... BlueViolet1, BlueViolet2, BlueViolet3 ), // below are the copies of the objects // and you can add as many as you want Course( title = "How does AI Works", R.drawable.ic_videocam, LightGreen1, LightGreen2, LightGreen3 ), Course( title = "Advance python Course", R.drawable.ic_play, skyblue1, skyblue2, skyblue3 ), Course( title = "Advance Java Course", R.drawable.ic_headphone, Beige1, Beige2, Beige3 ), Course( title = "prepare for aptitude test", R.drawable.ic_play, OrangeYellow1, OrangeYellow2, OrangeYellow3 ), Course( title = "How does AI Works", R.drawable.ic_videocam, LightGreen1, LightGreen2, LightGreen3 ), ) ) } // this is the final one that is bottomMenu BottomMenu(items = listOf( // having 5 instances BottomMenuContent("Home", R.drawable.ic_home), BottomMenuContent("explore", R.drawable.ic_baseline_explore_24), BottomMenuContent("dark mode", R.drawable.ic_moon), BottomMenuContent("videos", R.drawable.ic_videocam), BottomMenuContent("Profile", R.drawable.ic_profile), ), modifier = Modifier.align(Alignment.BottomCenter)) }}
Now add fun HomeScreen() that contains all the functions, in MainActivity as
Kotlin
package com.cuid.geekscourses import android.os.Bundleimport androidx.activity.ComponentActivityimport androidx.activity.compose.setContentimport androidx.compose.foundation.ExperimentalFoundationApiimport com.cuid.geekscourses.ui.HomeScreenimport com.cuid.geekscourses.ui.theme.Geekscourse class MainActivity : ComponentActivity() { @ExperimentalFoundationApi override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { Geekscourse{ HomeScreen() } } }}
Finally, Our UI is looking like this:
Output:
Project Link: Click Here
rajeev0719singh
singghakshay
Android-Jetpack
Picked
Android
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Create and Add Data to SQLite Database in Android?
Broadcast Receiver in Android With Example
Resource Raw Folder in Android Studio
Services in Android with Example
CardView in Android With Example
Broadcast Receiver in Android With Example
Android UI Layouts
Kotlin Array
Services in Android with Example
Android RecyclerView in Kotlin
|
[
{
"code": null,
"e": 26421,
"s": 26393,
"text": "\n15 Nov, 2021"
},
{
"code": null,
"e": 26885,
"s": 26421,
"text": "Jetpack Compose is a modern UI toolkit that is designed to simplify UI development in Android. It consists of a reactive programming model with conciseness and ease of Kotlin programming language. It is fully declarative so that you can describe your UI by calling some series of functions that will transform your data into a UI hierarchy. When the data changes or is updated then the framework automatically recalls these functions and updates the view for you."
},
{
"code": null,
"e": 26900,
"s": 26885,
"text": "Prerequisites:"
},
{
"code": null,
"e": 27001,
"s": 26900,
"text": "Familiar with Kotlin and OOP Concepts as wellBasic understanding about Jetpack ComposeAndroid Studio"
},
{
"code": null,
"e": 27047,
"s": 27001,
"text": "Familiar with Kotlin and OOP Concepts as well"
},
{
"code": null,
"e": 27089,
"s": 27047,
"text": "Basic understanding about Jetpack Compose"
},
{
"code": null,
"e": 27104,
"s": 27089,
"text": "Android Studio"
},
{
"code": null,
"e": 27218,
"s": 27104,
"text": "So, we are just going to create an application UI using jetpack compose (Kotlin). our final UI will look like it."
},
{
"code": null,
"e": 27278,
"s": 27218,
"text": "Media error: Format(s) not supported or source(s) not found"
},
{
"code": null,
"e": 27389,
"s": 27278,
"text": "It’s’ an easy UI to build using jetpack compose but a little bit hard using XML. So, let’s start step by step."
},
{
"code": null,
"e": 27433,
"s": 27389,
"text": "Step 1: Create a new android studio project"
},
{
"code": null,
"e": 27598,
"s": 27433,
"text": "To create a new project in Android Studio using Jetpack Compose please refer to:- How to Create a New Project in Android Studio Canary Version with Jetpack Compose."
},
{
"code": null,
"e": 27641,
"s": 27598,
"text": "Step 2: Let’s Add resources to the project"
},
{
"code": null,
"e": 27795,
"s": 27641,
"text": "There are some resources like colors, image assets, fonts, and some little things. You can easily find them otherwise just get them from the GitHub repo."
},
{
"code": null,
"e": 27839,
"s": 27795,
"text": "Step 3: Create a Kotlin class HomeScreen.kt"
},
{
"code": null,
"e": 28186,
"s": 27839,
"text": "We can do the same task in MainActivity.kt as well, but it’s good practice to create another file. Initially, we start from the top, so creating the first header of the UI. having two texts with an image of a search icon. Things are very easy in this case we just create functions and call them, and that is how we can reuse the code very easily."
},
{
"code": null,
"e": 28193,
"s": 28186,
"text": "Kotlin"
},
{
"code": "package com.cuid.geekscourse.ui.theme import androidx.compose.foundation.backgroundimport androidx.compose.foundation.layout.*import androidx.compose.material.Iconimport androidx.compose.material.MaterialThemeimport androidx.compose.material.Textimport androidx.compose.runtime.Composableimport androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifierimport androidx.compose.ui.graphics.Colorimport androidx.compose.ui.res.painterResourceimport androidx.compose.ui.tooling.preview.Previewimport androidx.compose.ui.unit.dpimport com.cuid.composeui.R // here we have created HomeScreen function// and we will call all functions inside it.// and finally just call this function from mainActivity@Composablefun HomeScreen() { // this is the most outer box that will // contain all the views,buttons,chips,etc. Box( modifier = Modifier .background(DeepBlue) .fillMaxSize() ) { Column { // this is how we call // function adding whole UI GreetingSection() } } @Composable // and this is the function// just for creating header at topfun GreetingSection( name: String = \"Geeks\") { // here we just arrange the views Row( horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically, modifier = Modifier .fillMaxWidth() .padding(15.dp) ) { Column( verticalArrangement = Arrangement.Center ) { // heading text view Text( text = \"Good morning, $name\", style = MaterialTheme.typography.h1 ) Text( text = \"We wish you have a good day!\", style = MaterialTheme.typography.body1 ) } // search icon Icon( painter = painterResource(id = R.drawable.ic_search), contentDescription = \"Search\", tint = Color.White, modifier = Modifier.size(24.dp) ) }}",
"e": 30243,
"s": 28193,
"text": null
},
{
"code": null,
"e": 30285,
"s": 30243,
"text": "Step 4: Create another function for chips"
},
{
"code": null,
"e": 30368,
"s": 30285,
"text": "As we have shown above in-app preview that we can change chips. So let’s build it."
},
{
"code": null,
"e": 30375,
"s": 30368,
"text": "Kotlin"
},
{
"code": "// This is how we can create chip seaction at the top of app @Composablefun ChipSection( // function with single argument chips: List<String>) { var selectedChipIndex by remember { // it will not update the string // but save and it will helpful for us mutableStateOf(0) } LazyRow { items(chips.size) { Box( contentAlignment = Alignment.Center, modifier = Modifier .padding(start = 15.dp, top = 15.dp, bottom = 15.dp) .clickable { selectedChipIndex = it } .clip(RoundedCornerShape(10.dp)) .background( // this is basic condition for selected chip index if (selectedChipIndex == it) ButtonGreen else DarkerButtonGreen ) .padding(15.dp) ) { Text(text = chips[it], color = TextWhite) } } }}",
"e": 31420,
"s": 30375,
"text": null
},
{
"code": null,
"e": 31469,
"s": 31420,
"text": "Step 5: Create a function for SuggestionSecation"
},
{
"code": null,
"e": 31513,
"s": 31469,
"text": "It’s really a very basic part of this app. "
},
{
"code": null,
"e": 31520,
"s": 31513,
"text": "Kotlin"
},
{
"code": "// This function is for suggestion secation @Composablefun SuggestionSection( color: Color = LightBlue) { Row( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceBetween, modifier = Modifier .padding(15.dp) .clip(RoundedCornerShape(10.dp)) .background(color) .padding(horizontal = 15.dp, vertical = 20.dp) .fillMaxWidth() ) { Column { // here are two text views or we can say only text Text( text = \"Daily Coding\", // it can be litile bit confusing but // it is just text style alternate // of fontfamily in XML style = MaterialTheme.typography.h2 ) Text( // same as above text = \"do at least • 3-10 problems / day\", style = MaterialTheme.typography.body1, color = TextWhite ) } Box( // box containing icon contentAlignment = Alignment.Center, modifier = Modifier .size(40.dp) .clip(CircleShape) .background(ButtonGreen) .padding(10.dp) ) { Icon( painter = painterResource(id = R.drawable.ic_play), contentDescription = \"Play\", tint = Color.White, modifier = Modifier.size(16.dp) ) } }}",
"e": 33061,
"s": 31520,
"text": null
},
{
"code": null,
"e": 33212,
"s": 33061,
"text": "The next step should be the card of courses but that is not easy or we can say the toughest part of the whole UI, so we will do it after the last one."
},
{
"code": null,
"e": 33301,
"s": 33212,
"text": "Let’s Create a BottomSection, but before that, we should create the class for simplicity"
},
{
"code": null,
"e": 33371,
"s": 33301,
"text": "because our BottomSection element has two fields or views so let’s do"
},
{
"code": null,
"e": 33433,
"s": 33371,
"text": "Step 6: Create Class for ButtomSection (BottomMenuContent.kt)"
},
{
"code": null,
"e": 33440,
"s": 33433,
"text": "Kotlin"
},
{
"code": "package com.cuid.geekscourses import androidx.annotation.DrawableRes// having two parameters title and iconiddata class BottomMenuContent( val title: String, @DrawableRes val iconId: Int)",
"e": 33634,
"s": 33440,
"text": null
},
{
"code": null,
"e": 33677,
"s": 33634,
"text": "Step 7: Create function for ButtomSection "
},
{
"code": null,
"e": 33684,
"s": 33677,
"text": "Kotlin"
},
{
"code": "@Composable// this function tells us that// how menu item should look likefun BottomMenu( items: List<BottomMenuContent>, modifier: Modifier = Modifier, activeHighlightColor: Color = ButtonGreen, activeTextColor: Color = Color.White, inactiveTextColor: Color = AquaBlue, initialSelectedItemIndex: Int = 0) { var selectedItemIndex by remember { mutableStateOf(initialSelectedItemIndex) } Row( horizontalArrangement = Arrangement.SpaceAround, verticalAlignment = Alignment.CenterVertically, modifier = modifier .fillMaxWidth() .background(DeepBlue) .padding(15.dp) ) { // it is basically what we should have // for creating an element of BottomMenuItem items.forEachIndexed { index, item -> BottomMenuItem( item = item, isSelected = index == selectedItemIndex, activeHighlightColor = activeHighlightColor, activeTextColor = activeTextColor, inactiveTextColor = inactiveTextColor ) { selectedItemIndex = index } } }}// it's basically how menu item should look like@Composablefun BottomMenuItem( item: BottomMenuContent, isSelected: Boolean = false, activeHighlightColor: Color = ButtonGreen, activeTextColor: Color = Color.White, inactiveTextColor: Color = AquaBlue, onItemClick: () -> Unit) { Column( horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center, modifier = Modifier.clickable { onItemClick() } ) { // here are some peremetens // for how elements will align Box( contentAlignment = Alignment.Center, modifier = Modifier .clip(RoundedCornerShape(10.dp)) .background(if (isSelected) activeHighlightColor else Color.Transparent) .padding(10.dp) ) { Icon( painter = painterResource(id = item.iconId), contentDescription = item.title, tint = if (isSelected) activeTextColor else inactiveTextColor, modifier = Modifier.size(20.dp) ) } Text( text = item.title, // it's basic condition color = if(isSelected) activeTextColor else inactiveTextColor ) }}",
"e": 36137,
"s": 33684,
"text": null
},
{
"code": null,
"e": 36240,
"s": 36137,
"text": "Now, the final part of the app is a little bit tricky, which is nothing but the course item, this one:"
},
{
"code": null,
"e": 36252,
"s": 36240,
"text": "course item"
},
{
"code": null,
"e": 36386,
"s": 36252,
"text": "Here we have three colors, string and icon as well, then same as above we will create a class, and set data during the function call"
},
{
"code": null,
"e": 36419,
"s": 36386,
"text": "Step 8: Creating Class Course.kt"
},
{
"code": null,
"e": 36534,
"s": 36419,
"text": "This section has five fields, so create five variables of their types. The fields you can see in the code as well."
},
{
"code": null,
"e": 36541,
"s": 36534,
"text": "Kotlin"
},
{
"code": "package com.cuid.geekscourses import androidx.annotation.DrawableResimport androidx.compose.ui.graphics.Color data class Course( val title: String, @DrawableRes val iconId: Int, val lightColor: Color, val mediumColor: Color, val darkColor: Color)",
"e": 36803,
"s": 36541,
"text": null
},
{
"code": null,
"e": 36956,
"s": 36803,
"text": "Now just think about it, that how to make those curves on the card. So basically, we set some points and create a smooth curve by joining points created"
},
{
"code": null,
"e": 36987,
"s": 36956,
"text": "Step 9: Creating CourseSection"
},
{
"code": null,
"e": 37034,
"s": 36987,
"text": "It’s basically just how our grid will Arrange."
},
{
"code": null,
"e": 37041,
"s": 37034,
"text": "Kotlin"
},
{
"code": "@ExperimentalFoundationApi@Composable// here we have just passed the list of coursesfun CourseSection(courses: List<Course>) { Column(modifier = Modifier.fillMaxWidth()) { Text( text = \"courses\", style = MaterialTheme.typography.h1, modifier = Modifier.padding(15.dp) ) // we have used lazyVertically grid LazyVerticalGrid( cells = GridCells.Fixed(2), // it basically tells no. of cells in a row contentPadding = PaddingValues(start = 7.5.dp, end = 7.5.dp,bottom = 100.dp), modifier = Modifier.fillMaxHeight() ) { items(courses.size) { // here we have to define how one of these item is look like // we will tell after defining item design // let me comment it for now and after // creating you just have to remove // CourseItem(course = courses[it]) } } }}",
"e": 38015,
"s": 37041,
"text": null
},
{
"code": null,
"e": 38057,
"s": 38015,
"text": "Step 10: Creating Course Card Item Design"
},
{
"code": null,
"e": 38064,
"s": 38057,
"text": "Kotlin"
},
{
"code": "@Composablefun CourseItem( course: Course) { BoxWithConstraints( // Box with some attributes modifier = Modifier .padding(7.5.dp) .aspectRatio(1f) .clip(RoundedCornerShape(10.dp)) .background(feature.darkColor) ) { val width = constraints.maxWidth val height = constraints.maxHeight // setting 5 points for medium // color or we can say for another // Medium colored path val mediumColoredPoint1 = Offset(0f, height * 0.3f) val mediumColoredPoint2 = Offset(width * 0.1f, height * 0.35f) val mediumColoredPoint3 = Offset(width * 0.4f, height * 0.05f) val mediumColoredPoint4 = Offset(width * 0.75f, height * 0.7f) val mediumColoredPoint5 = Offset(width * 1.4f, -height.toFloat()) // joining points to make curves with the help of path class // path file that we have created earlier // having function that just help to reduce our code // and the function is standardQuadFromTo(m1,m2) taking // two peramente and connect them val mediumColoredPath = Path().apply { moveTo(mediumColoredPoint1.x, mediumColoredPoint1.y) standardQuadFromTo(mediumColoredPoint1, mediumColoredPoint2) standardQuadFromTo(mediumColoredPoint2, mediumColoredPoint3) standardQuadFromTo(mediumColoredPoint3, mediumColoredPoint4) standardQuadFromTo(mediumColoredPoint4, mediumColoredPoint5) lineTo(width.toFloat() + 100f, height.toFloat() + 100f) lineTo(-100f, height.toFloat() + 100f) close() } // it's another part of that // texture with light color // Light colored path val lightPoint1 = Offset(0f, height * 0.35f) val lightPoint2 = Offset(width * 0.1f, height * 0.4f) val lightPoint3 = Offset(width * 0.3f, height * 0.35f) val lightPoint4 = Offset(width * 0.65f, height.toFloat()) val lightPoint5 = Offset(width * 1.4f, -height.toFloat() / 3f) val lightColoredPath = Path().apply { moveTo(lightPoint1.x, lightPoint1.y) standardQuadFromTo(lightPoint1, lightPoint2) standardQuadFromTo(lightPoint2, lightPoint3) standardQuadFromTo(lightPoint3, lightPoint4) standardQuadFromTo(lightPoint4, lightPoint5) lineTo(width.toFloat() + 100f, height.toFloat() + 100f) lineTo(-100f, height.toFloat() + 100f) close() } // canvas is used when we // want to draw something Canvas( modifier = Modifier .fillMaxSize() ) { drawPath( // function for drawing paths // just pass the path path = mediumColoredPath, color = course.mediumColor ) drawPath( // it's for the lighter path path = lightColoredPath, color = course.lightColor ) } // so , we have done with texture and // now just creating box and other things // box containing course elements Box( modifier = Modifier .fillMaxSize() .padding(15.dp) ) { Text( text = course.title, style = MaterialTheme.typography.h2, lineHeight = 26.sp, modifier = Modifier.align(Alignment.TopStart) ) Icon( painter = painterResource(id = course.iconId), contentDescription = course.title, tint = Color.White, modifier = Modifier.align(Alignment.BottomStart) ) Text( text = \"Start\", color = TextWhite, fontSize = 14.sp, fontWeight = FontWeight.Bold, modifier = Modifier .clickable { // Handle the clicks } .align(Alignment.BottomEnd) .clip(RoundedCornerShape(10.dp)) .background(ButtonGreen) .padding(vertical = 6.dp, horizontal = 15.dp) ) } }}",
"e": 42327,
"s": 38064,
"text": null
},
{
"code": null,
"e": 42418,
"s": 42327,
"text": "That’s all about, how our item will look like. So just pass the item in the course section"
},
{
"code": null,
"e": 42451,
"s": 42418,
"text": "CourseItem(course = courses[it])"
},
{
"code": null,
"e": 42514,
"s": 42451,
"text": "It’s that file that we have discussed above to reduce our code"
},
{
"code": null,
"e": 42521,
"s": 42514,
"text": "Kotlin"
},
{
"code": "package com.cuid.geekscourses import androidx.compose.ui.geometry.Offsetimport androidx.compose.ui.graphics.Pathimport kotlin.math.abs// The function is standardQuadFromTo(m1,m2)// taking two peramente those are nothing but points// that we are created and just add.fun Path.standardQuadFromTo(from: Offset, to: Offset) { // this function is basically draw // a line to our second point and // also smooth on that line and make it curve quadraticBezierTo( from.x, from.y, abs(from.x + to.x) / 2f, abs(from.y + to.y) / 2f )}",
"e": 43094,
"s": 42521,
"text": null
},
{
"code": null,
"e": 43182,
"s": 43094,
"text": "Now we have all the things ready so just call all the functions and see your result as "
},
{
"code": null,
"e": 43189,
"s": 43182,
"text": "Kotlin"
},
{
"code": "@ExperimentalFoundationApi@Composablefun HomeScreen() { // this is the most outer box // having all the views inside it Box( modifier = Modifier .background(DeepBlue) .fillMaxSize() ) { Column { // this is the function for header GreetingSection() // it's for chipsSecation, and pass // as many strings as you want ChipSection(chips = listOf(\"Data structures\", \"Algorithms\", \"competitive programming\", \"python\")) // function for suggestionSection suggestionSection() // this is for course secation CourseSection( // function require list of courses and // one course contain 5 attributes courses = listOf( Course( title = \"geek of the year\", R.drawable.ic_headphone, // these are colors....... BlueViolet1, BlueViolet2, BlueViolet3 ), // below are the copies of the objects // and you can add as many as you want Course( title = \"How does AI Works\", R.drawable.ic_videocam, LightGreen1, LightGreen2, LightGreen3 ), Course( title = \"Advance python Course\", R.drawable.ic_play, skyblue1, skyblue2, skyblue3 ), Course( title = \"Advance Java Course\", R.drawable.ic_headphone, Beige1, Beige2, Beige3 ), Course( title = \"prepare for aptitude test\", R.drawable.ic_play, OrangeYellow1, OrangeYellow2, OrangeYellow3 ), Course( title = \"How does AI Works\", R.drawable.ic_videocam, LightGreen1, LightGreen2, LightGreen3 ), ) ) } // this is the final one that is bottomMenu BottomMenu(items = listOf( // having 5 instances BottomMenuContent(\"Home\", R.drawable.ic_home), BottomMenuContent(\"explore\", R.drawable.ic_baseline_explore_24), BottomMenuContent(\"dark mode\", R.drawable.ic_moon), BottomMenuContent(\"videos\", R.drawable.ic_videocam), BottomMenuContent(\"Profile\", R.drawable.ic_profile), ), modifier = Modifier.align(Alignment.BottomCenter)) }}",
"e": 46244,
"s": 43189,
"text": null
},
{
"code": null,
"e": 46322,
"s": 46244,
"text": "Now add fun HomeScreen() that contains all the functions, in MainActivity as "
},
{
"code": null,
"e": 46329,
"s": 46322,
"text": "Kotlin"
},
{
"code": "package com.cuid.geekscourses import android.os.Bundleimport androidx.activity.ComponentActivityimport androidx.activity.compose.setContentimport androidx.compose.foundation.ExperimentalFoundationApiimport com.cuid.geekscourses.ui.HomeScreenimport com.cuid.geekscourses.ui.theme.Geekscourse class MainActivity : ComponentActivity() { @ExperimentalFoundationApi override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { Geekscourse{ HomeScreen() } } }}",
"e": 46891,
"s": 46329,
"text": null
},
{
"code": null,
"e": 46929,
"s": 46891,
"text": "Finally, Our UI is looking like this:"
},
{
"code": null,
"e": 46937,
"s": 46929,
"text": "Output:"
},
{
"code": null,
"e": 46962,
"s": 46937,
"text": "Project Link: Click Here"
},
{
"code": null,
"e": 46978,
"s": 46962,
"text": "rajeev0719singh"
},
{
"code": null,
"e": 46991,
"s": 46978,
"text": "singghakshay"
},
{
"code": null,
"e": 47007,
"s": 46991,
"text": "Android-Jetpack"
},
{
"code": null,
"e": 47014,
"s": 47007,
"text": "Picked"
},
{
"code": null,
"e": 47022,
"s": 47014,
"text": "Android"
},
{
"code": null,
"e": 47029,
"s": 47022,
"text": "Kotlin"
},
{
"code": null,
"e": 47037,
"s": 47029,
"text": "Android"
},
{
"code": null,
"e": 47135,
"s": 47037,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 47193,
"s": 47135,
"text": "How to Create and Add Data to SQLite Database in Android?"
},
{
"code": null,
"e": 47236,
"s": 47193,
"text": "Broadcast Receiver in Android With Example"
},
{
"code": null,
"e": 47274,
"s": 47236,
"text": "Resource Raw Folder in Android Studio"
},
{
"code": null,
"e": 47307,
"s": 47274,
"text": "Services in Android with Example"
},
{
"code": null,
"e": 47340,
"s": 47307,
"text": "CardView in Android With Example"
},
{
"code": null,
"e": 47383,
"s": 47340,
"text": "Broadcast Receiver in Android With Example"
},
{
"code": null,
"e": 47402,
"s": 47383,
"text": "Android UI Layouts"
},
{
"code": null,
"e": 47415,
"s": 47402,
"text": "Kotlin Array"
},
{
"code": null,
"e": 47448,
"s": 47415,
"text": "Services in Android with Example"
}
] |
How to prevent MongoDB from returning the object ID while finding a document?
|
To prevent MongoDB from returning the Object ID while finding a document, you need to set _id
to 0. Let us first create a collection with documents
> db.preventObjectIdDemo.insertOne(
... {
...
... "StudentName" : "Chris",
... "StudentDetails" : [
... {
... "StudentTotalScore" : 540,
... "StudentCountryName" : "US"
... },
... {
... "StudentTotalScore" : 489,
... "StudentCountryName" : "UK"
... }
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5ca20a9c66324ffac2a7dc63")
}
Following is the query to display all documents from a collection with the help of find() method
> db.preventObjectIdDemo.find().pretty();
This will produce the following output
{
"_id" : ObjectId("5ca20a9c66324ffac2a7dc63"),
"StudentName" : "Chris",
"StudentDetails" : [
{
"StudentTotalScore" : 540,
"StudentCountryName" : "US"
},
{
"StudentTotalScore" : 489,
"StudentCountryName" : "UK"
}
]
}
Following is the query to prevent MongoDB from returning the Object ID when finding a
document
> db.preventObjectIdDemo.find({ _id: ObjectId("5ca20a9c66324ffac2a7dc63")},
{StudentDetails: { $slice: [0, 1] } ,'_id': 0} ).pretty();
The following is the output where ObjectID isn’t visible
{
"StudentName" : "Chris",
"StudentDetails" : [
{
"StudentTotalScore" : 540,
"StudentCountryName" : "US"
}
]
}
|
[
{
"code": null,
"e": 1210,
"s": 1062,
"text": "To prevent MongoDB from returning the Object ID while finding a document, you need to set _id\nto 0. Let us first create a collection with documents"
},
{
"code": null,
"e": 1667,
"s": 1210,
"text": "> db.preventObjectIdDemo.insertOne(\n... {\n...\n... \"StudentName\" : \"Chris\",\n... \"StudentDetails\" : [\n... {\n... \"StudentTotalScore\" : 540,\n... \"StudentCountryName\" : \"US\"\n... },\n... {\n... \"StudentTotalScore\" : 489,\n... \"StudentCountryName\" : \"UK\"\n... }\n... ]\n... }\n... );\n{\n\"acknowledged\" : true,\n\"insertedId\" : ObjectId(\"5ca20a9c66324ffac2a7dc63\")\n}"
},
{
"code": null,
"e": 1764,
"s": 1667,
"text": "Following is the query to display all documents from a collection with the help of find() method"
},
{
"code": null,
"e": 1806,
"s": 1764,
"text": "> db.preventObjectIdDemo.find().pretty();"
},
{
"code": null,
"e": 1845,
"s": 1806,
"text": "This will produce the following output"
},
{
"code": null,
"e": 2134,
"s": 1845,
"text": "{\n \"_id\" : ObjectId(\"5ca20a9c66324ffac2a7dc63\"),\n \"StudentName\" : \"Chris\",\n \"StudentDetails\" : [\n {\n \"StudentTotalScore\" : 540,\n \"StudentCountryName\" : \"US\"\n },\n {\n \"StudentTotalScore\" : 489,\n \"StudentCountryName\" : \"UK\"\n }\n ]\n}"
},
{
"code": null,
"e": 2229,
"s": 2134,
"text": "Following is the query to prevent MongoDB from returning the Object ID when finding a\ndocument"
},
{
"code": null,
"e": 2364,
"s": 2229,
"text": "> db.preventObjectIdDemo.find({ _id: ObjectId(\"5ca20a9c66324ffac2a7dc63\")},\n{StudentDetails: { $slice: [0, 1] } ,'_id': 0} ).pretty();"
},
{
"code": null,
"e": 2421,
"s": 2364,
"text": "The following is the output where ObjectID isn’t visible"
},
{
"code": null,
"e": 2571,
"s": 2421,
"text": "{\n \"StudentName\" : \"Chris\",\n \"StudentDetails\" : [\n {\n \"StudentTotalScore\" : 540,\n \"StudentCountryName\" : \"US\"\n }\n ]\n}"
}
] |
TensorFlow - TensorBoard Visualization
|
TensorFlow includes a visualization tool, which is called the TensorBoard. It is used for analyzing Data Flow Graph and also used to understand machine-learning models. The important feature of TensorBoard includes a view of different types of statistics about the parameters and details of any graph in vertical alignment.
Deep neural network includes up to 36,000 nodes. TensorBoard helps in collapsing these nodes in high-level blocks and highlighting the identical structures. This allows better analysis of graph focusing on the primary sections of the computation graph. The TensorBoard visualization is said to be very interactive where a user can pan, zoom and expand the nodes to display the details.
The following schematic diagram representation shows the complete working of TensorBoard visualization −
The algorithms collapse nodes into high-level blocks and highlight the specific groups with identical structures, which separate high-degree nodes. The TensorBoard thus created is useful and is treated equally important for tuning a machine learning model. This visualization tool is designed for the configuration log file with summary information and details that need to be displayed.
Let us focus on the demo example of TensorBoard visualization with the help of the following code −
import tensorflow as tf
# Constants creation for TensorBoard visualization
a = tf.constant(10,name = "a")
b = tf.constant(90,name = "b")
y = tf.Variable(a+b*2,name = 'y')
model = tf.initialize_all_variables() #Creation of model
with tf.Session() as session:
merged = tf.merge_all_summaries()
writer = tf.train.SummaryWriter("/tmp/tensorflowlogs",session.graph)
session.run(model)
print(session.run(y))
The following table shows the various symbols of TensorBoard visualization used for the node representation −
61 Lectures
9 hours
Abhishek And Pukhraj
57 Lectures
7 hours
Abhishek And Pukhraj
52 Lectures
7 hours
Abhishek And Pukhraj
52 Lectures
6 hours
Abhishek And Pukhraj
29 Lectures
3.5 hours
Mohammad Nauman
82 Lectures
4 hours
Anis Koubaa
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2639,
"s": 2315,
"text": "TensorFlow includes a visualization tool, which is called the TensorBoard. It is used for analyzing Data Flow Graph and also used to understand machine-learning models. The important feature of TensorBoard includes a view of different types of statistics about the parameters and details of any graph in vertical alignment."
},
{
"code": null,
"e": 3025,
"s": 2639,
"text": "Deep neural network includes up to 36,000 nodes. TensorBoard helps in collapsing these nodes in high-level blocks and highlighting the identical structures. This allows better analysis of graph focusing on the primary sections of the computation graph. The TensorBoard visualization is said to be very interactive where a user can pan, zoom and expand the nodes to display the details."
},
{
"code": null,
"e": 3130,
"s": 3025,
"text": "The following schematic diagram representation shows the complete working of TensorBoard visualization −"
},
{
"code": null,
"e": 3518,
"s": 3130,
"text": "The algorithms collapse nodes into high-level blocks and highlight the specific groups with identical structures, which separate high-degree nodes. The TensorBoard thus created is useful and is treated equally important for tuning a machine learning model. This visualization tool is designed for the configuration log file with summary information and details that need to be displayed."
},
{
"code": null,
"e": 3618,
"s": 3518,
"text": "Let us focus on the demo example of TensorBoard visualization with the help of the following code −"
},
{
"code": null,
"e": 4044,
"s": 3618,
"text": "import tensorflow as tf \n\n# Constants creation for TensorBoard visualization \na = tf.constant(10,name = \"a\") \nb = tf.constant(90,name = \"b\") \ny = tf.Variable(a+b*2,name = 'y') \nmodel = tf.initialize_all_variables() #Creation of model \n\nwith tf.Session() as session: \n merged = tf.merge_all_summaries() \n writer = tf.train.SummaryWriter(\"/tmp/tensorflowlogs\",session.graph) \n session.run(model) \n print(session.run(y))"
},
{
"code": null,
"e": 4154,
"s": 4044,
"text": "The following table shows the various symbols of TensorBoard visualization used for the node representation −"
},
{
"code": null,
"e": 4187,
"s": 4154,
"text": "\n 61 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 4209,
"s": 4187,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 4242,
"s": 4209,
"text": "\n 57 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 4264,
"s": 4242,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 4297,
"s": 4264,
"text": "\n 52 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 4319,
"s": 4297,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 4352,
"s": 4319,
"text": "\n 52 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 4374,
"s": 4352,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 4409,
"s": 4374,
"text": "\n 29 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 4426,
"s": 4409,
"text": " Mohammad Nauman"
},
{
"code": null,
"e": 4459,
"s": 4426,
"text": "\n 82 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 4472,
"s": 4459,
"text": " Anis Koubaa"
},
{
"code": null,
"e": 4479,
"s": 4472,
"text": " Print"
},
{
"code": null,
"e": 4490,
"s": 4479,
"text": " Add Notes"
}
] |
Pascal - Packed Array
|
These arrays are bit-packed, i.e., each character or truth values are stored in consecutive bytes instead of using one storage unit, usually a word (4 bytes or more).
Normally, characters and Boolean values are stored in such a way that each character or truth value uses one storage unit like a word. This is called unpacked mode of data storage. Storage is fully utilized if characters are stored in consecutive bytes. This is called packed mode of data storage. Pascal allows the array data to be stored in packed mode.
Packed arrays are declared using the keywords packed array instead of array. For example −
type
pArray: packed array[index-type1, index-type2, ...] of element-type;
var
a: pArray;
The following example declares and uses a two-dimensional packed array −
program packedarray;
var
a: packed array [0..3, 0..3] of integer;
i, j : integer;
begin
for i:=0 to 3 do
for j:=0 to 3 do
a[i,j]:= i * j;
for i:=0 to 3 do
begin
for j:=0 to 3 do
write(a[i,j]:2,' ');
writeln;
end;
end.
When the above code is compiled and executed, it produces the following result −
0 0 0 0
0 1 2 3
0 2 4 6
0 3 6 9
94 Lectures
8.5 hours
Stone River ELearning
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2250,
"s": 2083,
"text": "These arrays are bit-packed, i.e., each character or truth values are stored in consecutive bytes instead of using one storage unit, usually a word (4 bytes or more)."
},
{
"code": null,
"e": 2606,
"s": 2250,
"text": "Normally, characters and Boolean values are stored in such a way that each character or truth value uses one storage unit like a word. This is called unpacked mode of data storage. Storage is fully utilized if characters are stored in consecutive bytes. This is called packed mode of data storage. Pascal allows the array data to be stored in packed mode."
},
{
"code": null,
"e": 2697,
"s": 2606,
"text": "Packed arrays are declared using the keywords packed array instead of array. For example −"
},
{
"code": null,
"e": 2792,
"s": 2697,
"text": "type\n pArray: packed array[index-type1, index-type2, ...] of element-type;\nvar\n a: pArray;"
},
{
"code": null,
"e": 2865,
"s": 2792,
"text": "The following example declares and uses a two-dimensional packed array −"
},
{
"code": null,
"e": 3165,
"s": 2865,
"text": "program packedarray; \nvar\n a: packed array [0..3, 0..3] of integer;\n i, j : integer; \n\nbegin \n for i:=0 to 3 do \n for j:=0 to 3 do \n a[i,j]:= i * j; \n \n for i:=0 to 3 do \n begin \n for j:=0 to 3 do \n write(a[i,j]:2,' '); \n writeln; \n end; \nend."
},
{
"code": null,
"e": 3246,
"s": 3165,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 3279,
"s": 3246,
"text": "0 0 0 0\n0 1 2 3\n0 2 4 6\n0 3 6 9\n"
},
{
"code": null,
"e": 3314,
"s": 3279,
"text": "\n 94 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 3337,
"s": 3314,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 3344,
"s": 3337,
"text": " Print"
},
{
"code": null,
"e": 3355,
"s": 3344,
"text": " Add Notes"
}
] |
Building a Soft Decision Tree in TensorFlow | by Benoit Descamps | Towards Data Science
|
Deep learning products have grown in interests within the industry. While being computationally expensive, they have proven efficient in tackling classification of unstructured data such as in natural language or image processing.
The goal of a high-value data science product lies not only within its high-value delivery but also in its acceptance by the business. Hence, interpretability remains an important factor.
Google Brain recently released a paper proposing the implementation of soft decision trees.
In this blog, I take some key points from their paper and illustrate how a Neural Network can mimic a tree structure.
What is a decision tree in Data Science?How can a neural network have a tree-like structure?Implementing a Soft Decision Tree in TensorFlow
What is a decision tree in Data Science?
How can a neural network have a tree-like structure?
Implementing a Soft Decision Tree in TensorFlow
For the sake of informality, in data science, a tree consists of three main ingredients:
Split conditions
Pruning conditions
Leaves
The split conditions partition the data over the leaf. The pruning conditions decide when the partitioning stops. Finally, and most importantly, the leaves contain the predicted target value which has been fitted to the data within the partition.
As illustrated in Figure 1, each split condition is a function of the features.
The splits in each inner node and the target output of the leaves are determined by the optimization of a loss function. Each data point is assigned a cost for the prediction.
where
is the target of the data-point x and
is the probability of the target class of the leaf. We have also denoted the leaf selector:
This notation will be clear in the next section.
A neural network consists of a set of smooth operations on its input features. By smooth, I mean that each operation is continuously differentiable in their variables.
The differentiability is a crucial ingredient, as the optimal variables are calculated using the gradients of the loss and the operations. This seems like a problem at first, if we want to design trees as each inner node of the tree, assign each data point of one of its children based on the split condition.
Hence, our first steps towards building a tree with a neural network is to smear out the split condition, by allowing the data to go both left and right at each split but with a probability.
Consequently, each data point does not have a unique path through the tree. They now belong to every leaf of the tree, with a certain probability, i.e. the path probability.
Let us denote the path probability from the root of the tree to the n’th-(inner)-node,
We can look back at the loss function, we have written previously, for each data point x:
This is nothing other than a weighting of the categorical cross-entropy,
with the probability of x belonging to a leaf, which is the path probability.
We have now rewritten the split condition. The leaf output can remain a probability, such as a softmax.
A last questions remains however, will the optimization converge to a proper local minimum?
The updates of the weights of the inner-nodes is dependent on the gradient of the loss and therefore the path probability
Let us have a closer look at its variation at some inner-node j:
We immediately see an issue here. If the probability of some leaf
is small for a lot of data, the weight is then barely be updated in the next step. Even more so, after this update the probability remains very small. Our model might therefore converge and get stuck in these useless local minima.
A performant tree does not only have maximally pure leafs, but distributes the data as evenly as possible over its leafs. If our model gets stuck in these local minima, we end in only a few highly populated leafs and a lot of sparsely populated leafs. In this case, we lose the usefulness of the tree, and we end up with a small ensemble of logistic regression models.
Google Brain’s team proposes a remedy to this issue by introducing the regularization,
This regularization favors evenly binary split, and penalizes early purification on the level of the inner-nodes. The decay-rate gamma adds emphasis in the early inner nodes of the tree.
Now that everything is set-up, we can discuss the TensorFlow implementation.
TensorFlow is a popular open source software library by Google Brain mainly used for the development of Deep Learning models. The user defines operations on a static computational graph and runs different sections of the graph depending on the need.
Let us summarize the different ingredients with some basic formula:
Split conditions
Pruning conditions: let’s stick to a simple maximum depth
Leaf output
Loss for each data point x
We split our work into three classes:
TreeProperties: contains all the hyper-parameter related properties of the model.
Node: defines all operation on node level, such as forwarding the probability shown below in the case of an inner node or the softmax in case of a leaf:
SoftDecisionTree: builds all the inner-nodes, leafs and outputs the predicted target for each data point.
Let’s have a closer look!
As seen in section 3.2.2,the hyperparameters self.decay_penalty and self.regularisation_penalty, corresponds to the decay-rate gamma and weight lambda respectively.
The next class is more interesting.
At instantiation, we define the weight and bias of the split probability of the Node. When building the node, we first forward the output of the node, which is either the softmax prediction probability or the probability of the split of the inner node.
The loss is also updated on the node level. Inner nodes only contribute to the loss through the regularization described earlier.
Finally, all the nodes are combined together into a tree. The output prediction of the target and the probability distribution of the nodes are combined into self.output and self.leafs_distribution.
Let us conclude with some testing on MNIST. Constructing a tree with the following hyperparameters:
max_depth = 7regularisation_penality=10.decay_penality=0.9
and choosing a training batch size of 32 and validation batch size of 256. We arrive at the following result:
Not bad. Certainly not as competitive as CNN but we see a lot of promising ideas!
Make sure to check out the full implementation.
@ Tuning Hyperparameters (part I): SuccessiveHalving
@ Custom Optimizer in TensorFlow
@ Regression Prediction Intervals with XGBOOST
|
[
{
"code": null,
"e": 402,
"s": 171,
"text": "Deep learning products have grown in interests within the industry. While being computationally expensive, they have proven efficient in tackling classification of unstructured data such as in natural language or image processing."
},
{
"code": null,
"e": 590,
"s": 402,
"text": "The goal of a high-value data science product lies not only within its high-value delivery but also in its acceptance by the business. Hence, interpretability remains an important factor."
},
{
"code": null,
"e": 682,
"s": 590,
"text": "Google Brain recently released a paper proposing the implementation of soft decision trees."
},
{
"code": null,
"e": 800,
"s": 682,
"text": "In this blog, I take some key points from their paper and illustrate how a Neural Network can mimic a tree structure."
},
{
"code": null,
"e": 940,
"s": 800,
"text": "What is a decision tree in Data Science?How can a neural network have a tree-like structure?Implementing a Soft Decision Tree in TensorFlow"
},
{
"code": null,
"e": 981,
"s": 940,
"text": "What is a decision tree in Data Science?"
},
{
"code": null,
"e": 1034,
"s": 981,
"text": "How can a neural network have a tree-like structure?"
},
{
"code": null,
"e": 1082,
"s": 1034,
"text": "Implementing a Soft Decision Tree in TensorFlow"
},
{
"code": null,
"e": 1171,
"s": 1082,
"text": "For the sake of informality, in data science, a tree consists of three main ingredients:"
},
{
"code": null,
"e": 1188,
"s": 1171,
"text": "Split conditions"
},
{
"code": null,
"e": 1207,
"s": 1188,
"text": "Pruning conditions"
},
{
"code": null,
"e": 1214,
"s": 1207,
"text": "Leaves"
},
{
"code": null,
"e": 1461,
"s": 1214,
"text": "The split conditions partition the data over the leaf. The pruning conditions decide when the partitioning stops. Finally, and most importantly, the leaves contain the predicted target value which has been fitted to the data within the partition."
},
{
"code": null,
"e": 1541,
"s": 1461,
"text": "As illustrated in Figure 1, each split condition is a function of the features."
},
{
"code": null,
"e": 1717,
"s": 1541,
"text": "The splits in each inner node and the target output of the leaves are determined by the optimization of a loss function. Each data point is assigned a cost for the prediction."
},
{
"code": null,
"e": 1723,
"s": 1717,
"text": "where"
},
{
"code": null,
"e": 1761,
"s": 1723,
"text": "is the target of the data-point x and"
},
{
"code": null,
"e": 1853,
"s": 1761,
"text": "is the probability of the target class of the leaf. We have also denoted the leaf selector:"
},
{
"code": null,
"e": 1902,
"s": 1853,
"text": "This notation will be clear in the next section."
},
{
"code": null,
"e": 2070,
"s": 1902,
"text": "A neural network consists of a set of smooth operations on its input features. By smooth, I mean that each operation is continuously differentiable in their variables."
},
{
"code": null,
"e": 2380,
"s": 2070,
"text": "The differentiability is a crucial ingredient, as the optimal variables are calculated using the gradients of the loss and the operations. This seems like a problem at first, if we want to design trees as each inner node of the tree, assign each data point of one of its children based on the split condition."
},
{
"code": null,
"e": 2571,
"s": 2380,
"text": "Hence, our first steps towards building a tree with a neural network is to smear out the split condition, by allowing the data to go both left and right at each split but with a probability."
},
{
"code": null,
"e": 2745,
"s": 2571,
"text": "Consequently, each data point does not have a unique path through the tree. They now belong to every leaf of the tree, with a certain probability, i.e. the path probability."
},
{
"code": null,
"e": 2832,
"s": 2745,
"text": "Let us denote the path probability from the root of the tree to the n’th-(inner)-node,"
},
{
"code": null,
"e": 2922,
"s": 2832,
"text": "We can look back at the loss function, we have written previously, for each data point x:"
},
{
"code": null,
"e": 2995,
"s": 2922,
"text": "This is nothing other than a weighting of the categorical cross-entropy,"
},
{
"code": null,
"e": 3073,
"s": 2995,
"text": "with the probability of x belonging to a leaf, which is the path probability."
},
{
"code": null,
"e": 3177,
"s": 3073,
"text": "We have now rewritten the split condition. The leaf output can remain a probability, such as a softmax."
},
{
"code": null,
"e": 3269,
"s": 3177,
"text": "A last questions remains however, will the optimization converge to a proper local minimum?"
},
{
"code": null,
"e": 3391,
"s": 3269,
"text": "The updates of the weights of the inner-nodes is dependent on the gradient of the loss and therefore the path probability"
},
{
"code": null,
"e": 3456,
"s": 3391,
"text": "Let us have a closer look at its variation at some inner-node j:"
},
{
"code": null,
"e": 3522,
"s": 3456,
"text": "We immediately see an issue here. If the probability of some leaf"
},
{
"code": null,
"e": 3753,
"s": 3522,
"text": "is small for a lot of data, the weight is then barely be updated in the next step. Even more so, after this update the probability remains very small. Our model might therefore converge and get stuck in these useless local minima."
},
{
"code": null,
"e": 4122,
"s": 3753,
"text": "A performant tree does not only have maximally pure leafs, but distributes the data as evenly as possible over its leafs. If our model gets stuck in these local minima, we end in only a few highly populated leafs and a lot of sparsely populated leafs. In this case, we lose the usefulness of the tree, and we end up with a small ensemble of logistic regression models."
},
{
"code": null,
"e": 4209,
"s": 4122,
"text": "Google Brain’s team proposes a remedy to this issue by introducing the regularization,"
},
{
"code": null,
"e": 4396,
"s": 4209,
"text": "This regularization favors evenly binary split, and penalizes early purification on the level of the inner-nodes. The decay-rate gamma adds emphasis in the early inner nodes of the tree."
},
{
"code": null,
"e": 4473,
"s": 4396,
"text": "Now that everything is set-up, we can discuss the TensorFlow implementation."
},
{
"code": null,
"e": 4723,
"s": 4473,
"text": "TensorFlow is a popular open source software library by Google Brain mainly used for the development of Deep Learning models. The user defines operations on a static computational graph and runs different sections of the graph depending on the need."
},
{
"code": null,
"e": 4791,
"s": 4723,
"text": "Let us summarize the different ingredients with some basic formula:"
},
{
"code": null,
"e": 4808,
"s": 4791,
"text": "Split conditions"
},
{
"code": null,
"e": 4866,
"s": 4808,
"text": "Pruning conditions: let’s stick to a simple maximum depth"
},
{
"code": null,
"e": 4878,
"s": 4866,
"text": "Leaf output"
},
{
"code": null,
"e": 4905,
"s": 4878,
"text": "Loss for each data point x"
},
{
"code": null,
"e": 4943,
"s": 4905,
"text": "We split our work into three classes:"
},
{
"code": null,
"e": 5025,
"s": 4943,
"text": "TreeProperties: contains all the hyper-parameter related properties of the model."
},
{
"code": null,
"e": 5178,
"s": 5025,
"text": "Node: defines all operation on node level, such as forwarding the probability shown below in the case of an inner node or the softmax in case of a leaf:"
},
{
"code": null,
"e": 5284,
"s": 5178,
"text": "SoftDecisionTree: builds all the inner-nodes, leafs and outputs the predicted target for each data point."
},
{
"code": null,
"e": 5310,
"s": 5284,
"text": "Let’s have a closer look!"
},
{
"code": null,
"e": 5475,
"s": 5310,
"text": "As seen in section 3.2.2,the hyperparameters self.decay_penalty and self.regularisation_penalty, corresponds to the decay-rate gamma and weight lambda respectively."
},
{
"code": null,
"e": 5511,
"s": 5475,
"text": "The next class is more interesting."
},
{
"code": null,
"e": 5764,
"s": 5511,
"text": "At instantiation, we define the weight and bias of the split probability of the Node. When building the node, we first forward the output of the node, which is either the softmax prediction probability or the probability of the split of the inner node."
},
{
"code": null,
"e": 5894,
"s": 5764,
"text": "The loss is also updated on the node level. Inner nodes only contribute to the loss through the regularization described earlier."
},
{
"code": null,
"e": 6093,
"s": 5894,
"text": "Finally, all the nodes are combined together into a tree. The output prediction of the target and the probability distribution of the nodes are combined into self.output and self.leafs_distribution."
},
{
"code": null,
"e": 6193,
"s": 6093,
"text": "Let us conclude with some testing on MNIST. Constructing a tree with the following hyperparameters:"
},
{
"code": null,
"e": 6252,
"s": 6193,
"text": "max_depth = 7regularisation_penality=10.decay_penality=0.9"
},
{
"code": null,
"e": 6362,
"s": 6252,
"text": "and choosing a training batch size of 32 and validation batch size of 256. We arrive at the following result:"
},
{
"code": null,
"e": 6444,
"s": 6362,
"text": "Not bad. Certainly not as competitive as CNN but we see a lot of promising ideas!"
},
{
"code": null,
"e": 6492,
"s": 6444,
"text": "Make sure to check out the full implementation."
},
{
"code": null,
"e": 6545,
"s": 6492,
"text": "@ Tuning Hyperparameters (part I): SuccessiveHalving"
},
{
"code": null,
"e": 6578,
"s": 6545,
"text": "@ Custom Optimizer in TensorFlow"
}
] |
How to align the bars of a barplot with the X-axis using ggplot2 in R?
|
The bar plot is created with geom_bar function but there always exist some space between the bars and the X-axis labels. If we want to reduce that space or completely remove it we need to use scale_y_continuous function by defining expand argument for former and scale_y_continuous(expand=c(0,0)) for latter.
Live Demo
Consider the below data frame −
set.seed(888)
x<-c("S1","S2","S3","S4")
y<-c(24,27,25,28)
df<-data.frame(x,y)
df
x y
1 S1 24
2 S2 27
3 S3 25
4 S4 28
Loading ggplot2 package and creating bar plot of y −
library(ggplot2)
ggplot(df,aes(x,y))+geom_bar(stat="identity")
Creating the bar plot without space between X-axis labels and the bars −
ggplot(df,aes(x,y))+geom_bar(stat="identity")+scale_y_continuous(expand=c(0,0))
|
[
{
"code": null,
"e": 1371,
"s": 1062,
"text": "The bar plot is created with geom_bar function but there always exist some space between the bars and the X-axis labels. If we want to reduce that space or completely remove it we need to use scale_y_continuous function by defining expand argument for former and scale_y_continuous(expand=c(0,0)) for latter."
},
{
"code": null,
"e": 1382,
"s": 1371,
"text": " Live Demo"
},
{
"code": null,
"e": 1414,
"s": 1382,
"text": "Consider the below data frame −"
},
{
"code": null,
"e": 1495,
"s": 1414,
"text": "set.seed(888)\nx<-c(\"S1\",\"S2\",\"S3\",\"S4\")\ny<-c(24,27,25,28)\ndf<-data.frame(x,y)\ndf"
},
{
"code": null,
"e": 1534,
"s": 1495,
"text": " x y\n1 S1 24\n2 S2 27\n3 S3 25\n4 S4 28"
},
{
"code": null,
"e": 1587,
"s": 1534,
"text": "Loading ggplot2 package and creating bar plot of y −"
},
{
"code": null,
"e": 1650,
"s": 1587,
"text": "library(ggplot2)\nggplot(df,aes(x,y))+geom_bar(stat=\"identity\")"
},
{
"code": null,
"e": 1723,
"s": 1650,
"text": "Creating the bar plot without space between X-axis labels and the bars −"
},
{
"code": null,
"e": 1803,
"s": 1723,
"text": "ggplot(df,aes(x,y))+geom_bar(stat=\"identity\")+scale_y_continuous(expand=c(0,0))"
}
] |
How to set random background for Recyclerview in Android?
|
Before getting into set random background color for recycler view example, we should know what is Recycler view in android. Recycler view is a more advanced version of the list view and it works based on View holder design pattern. Using recycler view we can show grids and list of items.
This example demonstrates How to set the random background for Recyclerview by creating a beautiful student records app that displays student name with age.
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 − Open build.gradle and add Recycler view library dependency.
apply plugin: 'com.android.application'
android {
compileSdkVersion 28
defaultConfig {
applicationId "com.example.andy.tutorialspoint"
minSdkVersion 19
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support:design:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation 'com.android.support:recyclerview-v7:28.0.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
Step 3 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:showIn="@layout/activity_main"
tools:context=".MainActivity">
<android.support.v7.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="vertical" />
</RelativeLayout>
In the above code, we have added recycler view to window manager as relative parent layout.
Step 4 − Add the following code to src/MainActivity.java
package com.example.andy.tutorialspoint;
import android.annotation.TargetApi;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private StudentAdapter studentAdapter;
private List<studentData> studentDataList =new ArrayList<>();
@TargetApi(Build.VERSION_CODES.O)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recycler_view);
studentAdapter=new StudentAdapter(studentDataList);
RecyclerView.LayoutManager manager=new LinearLayoutManager(this);
recyclerView.setLayoutManager(manager);
recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
recyclerView.setAdapter(studentAdapter);
StudentDataPrepare();
}
@RequiresApi(api = Build.VERSION_CODES.N)
private void StudentDataPrepare() {
studentData data=new studentData("sai",25);
studentDataList.add(data);
data=new studentData("sai",25);
studentDataList.add(data);
data=new studentData("raghu",20);
studentDataList.add(data);
data=new studentData("raj",28);
studentDataList.add(data);
data=new studentData("amar",15);
studentDataList.add(data);
data=new studentData("bapu",19);
studentDataList.add(data);
data=new studentData("chandra",52);
studentDataList.add(data);
data=new studentData("deraj",30);
studentDataList.add(data);
data=new studentData("eshanth",28);
studentDataList.add(data);
Collections.sort(studentDataList, new Comparator() {
@Override
public int compare(studentData o1, studentData o2) {
return o1.name.compareTo(o2.name);
}
});
}
}
In the above code, we have added a recycler view and studentAdapter. In that student adapter, we have passed studentDatalist as ArrayList. Student data list contains the name of the student and age.
To compare recycler view items we have used collections framework and sort method as shown below -
Collections.sort(studentDataList, new Comparator<studentData>() {
@Override
public int compare(studentData o1, studentData o2) {
return o1.name.compareTo(o2.name);
}
});
In the above code, we are comparing elements by using name.
Step 5 − Following is the content of the modified file src/ StudentAdapter.java.
package com.example.andy.tutorialspoint;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.List;
import java.util.Random;
class StudentAdapter extends RecyclerView.Adapter<StudentAdapter.MyViewHolder> {
List<studentData> studentDataList;
public StudentAdapter(List<studentData> studentDataList) {
this.studentDataList=studentDataList;
}
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.student_list_row, viewGroup, false);
return new MyViewHolder(itemView);
}
@Override
public void onBindViewHolder(MyViewHolder viewHolder, int i) {
studentData data=studentDataList.get(i);
Random rnd = new Random();
int currentColor = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
viewHolder.parent.setBackgroundColor(currentColor);
viewHolder.name.setText(data.name);
viewHolder.age.setText(String.valueOf(data.age));
}
@Override
public int getItemCount() {
return studentDataList.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView name,age;
LinearLayout parent;
public MyViewHolder(View itemView) {
super(itemView);
parent=itemView.findViewById(R.id.parent);
name=itemView.findViewById(R.id.name);
age=itemView.findViewById(R.id.age);
}
}
}
In the adapter class, we have four methods as shown below -
onCreateViewHolder() - It is used to create a view holder and it returns a view.
onBindViewHolder() - It going to bind with created view holder.
getItemCount() - It contains size of list.
MyViewHolder class- It is view holder inner class which is extended by RecyclerView.ViewHolder
To set a random background for recycler view items, we have generated random colors using random class(which is the predefined class in Android) and added color to a parent of view item as shown below -
Random rnd = new Random();
int currentColor = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
viewHolder.parent.setBackgroundColor(currentColor);
Step 6 − Following is the modified content of the XML res/layout/student_list_row.xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:weightSum="1"
android:layout_height="wrap_content">
<TextView
android:id="@+id/name"
android:layout_width="0dp"
android:layout_weight="0.5"
android:gravity="center"
android:textSize="15sp"
android:layout_height="100dp" />
<TextView
android:id="@+id/age"
android:layout_width="0dp"
android:layout_weight="0.5"
android:gravity="center"
android:textSize="15sp"
android:layout_height="100dp" />
</LinearLayout>
In the above list item view, we have created two text views for name and age.
Step 7 − Following is the content of the modified file src/ studentData.java.
package com.example.andy.tutorialspoint;
class studentData {
String name;
int age;
public studentData(String name, int age) {
this.name=name;
this.age=age;
}
}
In the above code informs about student data object. Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
In the above result, we have shown data from Alphabetic A and random background colors. Now scroll down. It shows the result as shown below -
Click here to download the project code
|
[
{
"code": null,
"e": 1351,
"s": 1062,
"text": "Before getting into set random background color for recycler view example, we should know what is Recycler view in android. Recycler view is a more advanced version of the list view and it works based on View holder design pattern. Using recycler view we can show grids and list of items."
},
{
"code": null,
"e": 1508,
"s": 1351,
"text": "This example demonstrates How to set the random background for Recyclerview by creating a beautiful student records app that displays student name with age."
},
{
"code": null,
"e": 1637,
"s": 1508,
"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": 1706,
"s": 1637,
"text": "Step 2 − Open build.gradle and add Recycler view library dependency."
},
{
"code": null,
"e": 2724,
"s": 1706,
"text": "apply plugin: 'com.android.application'\nandroid {\n compileSdkVersion 28\n defaultConfig {\n applicationId \"com.example.andy.tutorialspoint\"\n minSdkVersion 19\n targetSdkVersion 28\n versionCode 1\n versionName \"1.0\"\n testInstrumentationRunner \"android.support.test.runner.AndroidJUnitRunner\"\n }\n buildTypes {\n release {\n minifyEnabled false\n proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'\n }\n }\n}\ndependencies {\n implementation fileTree(dir: 'libs', include: ['*.jar'])\n implementation 'com.android.support:appcompat-v7:28.0.0'\n implementation 'com.android.support:design:28.0.0'\n implementation 'com.android.support.constraint:constraint-layout:1.1.3'\n implementation 'com.android.support:recyclerview-v7:28.0.0'\n testImplementation 'junit:junit:4.12'\n androidTestImplementation 'com.android.support.test:runner:1.0.2'\n androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'\n}"
},
{
"code": null,
"e": 2789,
"s": 2724,
"text": "Step 3 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 3451,
"s": 2789,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout\n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n xmlns:app=\"http://schemas.android.com/apk/res-auto\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n app:layout_behavior=\"@string/appbar_scrolling_view_behavior\"\n tools:showIn=\"@layout/activity_main\"\n tools:context=\".MainActivity\">\n <android.support.v7.widget.RecyclerView\n android:id=\"@+id/recycler_view\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:scrollbars=\"vertical\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 3543,
"s": 3451,
"text": "In the above code, we have added recycler view to window manager as relative parent layout."
},
{
"code": null,
"e": 3600,
"s": 3543,
"text": "Step 4 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 5993,
"s": 3600,
"text": "package com.example.andy.tutorialspoint;\nimport android.annotation.TargetApi;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.support.annotation.RequiresApi;\nimport android.support.design.widget.TabLayout;\nimport android.support.v4.view.ViewPager;\nimport android.support.v7.app.AppCompatActivity;\nimport android.support.v7.widget.DividerItemDecoration;\nimport android.support.v7.widget.LinearLayoutManager;\nimport android.support.v7.widget.RecyclerView;\nimport android.support.v7.widget.Toolbar;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.Comparator;\nimport java.util.List;\npublic class MainActivity extends AppCompatActivity {\n private RecyclerView recyclerView;\n private StudentAdapter studentAdapter;\n private List<studentData> studentDataList =new ArrayList<>();\n @TargetApi(Build.VERSION_CODES.O)\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n recyclerView = findViewById(R.id.recycler_view);\n studentAdapter=new StudentAdapter(studentDataList);\n RecyclerView.LayoutManager manager=new LinearLayoutManager(this);\n recyclerView.setLayoutManager(manager);\n recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));\n recyclerView.setAdapter(studentAdapter);\n StudentDataPrepare();\n }\n @RequiresApi(api = Build.VERSION_CODES.N)\n private void StudentDataPrepare() {\n studentData data=new studentData(\"sai\",25);\n studentDataList.add(data);\n data=new studentData(\"sai\",25);\n studentDataList.add(data);\n data=new studentData(\"raghu\",20);\n studentDataList.add(data);\n data=new studentData(\"raj\",28);\n studentDataList.add(data);\n data=new studentData(\"amar\",15);\n studentDataList.add(data);\n data=new studentData(\"bapu\",19);\n studentDataList.add(data);\n data=new studentData(\"chandra\",52);\n studentDataList.add(data);\n data=new studentData(\"deraj\",30);\n studentDataList.add(data);\n data=new studentData(\"eshanth\",28);\n studentDataList.add(data);\n Collections.sort(studentDataList, new Comparator() {\n @Override\n public int compare(studentData o1, studentData o2) {\n return o1.name.compareTo(o2.name);\n }\n });\n }\n}"
},
{
"code": null,
"e": 6192,
"s": 5993,
"text": "In the above code, we have added a recycler view and studentAdapter. In that student adapter, we have passed studentDatalist as ArrayList. Student data list contains the name of the student and age."
},
{
"code": null,
"e": 6291,
"s": 6192,
"text": "To compare recycler view items we have used collections framework and sort method as shown below -"
},
{
"code": null,
"e": 6476,
"s": 6291,
"text": "Collections.sort(studentDataList, new Comparator<studentData>() {\n @Override\n public int compare(studentData o1, studentData o2) {\n return o1.name.compareTo(o2.name);\n }\n});"
},
{
"code": null,
"e": 6536,
"s": 6476,
"text": "In the above code, we are comparing elements by using name."
},
{
"code": null,
"e": 6617,
"s": 6536,
"text": "Step 5 − Following is the content of the modified file src/ StudentAdapter.java."
},
{
"code": null,
"e": 8337,
"s": 6617,
"text": "package com.example.andy.tutorialspoint;\nimport android.graphics.Color;\nimport android.support.annotation.NonNull;\nimport android.support.v7.widget.RecyclerView;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.LinearLayout;\nimport android.widget.TextView;\nimport java.util.List;\nimport java.util.Random;\nclass StudentAdapter extends RecyclerView.Adapter<StudentAdapter.MyViewHolder> {\n List<studentData> studentDataList;\n public StudentAdapter(List<studentData> studentDataList) {\n this.studentDataList=studentDataList;\n }\n @NonNull\n @Override\n public MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {\n View itemView = LayoutInflater.from(viewGroup.getContext())\n .inflate(R.layout.student_list_row, viewGroup, false);\n return new MyViewHolder(itemView);\n }\n @Override\n public void onBindViewHolder(MyViewHolder viewHolder, int i) {\n studentData data=studentDataList.get(i);\n Random rnd = new Random();\n int currentColor = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));\n viewHolder.parent.setBackgroundColor(currentColor);\n viewHolder.name.setText(data.name);\n viewHolder.age.setText(String.valueOf(data.age));\n }\n @Override\n public int getItemCount() {\n return studentDataList.size();\n }\n class MyViewHolder extends RecyclerView.ViewHolder {\n TextView name,age;\n LinearLayout parent;\n public MyViewHolder(View itemView) {\n super(itemView);\n parent=itemView.findViewById(R.id.parent);\n name=itemView.findViewById(R.id.name);\n age=itemView.findViewById(R.id.age);\n }\n }\n}"
},
{
"code": null,
"e": 8397,
"s": 8337,
"text": "In the adapter class, we have four methods as shown below -"
},
{
"code": null,
"e": 8478,
"s": 8397,
"text": "onCreateViewHolder() - It is used to create a view holder and it returns a view."
},
{
"code": null,
"e": 8542,
"s": 8478,
"text": "onBindViewHolder() - It going to bind with created view holder."
},
{
"code": null,
"e": 8585,
"s": 8542,
"text": "getItemCount() - It contains size of list."
},
{
"code": null,
"e": 8680,
"s": 8585,
"text": "MyViewHolder class- It is view holder inner class which is extended by RecyclerView.ViewHolder"
},
{
"code": null,
"e": 8883,
"s": 8680,
"text": "To set a random background for recycler view items, we have generated random colors using random class(which is the predefined class in Android) and added color to a parent of view item as shown below -"
},
{
"code": null,
"e": 9052,
"s": 8883,
"text": "Random rnd = new Random();\nint currentColor = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));\nviewHolder.parent.setBackgroundColor(currentColor);"
},
{
"code": null,
"e": 9139,
"s": 9052,
"text": "Step 6 − Following is the modified content of the XML res/layout/student_list_row.xml."
},
{
"code": null,
"e": 9822,
"s": 9139,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:orientation=\"horizontal\" android:layout_width=\"match_parent\"\n android:weightSum=\"1\"\n android:layout_height=\"wrap_content\">\n <TextView\n android:id=\"@+id/name\"\n android:layout_width=\"0dp\"\n android:layout_weight=\"0.5\"\n android:gravity=\"center\"\n android:textSize=\"15sp\"\n android:layout_height=\"100dp\" />\n <TextView\n android:id=\"@+id/age\"\n android:layout_width=\"0dp\"\n android:layout_weight=\"0.5\"\n android:gravity=\"center\"\n android:textSize=\"15sp\"\n android:layout_height=\"100dp\" />\n</LinearLayout>"
},
{
"code": null,
"e": 9900,
"s": 9822,
"text": "In the above list item view, we have created two text views for name and age."
},
{
"code": null,
"e": 9978,
"s": 9900,
"text": "Step 7 − Following is the content of the modified file src/ studentData.java."
},
{
"code": null,
"e": 10162,
"s": 9978,
"text": "package com.example.andy.tutorialspoint;\nclass studentData {\n String name;\n int age;\n public studentData(String name, int age) {\n this.name=name;\n this.age=age;\n }\n}"
},
{
"code": null,
"e": 10562,
"s": 10162,
"text": "In the above code informs about student data object. 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": 10704,
"s": 10562,
"text": "In the above result, we have shown data from Alphabetic A and random background colors. Now scroll down. It shows the result as shown below -"
},
{
"code": null,
"e": 10744,
"s": 10704,
"text": "Click here to download the project code"
}
] |
Heap overflow and Stack overflow in C
|
Heap is used to store dynamic variables. It is a region of process’s memory. malloc(), calloc(), resize() all these inbuilt functions are generally used to store dynamic variables.
Heap overflow occurs when −
A) If we allocate dynamic large number of variables −
int main() {
float *ptr = (int *)malloc(sizeof(float)*1000000.0));
}
B) If we continuously allocate memory and do not free after using it.
int main() {
for (int i=0; i<100000000000; i++) {
int *p = (int *)malloc(sizeof(int));
}
}
Stack is a Last in First out data structure. It is used to store local variables which is used inside the function. Parameters are passed through this function and their return addresses.
If a program consumes more memory space, then stack overflow will occur as stack size is limited in computer memory.
Stack overflow occurs when −
C) If a function is called recursively by itself infinite times then stack will be unable to store large number of local variables, so stack overflow will occur −
void calculate(int a) {
if (a== 0)
return;
a = 6;
calculate(a);
}
int main() {
int a = 5;
calculate(a);
}
D) If we declare a large number of local variables or declare a large dimensional array or matrix can result stack overflow.
int main() {
A[20000][20000]
}
|
[
{
"code": null,
"e": 1243,
"s": 1062,
"text": "Heap is used to store dynamic variables. It is a region of process’s memory. malloc(), calloc(), resize() all these inbuilt functions are generally used to store dynamic variables."
},
{
"code": null,
"e": 1271,
"s": 1243,
"text": "Heap overflow occurs when −"
},
{
"code": null,
"e": 1325,
"s": 1271,
"text": "A) If we allocate dynamic large number of variables −"
},
{
"code": null,
"e": 1397,
"s": 1325,
"text": "int main() {\n float *ptr = (int *)malloc(sizeof(float)*1000000.0));\n}"
},
{
"code": null,
"e": 1467,
"s": 1397,
"text": "B) If we continuously allocate memory and do not free after using it."
},
{
"code": null,
"e": 1570,
"s": 1467,
"text": "int main() {\n for (int i=0; i<100000000000; i++) {\n int *p = (int *)malloc(sizeof(int));\n }\n}"
},
{
"code": null,
"e": 1758,
"s": 1570,
"text": "Stack is a Last in First out data structure. It is used to store local variables which is used inside the function. Parameters are passed through this function and their return addresses."
},
{
"code": null,
"e": 1875,
"s": 1758,
"text": "If a program consumes more memory space, then stack overflow will occur as stack size is limited in computer memory."
},
{
"code": null,
"e": 1904,
"s": 1875,
"text": "Stack overflow occurs when −"
},
{
"code": null,
"e": 2067,
"s": 1904,
"text": "C) If a function is called recursively by itself infinite times then stack will be unable to store large number of local variables, so stack overflow will occur −"
},
{
"code": null,
"e": 2200,
"s": 2067,
"text": "void calculate(int a) {\n if (a== 0)\n return;\n a = 6;\n calculate(a);\n}\nint main() {\n int a = 5;\n calculate(a);\n}"
},
{
"code": null,
"e": 2325,
"s": 2200,
"text": "D) If we declare a large number of local variables or declare a large dimensional array or matrix can result stack overflow."
},
{
"code": null,
"e": 2359,
"s": 2325,
"text": "int main() {\n A[20000][20000]\n}"
}
] |
GATE-CS-2009 - GeeksforGeeks
|
22 Nov, 2021
What is the chromatic number of an n-vertex simple connected graph which does not contain any odd length cycle? Assume n >= 2.
n-1
3
2
n
The chromatic number of a graph is the smallest number of colours needed to colour the vertices of so that no two adjacent vertices share the same colour. These types of questions can be solved by substitution with different values of n. 1) n = 2
This simple graph can be coloured with 2 colours. 2) n = 3
Here, in this graph let us suppose vertex A is coloured with C1 and vertices B, C can be coloured with colour C2 => chromatic number is 2 In the same way, you can check with other values, Chromatic number is equals to 2 A simple graph with no odd cycles is bipartite graph and a Bipartite graph can be colored using 2 colors
A page table entry must contain Page frame number. Virtual page number is typically used as index in page table to get the corresponding page frame number. See this for details.
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)
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Must Do Coding Questions for Product Based Companies
How to Replace Values in Column Based on Condition in Pandas?
C Program to read contents of Whole File
How to Download and Install Spring Tool Suite (Spring Tools 4 for Eclipse) IDE?
How to Replace Values in a List in Python?
How to Select Data Between Two Dates and Times in SQL Server?
Spring - REST Controller
How to Read Text Files with Pandas?
How to Calculate Moving Averages in Python?
How to Compare Two Columns in Pandas?
|
[
{
"code": null,
"e": 28855,
"s": 28827,
"text": "\n22 Nov, 2021"
},
{
"code": null,
"e": 28983,
"s": 28855,
"text": "What is the chromatic number of an n-vertex simple connected graph which does not contain any odd length cycle? Assume n >= 2. "
},
{
"code": null,
"e": 28988,
"s": 28983,
"text": "n-1 "
},
{
"code": null,
"e": 28991,
"s": 28988,
"text": "3 "
},
{
"code": null,
"e": 28994,
"s": 28991,
"text": "2 "
},
{
"code": null,
"e": 28997,
"s": 28994,
"text": "n "
},
{
"code": null,
"e": 29246,
"s": 28997,
"text": "The chromatic number of a graph is the smallest number of colours needed to colour the vertices of so that no two adjacent vertices share the same colour. These types of questions can be solved by substitution with different values of n. 1) n = 2 "
},
{
"code": null,
"e": 29307,
"s": 29246,
"text": "This simple graph can be coloured with 2 colours. 2) n = 3 "
},
{
"code": null,
"e": 29633,
"s": 29307,
"text": "Here, in this graph let us suppose vertex A is coloured with C1 and vertices B, C can be coloured with colour C2 => chromatic number is 2 In the same way, you can check with other values, Chromatic number is equals to 2 A simple graph with no odd cycles is bipartite graph and a Bipartite graph can be colored using 2 colors "
},
{
"code": null,
"e": 29811,
"s": 29633,
"text": "A page table entry must contain Page frame number. Virtual page number is typically used as index in page table to get the corresponding page frame number. See this for details."
},
{
"code": null,
"e": 30026,
"s": 29811,
"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": 30124,
"s": 30026,
"text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here."
},
{
"code": null,
"e": 30177,
"s": 30124,
"text": "Must Do Coding Questions for Product Based Companies"
},
{
"code": null,
"e": 30239,
"s": 30177,
"text": "How to Replace Values in Column Based on Condition in Pandas?"
},
{
"code": null,
"e": 30280,
"s": 30239,
"text": "C Program to read contents of Whole File"
},
{
"code": null,
"e": 30360,
"s": 30280,
"text": "How to Download and Install Spring Tool Suite (Spring Tools 4 for Eclipse) IDE?"
},
{
"code": null,
"e": 30403,
"s": 30360,
"text": "How to Replace Values in a List in Python?"
},
{
"code": null,
"e": 30465,
"s": 30403,
"text": "How to Select Data Between Two Dates and Times in SQL Server?"
},
{
"code": null,
"e": 30490,
"s": 30465,
"text": "Spring - REST Controller"
},
{
"code": null,
"e": 30526,
"s": 30490,
"text": "How to Read Text Files with Pandas?"
},
{
"code": null,
"e": 30570,
"s": 30526,
"text": "How to Calculate Moving Averages in Python?"
}
] |
C# | Uri.IsWellFormedOriginalString() Method - GeeksforGeeks
|
30 Apr, 2019
Uri.IsWellFormedOriginalString() Method is used to show whether the string used to construct this Uri was well-formed and is not required to be further escaped.
Syntax: public bool IsWellFormedOriginalString ();
Return Value: This method returns true if the string was well-formed otherwise, false.
Below programs illustrate the use of Uri.IsWellFormedOriginalString() Method:
Example 1:
// C# program to demonstrate the// Uri.IsWellFormedOriginalString()// Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { // Declaring and initializing address Uri address1 = new Uri("http://www.contoso.com/index.htm#search"); // Validating if Uri is well formed or not // using IsWellFormedOriginalString() method bool value = address1.IsWellFormedOriginalString(); // Displaying the result if (value) Console.WriteLine("uri is well formed"); else Console.WriteLine("uri is not well formed"); }}
uri is well formed
Example 2:
// C# program to demonstrate the// Uri.IsWellFormedOriginalString() // Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { try { // calling get() method get(new Uri("http://www.contoso.com/path")); // if The string is not correctly escaped. get(new Uri("http://www.contoso.com/path???/file name")); // The string is an absolute Uri // that represents an implicit // file Uri. get(new Uri("c:\\directory\filename")); // The string is an absolute URI that // is missing a slash before the path. get(new Uri("file://c:/directory/filename")); // The parser for the Uri.Scheme indicates // that the original string was not well-formed. get(new Uri("xy11.z://www.contoso.com/path/file")); // The string contains unescaped backslashes // even if they are treated as forwarding slashes. get(new Uri("http:\\host/path/file")); // The string represents a hierarchical // absolute Uri and does not contain "://". get(new Uri("www.contoso.com/path/file")); } catch (UriFormatException e) { Console.Write("uri is so poorly formed that system thrown "); Console.Write("{0}", e.GetType(), e.Message); Environment.Exit(1); } } // defining get() method public static void get(Uri address) { // Validating if Uri is well formed or not // using IsWellFormedOriginalString() method bool value = address.IsWellFormedOriginalString(); // Displaying the result if (value) Console.WriteLine("uri is well formed"); else Console.WriteLine("uri is poorly formed"); }}
uri is well formed
uri is poorly formed
uri is poorly formed
uri is poorly formed
uri is well formed
uri is so poorly formed that system thrown System.UriFormatException
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.uri.iswellformedoriginalstring?view=netstandard-2.1
CSharp-method
CSharp-Uri-Class
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Extension Method in C#
HashSet in C# with Examples
C# | Inheritance
Partial Classes in C#
C# | Generics - Introduction
Top 50 C# Interview Questions & Answers
Switch Statement in C#
Lambda Expressions in C#
Convert String to Character Array in C#
C# | How to insert an element in an Array?
|
[
{
"code": null,
"e": 25657,
"s": 25629,
"text": "\n30 Apr, 2019"
},
{
"code": null,
"e": 25818,
"s": 25657,
"text": "Uri.IsWellFormedOriginalString() Method is used to show whether the string used to construct this Uri was well-formed and is not required to be further escaped."
},
{
"code": null,
"e": 25869,
"s": 25818,
"text": "Syntax: public bool IsWellFormedOriginalString ();"
},
{
"code": null,
"e": 25956,
"s": 25869,
"text": "Return Value: This method returns true if the string was well-formed otherwise, false."
},
{
"code": null,
"e": 26034,
"s": 25956,
"text": "Below programs illustrate the use of Uri.IsWellFormedOriginalString() Method:"
},
{
"code": null,
"e": 26045,
"s": 26034,
"text": "Example 1:"
},
{
"code": "// C# program to demonstrate the// Uri.IsWellFormedOriginalString()// Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { // Declaring and initializing address Uri address1 = new Uri(\"http://www.contoso.com/index.htm#search\"); // Validating if Uri is well formed or not // using IsWellFormedOriginalString() method bool value = address1.IsWellFormedOriginalString(); // Displaying the result if (value) Console.WriteLine(\"uri is well formed\"); else Console.WriteLine(\"uri is not well formed\"); }}",
"e": 26689,
"s": 26045,
"text": null
},
{
"code": null,
"e": 26709,
"s": 26689,
"text": "uri is well formed\n"
},
{
"code": null,
"e": 26720,
"s": 26709,
"text": "Example 2:"
},
{
"code": "// C# program to demonstrate the// Uri.IsWellFormedOriginalString() // Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { try { // calling get() method get(new Uri(\"http://www.contoso.com/path\")); // if The string is not correctly escaped. get(new Uri(\"http://www.contoso.com/path???/file name\")); // The string is an absolute Uri // that represents an implicit // file Uri. get(new Uri(\"c:\\\\directory\\filename\")); // The string is an absolute URI that // is missing a slash before the path. get(new Uri(\"file://c:/directory/filename\")); // The parser for the Uri.Scheme indicates // that the original string was not well-formed. get(new Uri(\"xy11.z://www.contoso.com/path/file\")); // The string contains unescaped backslashes // even if they are treated as forwarding slashes. get(new Uri(\"http:\\\\host/path/file\")); // The string represents a hierarchical // absolute Uri and does not contain \"://\". get(new Uri(\"www.contoso.com/path/file\")); } catch (UriFormatException e) { Console.Write(\"uri is so poorly formed that system thrown \"); Console.Write(\"{0}\", e.GetType(), e.Message); Environment.Exit(1); } } // defining get() method public static void get(Uri address) { // Validating if Uri is well formed or not // using IsWellFormedOriginalString() method bool value = address.IsWellFormedOriginalString(); // Displaying the result if (value) Console.WriteLine(\"uri is well formed\"); else Console.WriteLine(\"uri is poorly formed\"); }}",
"e": 28618,
"s": 26720,
"text": null
},
{
"code": null,
"e": 28789,
"s": 28618,
"text": "uri is well formed\nuri is poorly formed\nuri is poorly formed\nuri is poorly formed\nuri is well formed\nuri is so poorly formed that system thrown System.UriFormatException\n"
},
{
"code": null,
"e": 28800,
"s": 28789,
"text": "Reference:"
},
{
"code": null,
"e": 28903,
"s": 28800,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.uri.iswellformedoriginalstring?view=netstandard-2.1"
},
{
"code": null,
"e": 28917,
"s": 28903,
"text": "CSharp-method"
},
{
"code": null,
"e": 28934,
"s": 28917,
"text": "CSharp-Uri-Class"
},
{
"code": null,
"e": 28937,
"s": 28934,
"text": "C#"
},
{
"code": null,
"e": 29035,
"s": 28937,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29058,
"s": 29035,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 29086,
"s": 29058,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 29103,
"s": 29086,
"text": "C# | Inheritance"
},
{
"code": null,
"e": 29125,
"s": 29103,
"text": "Partial Classes in C#"
},
{
"code": null,
"e": 29154,
"s": 29125,
"text": "C# | Generics - Introduction"
},
{
"code": null,
"e": 29194,
"s": 29154,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 29217,
"s": 29194,
"text": "Switch Statement in C#"
},
{
"code": null,
"e": 29242,
"s": 29217,
"text": "Lambda Expressions in C#"
},
{
"code": null,
"e": 29282,
"s": 29242,
"text": "Convert String to Character Array in C#"
}
] |
Rust vs Dart – Which is More Likely to Replace C++?
|
15 Feb, 2021
Dennis M Ritchie developed C in the year 1972 as a successor of the B language. And it is widely used in the system as well as application programming. Its popularity has grown tremendously these years and now an object-oriented language derivative from C called C++ is becoming mature and stable programming language.
Rust is a system-level programming language that stand close to C++ in terms of syntax,but offers high speed and memory safety. On the other hand, Dart is an object-oriented, web-based programming language and is enriched with the features of a classical programming language where it runs on both server and browser. Now that the two superheroes have met each other, let’s hunt for their similarities and overlaps to decide who is going to dominate the C++ world.
1. Syntax: Let’s understand the basic syntactical differences by writing a simple code.
C++
Dart
#include <iostream>using namespace std; int main() { cout<<"Welcome to GFG!"; return 0;}
void main() { print('Welcome to GFG!');}
Similarly, to print the same code in rust:
fn main() {
println!("Welcome to GFG!");
}
Output: Welcome to GFG!
2. Applications
Rust is a memory-efficient and safe language with no overhead of runtime and garbage collection. It can be called a long-awaited successor of C++. And thus it’s used more in the production industry. It can also be integrated into many other programming languages. Talking about C++, it is very good at game development. It is powerful and is capable of interacting with the applications that use Docker, MongoDB, etc. But Dart itself is a web-based programming language with splendid libraries available. The addition of new features has enabled the increase of Flutter users and thereby Dart users. Therefore C++ can face a slight competition in this field.
3. Speed
C++ is a swift language compared to interpreted languages like Python and Java. This is one reason that has made it wide famous in competitive programming, where TLE(Time Limit Extended) is one common error found. Compiler technology has enabled this characteristic to the language. But still ineptly written code can run slow. Rust too is terribly fast, secure, and reasonable language stuffed with simple programming syntax. Whereas Dart is a flexible language that is easily shipped from one platform to another. It involves both compiler and interpreter technology and is speedier but not up to the rank of C++ and Rust.
4. Popularity
Cross-platform application development using Flutter has been growing considerably and has increased the number of Dart users. Also, it’s alterability and adaptability have accelerated its usage in the browser and server-side programming too. Rust can power performance-related services, can be integrated with other languages, and also uses void garbage collection. Thus it does not permit null pointers, dangling pointers, or data races in safe code. Having a syntax similar to C++, it was easy to learn and get adapted to the language. The availability of surplus libraries cheat codes and functions have not replaced the position of the C++ language from the hearts of programmers.
Conclusion:
Rust is a language that can be obviously called a ‘game-changer in the programming world’ where it avoids the problems that gnaws other garbage collectible languages like Golang, Java etc. Rust competes very well in performance and efficiency with the C and C++ world because it has made the debugging and problem solving easier. It can run on embedded devices and has the potential to even tickle the old Fortran language. Dart is a client-optimized language used in API development and in building mobile applications that require complex logic. It is in reality a concise and expressive language and is also more productive. So it is hard to decide on which language will bestride the other.
acassis
Dart
Difference Between
GBlog
Rust
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Flutter - DropDownButton Widget
Flutter - Custom Bottom Navigation Bar
Flutter - Checkbox Widget
Flutter - Row and Column Widgets
ListView Class in Flutter
Class method vs Static method in Python
Difference between BFS and DFS
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Differences between JDK, JRE and JVM
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n15 Feb, 2021"
},
{
"code": null,
"e": 347,
"s": 28,
"text": "Dennis M Ritchie developed C in the year 1972 as a successor of the B language. And it is widely used in the system as well as application programming. Its popularity has grown tremendously these years and now an object-oriented language derivative from C called C++ is becoming mature and stable programming language."
},
{
"code": null,
"e": 812,
"s": 347,
"text": "Rust is a system-level programming language that stand close to C++ in terms of syntax,but offers high speed and memory safety. On the other hand, Dart is an object-oriented, web-based programming language and is enriched with the features of a classical programming language where it runs on both server and browser. Now that the two superheroes have met each other, let’s hunt for their similarities and overlaps to decide who is going to dominate the C++ world."
},
{
"code": null,
"e": 900,
"s": 812,
"text": "1. Syntax: Let’s understand the basic syntactical differences by writing a simple code."
},
{
"code": null,
"e": 904,
"s": 900,
"text": "C++"
},
{
"code": null,
"e": 909,
"s": 904,
"text": "Dart"
},
{
"code": "#include <iostream>using namespace std; int main() { cout<<\"Welcome to GFG!\"; return 0;}",
"e": 1007,
"s": 909,
"text": null
},
{
"code": "void main() { print('Welcome to GFG!');}",
"e": 1049,
"s": 1007,
"text": null
},
{
"code": null,
"e": 1092,
"s": 1049,
"text": "Similarly, to print the same code in rust:"
},
{
"code": null,
"e": 1140,
"s": 1092,
"text": "fn main() {\n println!(\"Welcome to GFG!\");\n\n}\n"
},
{
"code": null,
"e": 1165,
"s": 1140,
"text": "Output: Welcome to GFG!\n"
},
{
"code": null,
"e": 1181,
"s": 1165,
"text": "2. Applications"
},
{
"code": null,
"e": 1840,
"s": 1181,
"text": "Rust is a memory-efficient and safe language with no overhead of runtime and garbage collection. It can be called a long-awaited successor of C++. And thus it’s used more in the production industry. It can also be integrated into many other programming languages. Talking about C++, it is very good at game development. It is powerful and is capable of interacting with the applications that use Docker, MongoDB, etc. But Dart itself is a web-based programming language with splendid libraries available. The addition of new features has enabled the increase of Flutter users and thereby Dart users. Therefore C++ can face a slight competition in this field."
},
{
"code": null,
"e": 1849,
"s": 1840,
"text": "3. Speed"
},
{
"code": null,
"e": 2474,
"s": 1849,
"text": "C++ is a swift language compared to interpreted languages like Python and Java. This is one reason that has made it wide famous in competitive programming, where TLE(Time Limit Extended) is one common error found. Compiler technology has enabled this characteristic to the language. But still ineptly written code can run slow. Rust too is terribly fast, secure, and reasonable language stuffed with simple programming syntax. Whereas Dart is a flexible language that is easily shipped from one platform to another. It involves both compiler and interpreter technology and is speedier but not up to the rank of C++ and Rust."
},
{
"code": null,
"e": 2488,
"s": 2474,
"text": "4. Popularity"
},
{
"code": null,
"e": 3174,
"s": 2488,
"text": "Cross-platform application development using Flutter has been growing considerably and has increased the number of Dart users. Also, it’s alterability and adaptability have accelerated its usage in the browser and server-side programming too. Rust can power performance-related services, can be integrated with other languages, and also uses void garbage collection. Thus it does not permit null pointers, dangling pointers, or data races in safe code. Having a syntax similar to C++, it was easy to learn and get adapted to the language. The availability of surplus libraries cheat codes and functions have not replaced the position of the C++ language from the hearts of programmers."
},
{
"code": null,
"e": 3186,
"s": 3174,
"text": "Conclusion:"
},
{
"code": null,
"e": 3882,
"s": 3186,
"text": "Rust is a language that can be obviously called a ‘game-changer in the programming world’ where it avoids the problems that gnaws other garbage collectible languages like Golang, Java etc. Rust competes very well in performance and efficiency with the C and C++ world because it has made the debugging and problem solving easier. It can run on embedded devices and has the potential to even tickle the old Fortran language. Dart is a client-optimized language used in API development and in building mobile applications that require complex logic. It is in reality a concise and expressive language and is also more productive. So it is hard to decide on which language will bestride the other."
},
{
"code": null,
"e": 3890,
"s": 3882,
"text": "acassis"
},
{
"code": null,
"e": 3895,
"s": 3890,
"text": "Dart"
},
{
"code": null,
"e": 3914,
"s": 3895,
"text": "Difference Between"
},
{
"code": null,
"e": 3920,
"s": 3914,
"text": "GBlog"
},
{
"code": null,
"e": 3925,
"s": 3920,
"text": "Rust"
},
{
"code": null,
"e": 4023,
"s": 3925,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4055,
"s": 4023,
"text": "Flutter - DropDownButton Widget"
},
{
"code": null,
"e": 4094,
"s": 4055,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 4120,
"s": 4094,
"text": "Flutter - Checkbox Widget"
},
{
"code": null,
"e": 4153,
"s": 4120,
"text": "Flutter - Row and Column Widgets"
},
{
"code": null,
"e": 4179,
"s": 4153,
"text": "ListView Class in Flutter"
},
{
"code": null,
"e": 4219,
"s": 4179,
"text": "Class method vs Static method in Python"
},
{
"code": null,
"e": 4250,
"s": 4219,
"text": "Difference between BFS and DFS"
},
{
"code": null,
"e": 4311,
"s": 4250,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 4379,
"s": 4311,
"text": "Difference Between Method Overloading and Method Overriding in Java"
}
] |
Django Sign Up and login with confirmation Email | Python
|
25 May, 2022
Django by default provides an authentication system configuration. User objects are the core of the authentication system.today we will implement Django’s authentication system.
Modules required :
django : django install
crispy_forms :
pip install --upgrade django-crispy-forms
Basic setup :Start a project by the following command –
django-admin startproject project
Change directory to project –
cd project
Start the server- Start the server by typing the following command in terminal –
python manage.py runserver
To check whether the server is running or not go to a web browser and enter http://127.0.0.1:8000/ as URL.Now stop the server by pressing
ctrl-c
Let’s create an app now called the “user”.
python manage.py startapp user
Goto user/ folder by doing: cd user and create a folder templates with files index.html, login.html, Email.html, register.html files.
Open the project folder using a text editor. The directory structure should look like this :
Now add the “user” app and “crispy_form” in your todo_site in settings.py, and add
CRISPY_TEMPLATE_PACK = 'bootstrap4'
at last of settings.py
configure email settings in setting.py:
place your email and password here.
Edit urls.py file in project :
Python3
from django.contrib import adminfrom django.urls import path, includefrom user import views as user_viewfrom django.contrib.auth import views as auth urlpatterns = [ path('admin/', admin.site.urls), ##### user related path########################## path('', include('user.urls')), path('login/', user_view.Login, name ='login'), path('logout/', auth.LogoutView.as_view(template_name ='user/index.html'), name ='logout'), path('register/', user_view.register, name ='register'), ]
Edit urls.py in user :
Python3
from django.urls import path, includefrom django.conf import settingsfrom . import viewsfrom django.conf.urls.static import static urlpatterns = [ path('', views.index, name ='index'),]
Edit views.py in user :
Python3
from django.shortcuts import render, redirectfrom django.contrib import messagesfrom django.contrib.auth import authenticate, loginfrom django.contrib.auth.decorators import login_requiredfrom django.contrib.auth.forms import AuthenticationFormfrom .forms import UserRegisterFormfrom django.core.mail import send_mailfrom django.core.mail import EmailMultiAlternativesfrom django.template.loader import get_templatefrom django.template import Context #################### index####################################### def index(request): return render(request, 'user/index.html', {'title':'index'}) ########### register here ##################################### def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') email = form.cleaned_data.get('email') ######################### mail system #################################### htmly = get_template('user/Email.html') d = { 'username': username } subject, from_email, to = 'welcome', '[email protected]', email html_content = htmly.render(d) msg = EmailMultiAlternatives(subject, html_content, from_email, [to]) msg.attach_alternative(html_content, "text/html") msg.send() ################################################################## messages.success(request, f'Your account has been created ! You are now able to log in') return redirect('login') else: form = UserRegisterForm() return render(request, 'user/register.html', {'form': form, 'title':'reqister here'}) ################ login forms################################################### def Login(request): if request.method == 'POST': # AuthenticationForm_can_also_be_used__ username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username = username, password = password) if user is not None: form = login(request, user) messages.success(request, f' wecome {username} !!') return redirect('index') else: messages.info(request, f'account done not exit plz sign in') form = AuthenticationForm() return render(request, 'user/login.html', {'form':form, 'title':'log in'})
Configure your email here.
Now create a forms.py in user :
Python3
from django import formsfrom django.contrib.auth.models import Userfrom django.contrib.auth.forms import UserCreationForm class UserRegisterForm(UserCreationForm): email = forms.EmailField() phone_no = forms.CharField(max_length = 20) first_name = forms.CharField(max_length = 20) last_name = forms.CharField(max_length = 20) class Meta: model = User fields = ['username', 'email', 'phone_no', 'password1', 'password2']
Navigate to templates/user/ and edit files :
link to index.html file
link to Email.html
link to login.html
link to register.html
Make migrations and migrate them.
python manage.py makemigrations
python manage.py migrate
Now you can run the server to see your app.
python manage.py runserver
udit5656
Django-Projects
Python Django
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n25 May, 2022"
},
{
"code": null,
"e": 231,
"s": 52,
"text": "Django by default provides an authentication system configuration. User objects are the core of the authentication system.today we will implement Django’s authentication system. "
},
{
"code": null,
"e": 251,
"s": 231,
"text": "Modules required : "
},
{
"code": null,
"e": 275,
"s": 251,
"text": "django : django install"
},
{
"code": null,
"e": 290,
"s": 275,
"text": "crispy_forms :"
},
{
"code": null,
"e": 332,
"s": 290,
"text": "pip install --upgrade django-crispy-forms"
},
{
"code": null,
"e": 388,
"s": 332,
"text": "Basic setup :Start a project by the following command –"
},
{
"code": null,
"e": 423,
"s": 388,
"text": " django-admin startproject project"
},
{
"code": null,
"e": 453,
"s": 423,
"text": "Change directory to project –"
},
{
"code": null,
"e": 465,
"s": 453,
"text": " cd project"
},
{
"code": null,
"e": 546,
"s": 465,
"text": "Start the server- Start the server by typing the following command in terminal –"
},
{
"code": null,
"e": 574,
"s": 546,
"text": " python manage.py runserver"
},
{
"code": null,
"e": 712,
"s": 574,
"text": "To check whether the server is running or not go to a web browser and enter http://127.0.0.1:8000/ as URL.Now stop the server by pressing"
},
{
"code": null,
"e": 719,
"s": 712,
"text": "ctrl-c"
},
{
"code": null,
"e": 763,
"s": 719,
"text": "Let’s create an app now called the “user”. "
},
{
"code": null,
"e": 794,
"s": 763,
"text": "python manage.py startapp user"
},
{
"code": null,
"e": 929,
"s": 794,
"text": "Goto user/ folder by doing: cd user and create a folder templates with files index.html, login.html, Email.html, register.html files. "
},
{
"code": null,
"e": 1023,
"s": 929,
"text": "Open the project folder using a text editor. The directory structure should look like this : "
},
{
"code": null,
"e": 1107,
"s": 1023,
"text": "Now add the “user” app and “crispy_form” in your todo_site in settings.py, and add "
},
{
"code": null,
"e": 1143,
"s": 1107,
"text": "CRISPY_TEMPLATE_PACK = 'bootstrap4'"
},
{
"code": null,
"e": 1168,
"s": 1143,
"text": "at last of settings.py "
},
{
"code": null,
"e": 1209,
"s": 1168,
"text": "configure email settings in setting.py: "
},
{
"code": null,
"e": 1246,
"s": 1209,
"text": "place your email and password here. "
},
{
"code": null,
"e": 1279,
"s": 1246,
"text": "Edit urls.py file in project : "
},
{
"code": null,
"e": 1287,
"s": 1279,
"text": "Python3"
},
{
"code": "from django.contrib import adminfrom django.urls import path, includefrom user import views as user_viewfrom django.contrib.auth import views as auth urlpatterns = [ path('admin/', admin.site.urls), ##### user related path########################## path('', include('user.urls')), path('login/', user_view.Login, name ='login'), path('logout/', auth.LogoutView.as_view(template_name ='user/index.html'), name ='logout'), path('register/', user_view.register, name ='register'), ]",
"e": 1792,
"s": 1287,
"text": null
},
{
"code": null,
"e": 1816,
"s": 1792,
"text": "Edit urls.py in user : "
},
{
"code": null,
"e": 1824,
"s": 1816,
"text": "Python3"
},
{
"code": "from django.urls import path, includefrom django.conf import settingsfrom . import viewsfrom django.conf.urls.static import static urlpatterns = [ path('', views.index, name ='index'),]",
"e": 2019,
"s": 1824,
"text": null
},
{
"code": null,
"e": 2043,
"s": 2019,
"text": "Edit views.py in user :"
},
{
"code": null,
"e": 2051,
"s": 2043,
"text": "Python3"
},
{
"code": "from django.shortcuts import render, redirectfrom django.contrib import messagesfrom django.contrib.auth import authenticate, loginfrom django.contrib.auth.decorators import login_requiredfrom django.contrib.auth.forms import AuthenticationFormfrom .forms import UserRegisterFormfrom django.core.mail import send_mailfrom django.core.mail import EmailMultiAlternativesfrom django.template.loader import get_templatefrom django.template import Context #################### index####################################### def index(request): return render(request, 'user/index.html', {'title':'index'}) ########### register here ##################################### def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') email = form.cleaned_data.get('email') ######################### mail system #################################### htmly = get_template('user/Email.html') d = { 'username': username } subject, from_email, to = 'welcome', '[email protected]', email html_content = htmly.render(d) msg = EmailMultiAlternatives(subject, html_content, from_email, [to]) msg.attach_alternative(html_content, \"text/html\") msg.send() ################################################################## messages.success(request, f'Your account has been created ! You are now able to log in') return redirect('login') else: form = UserRegisterForm() return render(request, 'user/register.html', {'form': form, 'title':'reqister here'}) ################ login forms################################################### def Login(request): if request.method == 'POST': # AuthenticationForm_can_also_be_used__ username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username = username, password = password) if user is not None: form = login(request, user) messages.success(request, f' wecome {username} !!') return redirect('index') else: messages.info(request, f'account done not exit plz sign in') form = AuthenticationForm() return render(request, 'user/login.html', {'form':form, 'title':'log in'})",
"e": 4498,
"s": 2051,
"text": null
},
{
"code": null,
"e": 4526,
"s": 4498,
"text": "Configure your email here. "
},
{
"code": null,
"e": 4558,
"s": 4526,
"text": "Now create a forms.py in user :"
},
{
"code": null,
"e": 4566,
"s": 4558,
"text": "Python3"
},
{
"code": "from django import formsfrom django.contrib.auth.models import Userfrom django.contrib.auth.forms import UserCreationForm class UserRegisterForm(UserCreationForm): email = forms.EmailField() phone_no = forms.CharField(max_length = 20) first_name = forms.CharField(max_length = 20) last_name = forms.CharField(max_length = 20) class Meta: model = User fields = ['username', 'email', 'phone_no', 'password1', 'password2']",
"e": 5020,
"s": 4566,
"text": null
},
{
"code": null,
"e": 5066,
"s": 5020,
"text": "Navigate to templates/user/ and edit files : "
},
{
"code": null,
"e": 5090,
"s": 5066,
"text": "link to index.html file"
},
{
"code": null,
"e": 5109,
"s": 5090,
"text": "link to Email.html"
},
{
"code": null,
"e": 5128,
"s": 5109,
"text": "link to login.html"
},
{
"code": null,
"e": 5150,
"s": 5128,
"text": "link to register.html"
},
{
"code": null,
"e": 5185,
"s": 5150,
"text": "Make migrations and migrate them. "
},
{
"code": null,
"e": 5242,
"s": 5185,
"text": "python manage.py makemigrations\npython manage.py migrate"
},
{
"code": null,
"e": 5286,
"s": 5242,
"text": "Now you can run the server to see your app."
},
{
"code": null,
"e": 5313,
"s": 5286,
"text": "python manage.py runserver"
},
{
"code": null,
"e": 5326,
"s": 5317,
"text": "udit5656"
},
{
"code": null,
"e": 5342,
"s": 5326,
"text": "Django-Projects"
},
{
"code": null,
"e": 5356,
"s": 5342,
"text": "Python Django"
},
{
"code": null,
"e": 5363,
"s": 5356,
"text": "Python"
}
] |
Python infinity
|
10 Sep, 2021
As ironic as it may seem infinity is defined as an undefined number that can either be a positive or negative value. All arithmetic operations performed on an infinite value always lead to an infinite number, say it be sum, subtraction, multiplication, or any other operation.In the world of computer science, infinity is generally used to measure performance and optimize algorithms that perform computations on a large scale application.
Representing infinity as an Integer in pythonThe concept of representing infinity as an integer violates the definition of infinity itself. As of 2020, there is no such way to represent infinity as an integer in any programming language so far. But in python, as it is a dynamic language, float values can be used to represent an infinite integer. One can use float(‘inf’) as an integer to represent it as infinity. Below is the list of ways one can represent infinity in Python.
1. Using float(‘inf’) and float(‘-inf’):
As infinity can be both positive and negative they can be represented as a float(‘inf’) and float(‘-inf’) respectively. The below code shows the implementation of the above-discussed content:
Python3
# Defining a positive infinite integerpositive_infinity = float('inf')print('Positive Infinity: ', positive_infinity) # Defining a negative infinite integernegative_infinity = float('-inf')print('Negative Infinity: ', negative_infinity)
Output:
Positive Infinity: inf
Negative Infinity: -inf
2. using Python’s math module:
Python’s math module can also be used for representing infinite integers. The below code shows how it is done:
Python3
import math # Defining a positive infinite integerpositive_infinity = math.infprint('Positive Infinity: ', positive_infinity) # Defining a negative infinite integernegative_infinity = -math.infprint('Negative Infinity: ', negative_infinity)
Output:
Positive Infinity: inf
Negative Infinity: -inf
3. using Python’s decimal module:
Python’s decimal module can also be used for representing infinite float values. It is used as Decimal(‘Infinity’) for positive and Decimal(‘-Infinity’) for negative infinite value.
The below code shows its implementation:
Python3
from decimal import Decimal # Defining a positive infinite integerpositive_infinity = Decimal('Infinity')print('Positive Infinity: ', positive_infinity) # Defining a negative infinite integernegative_infinity = Decimal('-Infinity')print('Negative Infinity: ', negative_infinity)
Output:
Positive Infinity: Infinity
Negative Infinity: -Infinity
4. using Python’s Numpy library:
Python’s Numpy module can also be used for representing infinite values. It is used as np.inf for positive and -np.inf for negative infinite value. The use of Numpy library for representing an infinite value is shown in the code below:
Python3
import numpy as np # Defining a positive infinite integerpositive_infinity = np.infprint('Positive Infinity: ', positive_infinity) # Defining a negative infinite integernegative_infinity = -np.infprint('Negative Infinity: ', negative_infinity)
Output:
Positive Infinity: inf
Negative Infinity: -inf
Checking If a Number Is Infinite in PythonTo check if a given number is infinite or not, one can use isinf() method of the math library which returns a boolean value. The below code shows the use of isinf() method:
Python3
import numpy as npimport math # Defining a positive infinite integera = np.inf # Defining a negative infinite integerb = -np.inf # Define a finite integerc = 300 # check if a in infiniteprint(math.isinf(a)) # check if b in infiniteprint(math.isinf(b)) # check if c in infiniteprint(math.isinf(c))
Output:
True
True
False
Comparing infinite values to finite values in python The concept of comparing an infinite value to finite values is as simple as it gets. As positive infinity is always bigger than every natural number and negative infinity is always smaller than negative numbers. For better understanding look into the code below:
Python3
import numpy as np # Defining a positive infinite integera = np.inf # Defining a negative infinite integerb = -np.inf # Define a finite + ve integerc = 300 # Define a finite -ve integerd = -300 # helper function to make comparisonsdef compare(x, y): if x>y: print("True") else: print("False") compare(a, b)compare(a, c)compare(a, d)compare(b, c)compare(b, d)
Output:
True
True
True
False
False
akshaysingh98088
rs1686740
adnanirshad158
Python math-library
python-basics
Python
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n10 Sep, 2021"
},
{
"code": null,
"e": 492,
"s": 52,
"text": "As ironic as it may seem infinity is defined as an undefined number that can either be a positive or negative value. All arithmetic operations performed on an infinite value always lead to an infinite number, say it be sum, subtraction, multiplication, or any other operation.In the world of computer science, infinity is generally used to measure performance and optimize algorithms that perform computations on a large scale application."
},
{
"code": null,
"e": 973,
"s": 492,
"text": "Representing infinity as an Integer in pythonThe concept of representing infinity as an integer violates the definition of infinity itself. As of 2020, there is no such way to represent infinity as an integer in any programming language so far. But in python, as it is a dynamic language, float values can be used to represent an infinite integer. One can use float(‘inf’) as an integer to represent it as infinity. Below is the list of ways one can represent infinity in Python. "
},
{
"code": null,
"e": 1014,
"s": 973,
"text": "1. Using float(‘inf’) and float(‘-inf’):"
},
{
"code": null,
"e": 1206,
"s": 1014,
"text": "As infinity can be both positive and negative they can be represented as a float(‘inf’) and float(‘-inf’) respectively. The below code shows the implementation of the above-discussed content:"
},
{
"code": null,
"e": 1214,
"s": 1206,
"text": "Python3"
},
{
"code": "# Defining a positive infinite integerpositive_infinity = float('inf')print('Positive Infinity: ', positive_infinity) # Defining a negative infinite integernegative_infinity = float('-inf')print('Negative Infinity: ', negative_infinity)",
"e": 1451,
"s": 1214,
"text": null
},
{
"code": null,
"e": 1460,
"s": 1451,
"text": "Output: "
},
{
"code": null,
"e": 1509,
"s": 1460,
"text": "Positive Infinity: inf\nNegative Infinity: -inf"
},
{
"code": null,
"e": 1540,
"s": 1509,
"text": "2. using Python’s math module:"
},
{
"code": null,
"e": 1652,
"s": 1540,
"text": "Python’s math module can also be used for representing infinite integers. The below code shows how it is done: "
},
{
"code": null,
"e": 1660,
"s": 1652,
"text": "Python3"
},
{
"code": "import math # Defining a positive infinite integerpositive_infinity = math.infprint('Positive Infinity: ', positive_infinity) # Defining a negative infinite integernegative_infinity = -math.infprint('Negative Infinity: ', negative_infinity)",
"e": 1901,
"s": 1660,
"text": null
},
{
"code": null,
"e": 1910,
"s": 1901,
"text": "Output: "
},
{
"code": null,
"e": 1959,
"s": 1910,
"text": "Positive Infinity: inf\nNegative Infinity: -inf"
},
{
"code": null,
"e": 1993,
"s": 1959,
"text": "3. using Python’s decimal module:"
},
{
"code": null,
"e": 2176,
"s": 1993,
"text": "Python’s decimal module can also be used for representing infinite float values. It is used as Decimal(‘Infinity’) for positive and Decimal(‘-Infinity’) for negative infinite value. "
},
{
"code": null,
"e": 2219,
"s": 2176,
"text": "The below code shows its implementation: "
},
{
"code": null,
"e": 2227,
"s": 2219,
"text": "Python3"
},
{
"code": "from decimal import Decimal # Defining a positive infinite integerpositive_infinity = Decimal('Infinity')print('Positive Infinity: ', positive_infinity) # Defining a negative infinite integernegative_infinity = Decimal('-Infinity')print('Negative Infinity: ', negative_infinity)",
"e": 2506,
"s": 2227,
"text": null
},
{
"code": null,
"e": 2515,
"s": 2506,
"text": "Output: "
},
{
"code": null,
"e": 2574,
"s": 2515,
"text": "Positive Infinity: Infinity\nNegative Infinity: -Infinity"
},
{
"code": null,
"e": 2607,
"s": 2574,
"text": "4. using Python’s Numpy library:"
},
{
"code": null,
"e": 2844,
"s": 2607,
"text": "Python’s Numpy module can also be used for representing infinite values. It is used as np.inf for positive and -np.inf for negative infinite value. The use of Numpy library for representing an infinite value is shown in the code below: "
},
{
"code": null,
"e": 2852,
"s": 2844,
"text": "Python3"
},
{
"code": "import numpy as np # Defining a positive infinite integerpositive_infinity = np.infprint('Positive Infinity: ', positive_infinity) # Defining a negative infinite integernegative_infinity = -np.infprint('Negative Infinity: ', negative_infinity)",
"e": 3096,
"s": 2852,
"text": null
},
{
"code": null,
"e": 3105,
"s": 3096,
"text": "Output: "
},
{
"code": null,
"e": 3154,
"s": 3105,
"text": "Positive Infinity: inf\nNegative Infinity: -inf"
},
{
"code": null,
"e": 3370,
"s": 3154,
"text": "Checking If a Number Is Infinite in PythonTo check if a given number is infinite or not, one can use isinf() method of the math library which returns a boolean value. The below code shows the use of isinf() method: "
},
{
"code": null,
"e": 3378,
"s": 3370,
"text": "Python3"
},
{
"code": "import numpy as npimport math # Defining a positive infinite integera = np.inf # Defining a negative infinite integerb = -np.inf # Define a finite integerc = 300 # check if a in infiniteprint(math.isinf(a)) # check if b in infiniteprint(math.isinf(b)) # check if c in infiniteprint(math.isinf(c))",
"e": 3675,
"s": 3378,
"text": null
},
{
"code": null,
"e": 3684,
"s": 3675,
"text": "Output: "
},
{
"code": null,
"e": 3700,
"s": 3684,
"text": "True\nTrue\nFalse"
},
{
"code": null,
"e": 4017,
"s": 3700,
"text": "Comparing infinite values to finite values in python The concept of comparing an infinite value to finite values is as simple as it gets. As positive infinity is always bigger than every natural number and negative infinity is always smaller than negative numbers. For better understanding look into the code below: "
},
{
"code": null,
"e": 4025,
"s": 4017,
"text": "Python3"
},
{
"code": "import numpy as np # Defining a positive infinite integera = np.inf # Defining a negative infinite integerb = -np.inf # Define a finite + ve integerc = 300 # Define a finite -ve integerd = -300 # helper function to make comparisonsdef compare(x, y): if x>y: print(\"True\") else: print(\"False\") compare(a, b)compare(a, c)compare(a, d)compare(b, c)compare(b, d)",
"e": 4413,
"s": 4025,
"text": null
},
{
"code": null,
"e": 4422,
"s": 4413,
"text": "Output: "
},
{
"code": null,
"e": 4449,
"s": 4422,
"text": "True\nTrue\nTrue\nFalse\nFalse"
},
{
"code": null,
"e": 4468,
"s": 4451,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 4478,
"s": 4468,
"text": "rs1686740"
},
{
"code": null,
"e": 4493,
"s": 4478,
"text": "adnanirshad158"
},
{
"code": null,
"e": 4513,
"s": 4493,
"text": "Python math-library"
},
{
"code": null,
"e": 4527,
"s": 4513,
"text": "python-basics"
},
{
"code": null,
"e": 4534,
"s": 4527,
"text": "Python"
},
{
"code": null,
"e": 4550,
"s": 4534,
"text": "Write From Home"
}
] |
Find index of closing bracket for a given opening bracket in an expression
|
10 Jan, 2019
Given a string with brackets. If the start index of the open bracket is given, find the index of the closing bracket.
Examples:
Input : string = [ABC[23]][89]
index = 0
Output : 8
The opening bracket at index 0 corresponds
to closing bracket at index 8.
The idea is to use Stack data structure. We traverse given expression from given index and keep pushing starting brackets. Whenever we encounter a closing bracket, we pop a starting bracket. If stack becomes empty at any moment, we return that index.
C++
Java
Python
C#
// CPP program to find index of closing// bracket for given opening bracket.#include <bits/stdc++.h>using namespace std; // Function to find index of closing// bracket for given opening bracket.void test(string expression, int index){ int i; // If index given is invalid and is // not an opening bracket. if(expression[index]!='['){ cout << expression << ", " << index << ": -1\n"; return; } // Stack to store opening brackets. stack <int> st; // Traverse through string starting from // given index. for(i = index; i < expression.length(); i++){ // If current character is an // opening bracket push it in stack. if(expression[i] == '[') st.push(expression[i]); // If current character is a closing // bracket, pop from stack. If stack // is empty, then this closing // bracket is required bracket. else if(expression[i] == ']'){ st.pop(); if(st.empty()){ cout << expression << ", " << index << ": " << i << "\n"; return; } } } // If no matching closing bracket // is found. cout << expression << ", " << index << ": -1\n";} // Driver Codeint main() { test("[ABC[23]][89]", 0); // should be 8 test("[ABC[23]][89]", 4); // should be 7 test("[ABC[23]][89]", 9); // should be 12 test("[ABC[23]][89]", 1); // No matching bracket return 0;} // This code is contributed by Nikhil Jindal.
// Java program to find index of closing // bracket for given opening bracket. import java.util.Stack;class GFG { // Function to find index of closing // bracket for given opening bracket. static void test(String expression, int index) { int i; // If index given is invalid and is // not an opening bracket. if (expression.charAt(index) != '[') { System.out.print(expression + ", " + index + ": -1\n"); return; } // Stack to store opening brackets. Stack<Integer> st = new Stack<>(); // Traverse through string starting from // given index. for (i = index; i < expression.length(); i++) { // If current character is an // opening bracket push it in stack. if (expression.charAt(i) == '[') { st.push((int) expression.charAt(i)); } // If current character is a closing // bracket, pop from stack. If stack // is empty, then this closing // bracket is required bracket. else if (expression.charAt(i) == ']') { st.pop(); if (st.empty()) { System.out.print(expression + ", " + index + ": " + i + "\n"); return; } } } // If no matching closing bracket // is found. System.out.print(expression + ", " + index + ": -1\n"); } // Driver Code public static void main(String[] args) { test("[ABC[23]][89]", 0); // should be 8 test("[ABC[23]][89]", 4); // should be 7 test("[ABC[23]][89]", 9); // should be 12 test("[ABC[23]][89]", 1); // No matching bracket }// this code is contributed by Rajput-Ji}
# Python program to find index of closing# bracket for a given opening bracket.from collections import deque def getIndex(s, i): # If input is invalid. if s[i] != '[': return -1 # Create a deque to use it as a stack. d = deque() # Traverse through all elements # starting from i. for k in range(i, len(s)): # Pop a starting bracket # for every closing bracket if s[k] == ']': d.popleft() # Push all starting brackets elif s[k] == '[': d.append(s[i]) # If deque becomes empty if not d: return k return -1 # Driver code to test above method.def test(s, i): matching_index = getIndex(s, i) print(s + ", " + str(i) + ": " + str(matching_index)) def main(): test("[ABC[23]][89]", 0) # should be 8 test("[ABC[23]][89]", 4) # should be 7 test("[ABC[23]][89]", 9) # should be 12 test("[ABC[23]][89]", 1) # No matching bracket if __name__ == "__main__": main()
// C# program to find index of closing // bracket for given opening bracket. using System;using System.Collections;public class GFG { // Function to find index of closing // bracket for given opening bracket. static void test(String expression, int index) { int i; // If index given is invalid and is // not an opening bracket. if (expression[index] != '[') { Console.Write(expression + ", " + index + ": -1\n"); return; } // Stack to store opening brackets. Stack st = new Stack(); // Traverse through string starting from // given index. for (i = index; i < expression.Length; i++) { // If current character is an // opening bracket push it in stack. if (expression[i] == '[') { st.Push((int) expression[i]); } // If current character is a closing // bracket, pop from stack. If stack // is empty, then this closing // bracket is required bracket. else if (expression[i] == ']') { st.Pop(); if (st.Count==0) { Console.Write(expression + ", " + index + ": " + i + "\n"); return; } } } // If no matching closing bracket // is found. Console.Write(expression + ", " + index + ": -1\n"); } // Driver Code public static void Main() { test("[ABC[23]][89]", 0); // should be 8 test("[ABC[23]][89]", 4); // should be 7 test("[ABC[23]][89]", 9); // should be 12 test("[ABC[23]][89]", 1); // No matching bracket } } // This code is contributed by 29AjayKumar
Output:
[ABC[23]][89], 0: 8
[ABC[23]][89], 4: 7
[ABC[23]][89], 9: 12
[ABC[23]][89], 1: -1
Time Complexity: O(n)Auxiliary Space: O(n)
nik1996
Rajput-Ji
29AjayKumar
Stack
Strings
Strings
Stack
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n10 Jan, 2019"
},
{
"code": null,
"e": 170,
"s": 52,
"text": "Given a string with brackets. If the start index of the open bracket is given, find the index of the closing bracket."
},
{
"code": null,
"e": 180,
"s": 170,
"text": "Examples:"
},
{
"code": null,
"e": 315,
"s": 180,
"text": "Input : string = [ABC[23]][89]\n index = 0\nOutput : 8\nThe opening bracket at index 0 corresponds\nto closing bracket at index 8.\n"
},
{
"code": null,
"e": 566,
"s": 315,
"text": "The idea is to use Stack data structure. We traverse given expression from given index and keep pushing starting brackets. Whenever we encounter a closing bracket, we pop a starting bracket. If stack becomes empty at any moment, we return that index."
},
{
"code": null,
"e": 570,
"s": 566,
"text": "C++"
},
{
"code": null,
"e": 575,
"s": 570,
"text": "Java"
},
{
"code": null,
"e": 582,
"s": 575,
"text": "Python"
},
{
"code": null,
"e": 585,
"s": 582,
"text": "C#"
},
{
"code": "// CPP program to find index of closing// bracket for given opening bracket.#include <bits/stdc++.h>using namespace std; // Function to find index of closing// bracket for given opening bracket.void test(string expression, int index){ int i; // If index given is invalid and is // not an opening bracket. if(expression[index]!='['){ cout << expression << \", \" << index << \": -1\\n\"; return; } // Stack to store opening brackets. stack <int> st; // Traverse through string starting from // given index. for(i = index; i < expression.length(); i++){ // If current character is an // opening bracket push it in stack. if(expression[i] == '[') st.push(expression[i]); // If current character is a closing // bracket, pop from stack. If stack // is empty, then this closing // bracket is required bracket. else if(expression[i] == ']'){ st.pop(); if(st.empty()){ cout << expression << \", \" << index << \": \" << i << \"\\n\"; return; } } } // If no matching closing bracket // is found. cout << expression << \", \" << index << \": -1\\n\";} // Driver Codeint main() { test(\"[ABC[23]][89]\", 0); // should be 8 test(\"[ABC[23]][89]\", 4); // should be 7 test(\"[ABC[23]][89]\", 9); // should be 12 test(\"[ABC[23]][89]\", 1); // No matching bracket return 0;} // This code is contributed by Nikhil Jindal.",
"e": 2181,
"s": 585,
"text": null
},
{
"code": "// Java program to find index of closing // bracket for given opening bracket. import java.util.Stack;class GFG { // Function to find index of closing // bracket for given opening bracket. static void test(String expression, int index) { int i; // If index given is invalid and is // not an opening bracket. if (expression.charAt(index) != '[') { System.out.print(expression + \", \" + index + \": -1\\n\"); return; } // Stack to store opening brackets. Stack<Integer> st = new Stack<>(); // Traverse through string starting from // given index. for (i = index; i < expression.length(); i++) { // If current character is an // opening bracket push it in stack. if (expression.charAt(i) == '[') { st.push((int) expression.charAt(i)); } // If current character is a closing // bracket, pop from stack. If stack // is empty, then this closing // bracket is required bracket. else if (expression.charAt(i) == ']') { st.pop(); if (st.empty()) { System.out.print(expression + \", \" + index + \": \" + i + \"\\n\"); return; } } } // If no matching closing bracket // is found. System.out.print(expression + \", \" + index + \": -1\\n\"); } // Driver Code public static void main(String[] args) { test(\"[ABC[23]][89]\", 0); // should be 8 test(\"[ABC[23]][89]\", 4); // should be 7 test(\"[ABC[23]][89]\", 9); // should be 12 test(\"[ABC[23]][89]\", 1); // No matching bracket }// this code is contributed by Rajput-Ji}",
"e": 4019,
"s": 2181,
"text": null
},
{
"code": "# Python program to find index of closing# bracket for a given opening bracket.from collections import deque def getIndex(s, i): # If input is invalid. if s[i] != '[': return -1 # Create a deque to use it as a stack. d = deque() # Traverse through all elements # starting from i. for k in range(i, len(s)): # Pop a starting bracket # for every closing bracket if s[k] == ']': d.popleft() # Push all starting brackets elif s[k] == '[': d.append(s[i]) # If deque becomes empty if not d: return k return -1 # Driver code to test above method.def test(s, i): matching_index = getIndex(s, i) print(s + \", \" + str(i) + \": \" + str(matching_index)) def main(): test(\"[ABC[23]][89]\", 0) # should be 8 test(\"[ABC[23]][89]\", 4) # should be 7 test(\"[ABC[23]][89]\", 9) # should be 12 test(\"[ABC[23]][89]\", 1) # No matching bracket if __name__ == \"__main__\": main()",
"e": 5023,
"s": 4019,
"text": null
},
{
"code": "// C# program to find index of closing // bracket for given opening bracket. using System;using System.Collections;public class GFG { // Function to find index of closing // bracket for given opening bracket. static void test(String expression, int index) { int i; // If index given is invalid and is // not an opening bracket. if (expression[index] != '[') { Console.Write(expression + \", \" + index + \": -1\\n\"); return; } // Stack to store opening brackets. Stack st = new Stack(); // Traverse through string starting from // given index. for (i = index; i < expression.Length; i++) { // If current character is an // opening bracket push it in stack. if (expression[i] == '[') { st.Push((int) expression[i]); } // If current character is a closing // bracket, pop from stack. If stack // is empty, then this closing // bracket is required bracket. else if (expression[i] == ']') { st.Pop(); if (st.Count==0) { Console.Write(expression + \", \" + index + \": \" + i + \"\\n\"); return; } } } // If no matching closing bracket // is found. Console.Write(expression + \", \" + index + \": -1\\n\"); } // Driver Code public static void Main() { test(\"[ABC[23]][89]\", 0); // should be 8 test(\"[ABC[23]][89]\", 4); // should be 7 test(\"[ABC[23]][89]\", 9); // should be 12 test(\"[ABC[23]][89]\", 1); // No matching bracket } } // This code is contributed by 29AjayKumar ",
"e": 6849,
"s": 5023,
"text": null
},
{
"code": null,
"e": 6857,
"s": 6849,
"text": "Output:"
},
{
"code": null,
"e": 6940,
"s": 6857,
"text": "[ABC[23]][89], 0: 8\n[ABC[23]][89], 4: 7\n[ABC[23]][89], 9: 12\n[ABC[23]][89], 1: -1\n"
},
{
"code": null,
"e": 6983,
"s": 6940,
"text": "Time Complexity: O(n)Auxiliary Space: O(n)"
},
{
"code": null,
"e": 6991,
"s": 6983,
"text": "nik1996"
},
{
"code": null,
"e": 7001,
"s": 6991,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 7013,
"s": 7001,
"text": "29AjayKumar"
},
{
"code": null,
"e": 7019,
"s": 7013,
"text": "Stack"
},
{
"code": null,
"e": 7027,
"s": 7019,
"text": "Strings"
},
{
"code": null,
"e": 7035,
"s": 7027,
"text": "Strings"
},
{
"code": null,
"e": 7041,
"s": 7035,
"text": "Stack"
}
] |
How to play an Audio file using Java
|
03 Jul, 2022
In this article we will see, how can we play an audio file in pure java, here pure means, we are not going to use any external library. You can create your own music player by the help of this article. Java inbuilt libraries support only AIFC, AIFF, AU, SND and WAVE formats.There are 2 different interfaces which can be used for this purpose Clip and SourceDataLine. In this article, we will discuss playing audio file using Clip only and see the various methods of clip. We will cover following operations:
Start.Pause.Resume.Restart.StopJump to a specific position of playback.
Start.
Pause.
Resume.
Restart.
Stop
Jump to a specific position of playback.
Play Audio using Clip
Clip is a java interface available in javax.sound.sampled package and introduced in Java7.Following steps are to be followed to play a clip object.
Create an object of AudioInputStream by using AudioSystem.getAudioInputStream(File file). AudioInputStream converts an audio file into stream.Get a clip reference object from AudioSystem.Stream an audio input stream from which audio data will be read into the clip by using open() method of Clip interface.Set the required properties to the clip like frame position, loop, microsecond position.Start the clip
Create an object of AudioInputStream by using AudioSystem.getAudioInputStream(File file). AudioInputStream converts an audio file into stream.
Get a clip reference object from AudioSystem.
Stream an audio input stream from which audio data will be read into the clip by using open() method of Clip interface.
Set the required properties to the clip like frame position, loop, microsecond position.
Start the clip
// Java program to play an Audio// file using Clip Objectimport java.io.File;import java.io.IOException;import java.util.Scanner; import javax.sound.sampled.AudioInputStream;import javax.sound.sampled.AudioSystem;import javax.sound.sampled.Clip;import javax.sound.sampled.LineUnavailableException;import javax.sound.sampled.UnsupportedAudioFileException; public class SimpleAudioPlayer { // to store current position Long currentFrame; Clip clip; // current status of clip String status; AudioInputStream audioInputStream; static String filePath; // constructor to initialize streams and clip public SimpleAudioPlayer() throws UnsupportedAudioFileException, IOException, LineUnavailableException { // create AudioInputStream object audioInputStream = AudioSystem.getAudioInputStream(new File(filePath).getAbsoluteFile()); // create clip reference clip = AudioSystem.getClip(); // open audioInputStream to the clip clip.open(audioInputStream); clip.loop(Clip.LOOP_CONTINUOUSLY); } public static void main(String[] args) { try { filePath = "Your path for the file"; SimpleAudioPlayer audioPlayer = new SimpleAudioPlayer(); audioPlayer.play(); Scanner sc = new Scanner(System.in); while (true) { System.out.println("1. pause"); System.out.println("2. resume"); System.out.println("3. restart"); System.out.println("4. stop"); System.out.println("5. Jump to specific time"); int c = sc.nextInt(); audioPlayer.gotoChoice(c); if (c == 4) break; } sc.close(); } catch (Exception ex) { System.out.println("Error with playing sound."); ex.printStackTrace(); } } // Work as the user enters his choice private void gotoChoice(int c) throws IOException, LineUnavailableException, UnsupportedAudioFileException { switch (c) { case 1: pause(); break; case 2: resumeAudio(); break; case 3: restart(); break; case 4: stop(); break; case 5: System.out.println("Enter time (" + 0 + ", " + clip.getMicrosecondLength() + ")"); Scanner sc = new Scanner(System.in); long c1 = sc.nextLong(); jump(c1); break; } } // Method to play the audio public void play() { //start the clip clip.start(); status = "play"; } // Method to pause the audio public void pause() { if (status.equals("paused")) { System.out.println("audio is already paused"); return; } this.currentFrame = this.clip.getMicrosecondPosition(); clip.stop(); status = "paused"; } // Method to resume the audio public void resumeAudio() throws UnsupportedAudioFileException, IOException, LineUnavailableException { if (status.equals("play")) { System.out.println("Audio is already "+ "being played"); return; } clip.close(); resetAudioStream(); clip.setMicrosecondPosition(currentFrame); this.play(); } // Method to restart the audio public void restart() throws IOException, LineUnavailableException, UnsupportedAudioFileException { clip.stop(); clip.close(); resetAudioStream(); currentFrame = 0L; clip.setMicrosecondPosition(0); this.play(); } // Method to stop the audio public void stop() throws UnsupportedAudioFileException, IOException, LineUnavailableException { currentFrame = 0L; clip.stop(); clip.close(); } // Method to jump over a specific part public void jump(long c) throws UnsupportedAudioFileException, IOException, LineUnavailableException { if (c > 0 && c < clip.getMicrosecondLength()) { clip.stop(); clip.close(); resetAudioStream(); currentFrame = c; clip.setMicrosecondPosition(c); this.play(); } } // Method to reset audio stream public void resetAudioStream() throws UnsupportedAudioFileException, IOException, LineUnavailableException { audioInputStream = AudioSystem.getAudioInputStream( new File(filePath).getAbsoluteFile()); clip.open(audioInputStream); clip.loop(Clip.LOOP_CONTINUOUSLY); } }
In above program we have used AudioInputStream which is a class in Java to read audio file as a stream. Like every stream of java if it is to be used again it has to be reset.
To pause the playback we have to stop the player and store the current frame in an object. So that while resuming we can use it. When resuming we just have to play again the player from the last position we left.clip.getMicrosecondPosition() method returns the current position of audio and clip.setMicrosecondPosition(long position) sets the current position of audio.
To stop the playback, you must have to close the clip otherwise it will remain open. I have also used clip.loop(Clip.LOOP_CONTINOUSLY) for testing. Because wav files are generally small so I have played mine in a loop.
Important Points:
Always close your opened stream and resources before exiting the program.You have to stop the clip before playing it again. So keep proper checks.If AudioInputStream is to be used again, it has to be reset.
Always close your opened stream and resources before exiting the program.
You have to stop the clip before playing it again. So keep proper checks.
If AudioInputStream is to be used again, it has to be reset.
This article is contributed by Vishal Garg. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
java-file-handling
Java-Library
java-puzzle
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
Stream In Java
Collections in Java
Singleton Class in Java
Multidimensional Arrays in Java
Set in Java
Stack Class in Java
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n03 Jul, 2022"
},
{
"code": null,
"e": 561,
"s": 52,
"text": "In this article we will see, how can we play an audio file in pure java, here pure means, we are not going to use any external library. You can create your own music player by the help of this article. Java inbuilt libraries support only AIFC, AIFF, AU, SND and WAVE formats.There are 2 different interfaces which can be used for this purpose Clip and SourceDataLine. In this article, we will discuss playing audio file using Clip only and see the various methods of clip. We will cover following operations:"
},
{
"code": null,
"e": 633,
"s": 561,
"text": "Start.Pause.Resume.Restart.StopJump to a specific position of playback."
},
{
"code": null,
"e": 640,
"s": 633,
"text": "Start."
},
{
"code": null,
"e": 647,
"s": 640,
"text": "Pause."
},
{
"code": null,
"e": 655,
"s": 647,
"text": "Resume."
},
{
"code": null,
"e": 664,
"s": 655,
"text": "Restart."
},
{
"code": null,
"e": 669,
"s": 664,
"text": "Stop"
},
{
"code": null,
"e": 710,
"s": 669,
"text": "Jump to a specific position of playback."
},
{
"code": null,
"e": 732,
"s": 710,
"text": "Play Audio using Clip"
},
{
"code": null,
"e": 880,
"s": 732,
"text": "Clip is a java interface available in javax.sound.sampled package and introduced in Java7.Following steps are to be followed to play a clip object."
},
{
"code": null,
"e": 1289,
"s": 880,
"text": "Create an object of AudioInputStream by using AudioSystem.getAudioInputStream(File file). AudioInputStream converts an audio file into stream.Get a clip reference object from AudioSystem.Stream an audio input stream from which audio data will be read into the clip by using open() method of Clip interface.Set the required properties to the clip like frame position, loop, microsecond position.Start the clip"
},
{
"code": null,
"e": 1432,
"s": 1289,
"text": "Create an object of AudioInputStream by using AudioSystem.getAudioInputStream(File file). AudioInputStream converts an audio file into stream."
},
{
"code": null,
"e": 1478,
"s": 1432,
"text": "Get a clip reference object from AudioSystem."
},
{
"code": null,
"e": 1598,
"s": 1478,
"text": "Stream an audio input stream from which audio data will be read into the clip by using open() method of Clip interface."
},
{
"code": null,
"e": 1687,
"s": 1598,
"text": "Set the required properties to the clip like frame position, loop, microsecond position."
},
{
"code": null,
"e": 1702,
"s": 1687,
"text": "Start the clip"
},
{
"code": "// Java program to play an Audio// file using Clip Objectimport java.io.File;import java.io.IOException;import java.util.Scanner; import javax.sound.sampled.AudioInputStream;import javax.sound.sampled.AudioSystem;import javax.sound.sampled.Clip;import javax.sound.sampled.LineUnavailableException;import javax.sound.sampled.UnsupportedAudioFileException; public class SimpleAudioPlayer { // to store current position Long currentFrame; Clip clip; // current status of clip String status; AudioInputStream audioInputStream; static String filePath; // constructor to initialize streams and clip public SimpleAudioPlayer() throws UnsupportedAudioFileException, IOException, LineUnavailableException { // create AudioInputStream object audioInputStream = AudioSystem.getAudioInputStream(new File(filePath).getAbsoluteFile()); // create clip reference clip = AudioSystem.getClip(); // open audioInputStream to the clip clip.open(audioInputStream); clip.loop(Clip.LOOP_CONTINUOUSLY); } public static void main(String[] args) { try { filePath = \"Your path for the file\"; SimpleAudioPlayer audioPlayer = new SimpleAudioPlayer(); audioPlayer.play(); Scanner sc = new Scanner(System.in); while (true) { System.out.println(\"1. pause\"); System.out.println(\"2. resume\"); System.out.println(\"3. restart\"); System.out.println(\"4. stop\"); System.out.println(\"5. Jump to specific time\"); int c = sc.nextInt(); audioPlayer.gotoChoice(c); if (c == 4) break; } sc.close(); } catch (Exception ex) { System.out.println(\"Error with playing sound.\"); ex.printStackTrace(); } } // Work as the user enters his choice private void gotoChoice(int c) throws IOException, LineUnavailableException, UnsupportedAudioFileException { switch (c) { case 1: pause(); break; case 2: resumeAudio(); break; case 3: restart(); break; case 4: stop(); break; case 5: System.out.println(\"Enter time (\" + 0 + \", \" + clip.getMicrosecondLength() + \")\"); Scanner sc = new Scanner(System.in); long c1 = sc.nextLong(); jump(c1); break; } } // Method to play the audio public void play() { //start the clip clip.start(); status = \"play\"; } // Method to pause the audio public void pause() { if (status.equals(\"paused\")) { System.out.println(\"audio is already paused\"); return; } this.currentFrame = this.clip.getMicrosecondPosition(); clip.stop(); status = \"paused\"; } // Method to resume the audio public void resumeAudio() throws UnsupportedAudioFileException, IOException, LineUnavailableException { if (status.equals(\"play\")) { System.out.println(\"Audio is already \"+ \"being played\"); return; } clip.close(); resetAudioStream(); clip.setMicrosecondPosition(currentFrame); this.play(); } // Method to restart the audio public void restart() throws IOException, LineUnavailableException, UnsupportedAudioFileException { clip.stop(); clip.close(); resetAudioStream(); currentFrame = 0L; clip.setMicrosecondPosition(0); this.play(); } // Method to stop the audio public void stop() throws UnsupportedAudioFileException, IOException, LineUnavailableException { currentFrame = 0L; clip.stop(); clip.close(); } // Method to jump over a specific part public void jump(long c) throws UnsupportedAudioFileException, IOException, LineUnavailableException { if (c > 0 && c < clip.getMicrosecondLength()) { clip.stop(); clip.close(); resetAudioStream(); currentFrame = c; clip.setMicrosecondPosition(c); this.play(); } } // Method to reset audio stream public void resetAudioStream() throws UnsupportedAudioFileException, IOException, LineUnavailableException { audioInputStream = AudioSystem.getAudioInputStream( new File(filePath).getAbsoluteFile()); clip.open(audioInputStream); clip.loop(Clip.LOOP_CONTINUOUSLY); } }",
"e": 6914,
"s": 1702,
"text": null
},
{
"code": null,
"e": 7090,
"s": 6914,
"text": "In above program we have used AudioInputStream which is a class in Java to read audio file as a stream. Like every stream of java if it is to be used again it has to be reset."
},
{
"code": null,
"e": 7460,
"s": 7090,
"text": "To pause the playback we have to stop the player and store the current frame in an object. So that while resuming we can use it. When resuming we just have to play again the player from the last position we left.clip.getMicrosecondPosition() method returns the current position of audio and clip.setMicrosecondPosition(long position) sets the current position of audio."
},
{
"code": null,
"e": 7679,
"s": 7460,
"text": "To stop the playback, you must have to close the clip otherwise it will remain open. I have also used clip.loop(Clip.LOOP_CONTINOUSLY) for testing. Because wav files are generally small so I have played mine in a loop."
},
{
"code": null,
"e": 7697,
"s": 7679,
"text": "Important Points:"
},
{
"code": null,
"e": 7904,
"s": 7697,
"text": "Always close your opened stream and resources before exiting the program.You have to stop the clip before playing it again. So keep proper checks.If AudioInputStream is to be used again, it has to be reset."
},
{
"code": null,
"e": 7978,
"s": 7904,
"text": "Always close your opened stream and resources before exiting the program."
},
{
"code": null,
"e": 8052,
"s": 7978,
"text": "You have to stop the clip before playing it again. So keep proper checks."
},
{
"code": null,
"e": 8113,
"s": 8052,
"text": "If AudioInputStream is to be used again, it has to be reset."
},
{
"code": null,
"e": 8409,
"s": 8113,
"text": " This article is contributed by Vishal Garg. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 8534,
"s": 8409,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 8553,
"s": 8534,
"text": "java-file-handling"
},
{
"code": null,
"e": 8566,
"s": 8553,
"text": "Java-Library"
},
{
"code": null,
"e": 8578,
"s": 8566,
"text": "java-puzzle"
},
{
"code": null,
"e": 8583,
"s": 8578,
"text": "Java"
},
{
"code": null,
"e": 8588,
"s": 8583,
"text": "Java"
},
{
"code": null,
"e": 8686,
"s": 8588,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8737,
"s": 8686,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 8768,
"s": 8737,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 8787,
"s": 8768,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 8817,
"s": 8787,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 8832,
"s": 8817,
"text": "Stream In Java"
},
{
"code": null,
"e": 8852,
"s": 8832,
"text": "Collections in Java"
},
{
"code": null,
"e": 8876,
"s": 8852,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 8908,
"s": 8876,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 8920,
"s": 8908,
"text": "Set in Java"
}
] |
D3.js group() Method
|
23 Sep, 2020
With the help of d3.group() method, we can group the iterable data structure into a map where the key is defined as the element from iterable and values as an array.
Syntax:
d3.group( iterable, ...keys )
Return value: It returns the map having key as element and value as an array.
Note: To execute the below examples you have to install the d3 library by using this command prompt we have to execute the following command.
npm install d3
Example 1: In this example, we can see that by using the d3.group() method. We are able to get the map from the group iterable where the key is an element and the value as an array.
Javascript
// Defining d3 contrib variable var d3 = require('d3'); data = [ {name: "ABC", amount: "34.0", date: "11/12/2015"}, {name: "DEF", amount: "120.11", date: "11/12/2015"}, {name: "MNO", amount: "12.01", date: "01/04/2016"}, {name: "XYZ", amount: "34.05", date: "01/04/2016"}] var grouped_data = d3.group(data, d => d.name) console.log(grouped_data)
Output:
Map {‘ABC’ => [ { name: ‘ABC’, amount: ‘34.0’, date: ’11/12/2015′ } ],‘DEF’ => [ { name: ‘DEF’, amount: ‘120.11’, date: ’11/12/2015′ } ],‘MNO’ => [ { name: ‘MNO’, amount: ‘12.01’, date: ’01/04/2016′ } ],‘XYZ’ => [ { name: ‘XYZ’, amount: ‘34.05’, date: ’01/04/2016′ } ]}
Example 2:
Javascript
// Defining d3 contrib variable var d3 = require('d3'); data = [ {name: "ABC", amount: "34.0", date: "11/12/2015"}, {name: "DEF", amount: "120.11", date: "11/12/2015"}, {name: "MNO", amount: "12.01", date: "01/04/2016"}, {name: "XYZ", amount: "34.05", date: "01/04/2016"}] var grouped_data = d3.group(data, d => d.name, d => d.amount) console.log(grouped_data)
Output:
Map {
'ABC' => Map { '34.0' => [ [Object] ] },
'DEF' => Map { '120.11' => [ [Object] ] },
'MNO' => Map { '12.01' => [ [Object] ] },
'XYZ' => Map { '34.05' => [ [Object] ] }
}
D3.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
Roadmap to Learn JavaScript For Beginners
JavaScript | Promises
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 Sep, 2020"
},
{
"code": null,
"e": 194,
"s": 28,
"text": "With the help of d3.group() method, we can group the iterable data structure into a map where the key is defined as the element from iterable and values as an array."
},
{
"code": null,
"e": 202,
"s": 194,
"text": "Syntax:"
},
{
"code": null,
"e": 232,
"s": 202,
"text": "d3.group( iterable, ...keys )"
},
{
"code": null,
"e": 310,
"s": 232,
"text": "Return value: It returns the map having key as element and value as an array."
},
{
"code": null,
"e": 452,
"s": 310,
"text": "Note: To execute the below examples you have to install the d3 library by using this command prompt we have to execute the following command."
},
{
"code": null,
"e": 467,
"s": 452,
"text": "npm install d3"
},
{
"code": null,
"e": 649,
"s": 467,
"text": "Example 1: In this example, we can see that by using the d3.group() method. We are able to get the map from the group iterable where the key is an element and the value as an array."
},
{
"code": null,
"e": 660,
"s": 649,
"text": "Javascript"
},
{
"code": "// Defining d3 contrib variable var d3 = require('d3'); data = [ {name: \"ABC\", amount: \"34.0\", date: \"11/12/2015\"}, {name: \"DEF\", amount: \"120.11\", date: \"11/12/2015\"}, {name: \"MNO\", amount: \"12.01\", date: \"01/04/2016\"}, {name: \"XYZ\", amount: \"34.05\", date: \"01/04/2016\"}] var grouped_data = d3.group(data, d => d.name) console.log(grouped_data)",
"e": 1018,
"s": 660,
"text": null
},
{
"code": null,
"e": 1026,
"s": 1018,
"text": "Output:"
},
{
"code": null,
"e": 1296,
"s": 1026,
"text": "Map {‘ABC’ => [ { name: ‘ABC’, amount: ‘34.0’, date: ’11/12/2015′ } ],‘DEF’ => [ { name: ‘DEF’, amount: ‘120.11’, date: ’11/12/2015′ } ],‘MNO’ => [ { name: ‘MNO’, amount: ‘12.01’, date: ’01/04/2016′ } ],‘XYZ’ => [ { name: ‘XYZ’, amount: ‘34.05’, date: ’01/04/2016′ } ]}"
},
{
"code": null,
"e": 1307,
"s": 1296,
"text": "Example 2:"
},
{
"code": null,
"e": 1318,
"s": 1307,
"text": "Javascript"
},
{
"code": "// Defining d3 contrib variable var d3 = require('d3'); data = [ {name: \"ABC\", amount: \"34.0\", date: \"11/12/2015\"}, {name: \"DEF\", amount: \"120.11\", date: \"11/12/2015\"}, {name: \"MNO\", amount: \"12.01\", date: \"01/04/2016\"}, {name: \"XYZ\", amount: \"34.05\", date: \"01/04/2016\"}] var grouped_data = d3.group(data, d => d.name, d => d.amount) console.log(grouped_data)",
"e": 1699,
"s": 1318,
"text": null
},
{
"code": null,
"e": 1707,
"s": 1699,
"text": "Output:"
},
{
"code": null,
"e": 1892,
"s": 1707,
"text": "Map {\n 'ABC' => Map { '34.0' => [ [Object] ] },\n 'DEF' => Map { '120.11' => [ [Object] ] },\n 'MNO' => Map { '12.01' => [ [Object] ] },\n 'XYZ' => Map { '34.05' => [ [Object] ] } \n}\n"
},
{
"code": null,
"e": 1898,
"s": 1892,
"text": "D3.js"
},
{
"code": null,
"e": 1909,
"s": 1898,
"text": "JavaScript"
},
{
"code": null,
"e": 1926,
"s": 1909,
"text": "Web Technologies"
},
{
"code": null,
"e": 2024,
"s": 1926,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2085,
"s": 2024,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2125,
"s": 2085,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 2166,
"s": 2125,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 2208,
"s": 2166,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 2230,
"s": 2208,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 2292,
"s": 2230,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2325,
"s": 2292,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2386,
"s": 2325,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2436,
"s": 2386,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
PostgreSQL – Backup Database
|
16 Jun, 2022
All commercial firms and corporations are never 100% free of data threats. Being wary of scenarios like data corruption, host or network failures or even deliberate storage facility destruction is extremely important. Therefore, backing up data is a critical activity that every firm depends on to ensure its existence in the market. The idea behind backups of servers extends beyond just the ability to contend in the market. Here are a few reasons why backups are done so often:
Data-loss prevention: In cases of dire situations such as cyber threats or catastrophes, data must be kept alive in its authentic dress.Business Health: all businesses must review their records in order to stay reliant and aware on all levels of database security.Foster responsibility: backing up servers is the most fluent manner by which a firm gathers trust from the consumers regarding the safekeeping of information.
Data-loss prevention: In cases of dire situations such as cyber threats or catastrophes, data must be kept alive in its authentic dress.
Business Health: all businesses must review their records in order to stay reliant and aware on all levels of database security.
Foster responsibility: backing up servers is the most fluent manner by which a firm gathers trust from the consumers regarding the safekeeping of information.
PostgreSQL has a noteworthy share in the market, setting aside MySQL as the undisputed leader. As is customary for any Database Management System of such a high standard, PostgreSQL provides a set of both logical and physical backups. For those not aware of the difference:
Logical backups contain info regarding the database, such as the tables and schemas while physical backups contain the files and directories of the information.
Logical backups are less size when compared to physical backups.
Conceptually, there are several levels of backup (differential, full, incremental etc.) but that is besides the objective of this article. We shall be dealing with the approaches that PostgreSQL offers to its users. Here we shall focus on 3 of them –
File System Level BackupsSQL DumpsContinuous or Repetitive Archiving
File System Level Backups
SQL Dumps
Continuous or Repetitive Archiving
A file system level backup is a physical backup. The idea is to make a copy of all files that created the database. This means we are looking at database clusters and directories that are used by PostgreSQL to write the data into the database. One way of interpreting this is by visualizing yourself as the scientist publishing a research paper and using loads of previously written work to give definition to your work. The works you refer to form a framework and layout which guide you throughout your writing process. The files that PostgreSQL attempts to copy are the framework and layout along with guidelines containing the data (specifically a bunch of .dat files).
The copying statement:
tar -cf backup.tar /%p $PATH TO DATA FILE/%f $FILENAME
OR
rsync -v /var/lib/pgsql/13/backups/ /Directory 2/
Notice that a .tar file is created i.e., a tape archive. Meanwhile, rsync is a command that SYNCHRONIZES two directories. So, if Directory 2 does not have the same contents as the first directory (/var/lib/....), then it would after execution – a cleaver form of copying.
However, we must enable archiving prior to execution. Obviously, simply copying data is considered as being careless; ongoing transactions will affect the immediate state of files being copied, leading to a questionable status of the backup and its reliability.
Note: This is a deliberate overlap with the last approach discussed in this article; it helps with improving the quality of the backup.
Therefore, we begin by first enabling WAL archiving. WAL archives are files that maintain all modifications made by transactions in order to keep data in the database and the instance memory consistent.
WAL files are ‘Write-Ahead Log’ files. All transactions performed are first written to the WAL file before those changes are applied to the actual disk space. WAL archives are copies of the WAL files and exist in a separate directory to avoid plausible crashes.
Step 1: Start the backup by first connecting to the database as a privileged user and then running the following. /db is the name of the database you wish to back up.
SELECT pg_start_backup('label',false,false);
tar -cf -z backup_name.tar /db $the name of the database you wish to backup
-cf : this indicates a ‘custom format’. By including this, the user states that the archive file will have a custom format. This introduces flexibility when re-importing the file.
-z : this attribute to the command indicates to postgreSQL to compress the output file.
Step 2: Tell the database to terminate backup mode.
SELECT * FROM pg_stop_backup(false, true);
What this command also does is that it creates a .backup file that helps identify the first and last archive logs. This is important when restoring the database.
In the very likely case that the user forgets to enable WAL archiving, this is displayed on the shell:
Set the following in the postgresql.conf file:
-wal_level = replica
-archive_mode = on
-archive_command = 'cp %p /%f'
This enables WAL archiving. %p is the path name and %f is the name of the file. Setting parameters in the configuration file is only possible via command line.
Demerits of File System Level Backups:
They require for the entire database to be backed-up. Backing up schemas or only specific tables is not an option. The same applies for the restoration process as well i.e., the entire database must be restored.
In consequence, they take up more space on storage by default.
The server must be stopped to obtain a usable backup. This results in unnecessary overhead and disrupts continuity in business transactions.
Closest Alternative:
Another method of issuing a backup is by using pg_basebackup for the following reasons:
Recovery from the backup is faster and safer
It is installation version specific
Backups are done over replication protocols
When it comes to smaller Databases, it is much more convenient to execute an SQL Dump. SQL Dumps are logical backups. This implies that the method would backup all instructions that were used to create the schemas and the tables. Therefore, the file that is exported after the backup is literally a file full of DDL and DML commands.
PostgreSQL offers two methods by which an SQL dump may be performed.
pg_dump is a simple command that creates a copy of one of the databases on the server. Think of it as ‘dumping the object files of only ONE database into a new file. At the end of this process, a new file is created which is human-interpretable (filled with SQL commands). pg_dump works with the following options:
-Fc : exports the file in custom format – explained above for File System Level backups
-Z : this is used along with the command to compress the data. As one would expect, this is used with large databases.
-j : used to enable parallel backups using pg_dump again
-a : this option specifies that only data will be backed up.
-s : used when only schemas are required to be backed up.
-t : used when only tables of the database required to be backed up.
Here is the sample format by which a user may create an SQL dump using pg_dump:
>> C:\Program Files\PostgreSQL\13\bin
>> pg_dump -U username -W -F p database_name > path_to_output_file.sql
>> Password:
>>(For example)
>> pg_dump -U dbuser04 -W -F p My_University > University_backup.sql
The user must first navigate to the \bin folder of the PostgreSQL version installed ON THE TERMINAL or CMD. Once that is done, the command – as stated – may be performed. It is suggested that the output file be created in a known location prior to execution (don’t rely on PostgreSQL to create it for you). In the command above, -W is an option which enables verification of the user via the password. -F is used to specify the format of the output file in the following character (remember to change the extension of the output file). Therefore:
p = plain text file
t = tar file
d = directory-format archive
c = custom format archive
Using pg_dumpall:
The apparent caveat is how pg_dump is restricted to creating a copy of a single database at a time. For situations where multiple databases in the server must be backed up, PostgreSQL makes available the pg_dumpall command. For most part, its syntax stays the same and so do the options with the exception of –W (honestly, no one really would want to type the password for every single database they backup).
>> C:\Program Files\PostgreSQL\13\bin
>> pg_dumpall -U username -F p > path_to_output_file.sql
In many cases, firms might prefer to only make copies of the schemas or certain object definitions and not really the data. This is very much accounted for.
>> pg_dumpall --tablespaces-only > path_to_output_file.sql $for only tablespaces
>> pg_dumpall --schema-only > path_to_output_file.sql $for only schemas
Based on multiple IT factions of corporations utilizing PostgreSQL servers for day-to-day procedures, the shortcomings of SQL Dumps easily provide incentive to use other approaches for Backups and Recovery.
As we have seen, SQL dumps literally recreate every variable based on the instructions stored in the output file. In fact, it works on rebuilding all indexes as well. The cap on restoring speeds is obvious as a result.
A major consequence of the above is the unwanted overhead which businesses never welcome.
Technically, with multiple dumps occurring simultaneously, syntax reversal is a major issue.
Being a logical export, SQL dumps may not be 100% portable.
Consider a database ‘crimedb’ which stores a record of all criminals in the police registry. We shall attempt a regular backup of all tables.
List of all tables in the crimedb database
Execution of pg_dump
Instances from the created Postgres dump file criminal_backup.sql
This is a rather complex procedure when compared to the previous approaches discussed. However, the benefits prevail.
Continuous or repetitive archiving combines the ideas of issuing a File System Level Backup and a backup of the WAL files (technically, enabling WAL archiving separately). It may seem like File System Level Backups all over again, but with the added emphasis on retaining and not just archiving the WAL files while the backup is underway. This enables us to take ‘simultaneous snapshots’ of the database when offline. Another difference is with the restoring procedure – recovery of Continuous Archiving backups is much different.
This section deals with Point-in-Time-Recovery Backups. This is a form of continuous archiving where the user may back up and restore data to a certain point in time in the past. The wordplay is based on the latest WAL archive created.
In short, the procedure is as follows:
Enable WAL ArchivingCreate a way by which the WAL files are retained.Make a File System Level backup (we will use pg_basebackup this time).Retain the backup so that the DB is replayed to a point in time.
Enable WAL Archiving
Create a way by which the WAL files are retained.
Make a File System Level backup (we will use pg_basebackup this time).
Retain the backup so that the DB is replayed to a point in time.
First, let’s connect to the server and execute the following in the psql shell:
>> show archive_mode;
If archiving is disabled then the following is displayed:
The first step (enabling archiving) varies from system to system based on the OS and sometimes the version of Postgres installed. All remaining steps follow a common procedure.
Step 1 (Windows):
First things first, stop the Postgres service from the Windows service manager.
Type services.msc in the taskbar and run it to access this panel.
Now, head to the Postgres.conf file in the \data directory. For example C:\Program Files\PostgreSQL\13\data and make the following parameter changes:
>> archive_mode = on
>> archive_command = 'copy "%p" "C:\\server\\archivedir\\%f"'
>> wal_level = replica
Replace %p with the path of the file we wish to archive which is pg_wal and replace %f with the filename. Be sure to use ‘\\’ for the directories to avoid any issues.
Now, Start the Postgres services.
Step 1 (Linux):
Follow the procedure dictated in the code below:
$ mkdir db_archive
$ sudo chown postgres:postgres db_archive
Now, we have a directory created to which we shall write the archives. Also, we have given permission to the Postgres user to write to this directory. We must configure our parameters in the postgresql.conf file. Find the file in the data directory or the main directory of the PostgreSQL version you have installed, manually. Then make the following changes to the file (open the file and edit its contents):
# uncomment archive parameter and set it to the following:
archive_mode = on
archive_command = 'test ! -f /path/to/db_archive/%f && cp %p /path/to/db_archive/%f'
# change wal_level as well
wal_level = replica
PostgreSQL.conf file after enabling archiving
Save and exit the file. You must restart the database server now to apply these changes to the setup. The Linux equivalent of this is:
$ sudo systemctl restart postgresql.service
Steps 2 – 4 (common for both platforms):
Open the SQL prompt or SQL Shell (psql) on your system. Connect to the server. Now execute the following query to make a backup.
postgres=# SELECT pg_start_backup('label',false,false)
postgres=# pg_basebackup -Ft -D directory_you_wish_to_backup_to
postgres=# SELECT pg_stop_backup(true,false)
pg_start_backup( ) and pg_stop_backup( ) may be omitted since, pg_basebackup( ) is capable of handling control on its own. Once the prompt is returned, users may check the directory to which the backup was created and be reassured to find a .tar backup file. It is up to the user to specify the kind of file format preferred (p or t or c).
Now that we have a file system level backup and the WAL archives, we can execute a Point in Time Recovery. Let us assume that our Database crashed and as a result, our data was corrupted or damaged, or destroyed.
Stop the services of the database once the backup has been created and delete all the data within the data directory since the data is no longer validated on account of the DB crash.
$ sudo systemctl stop postgres.services
$ or use the windows services panel (if you use Windows)
This is the extent to which continuous archiving can be dealt with (we are only creating a backup, not restoring it yet). However, the process is rather simple and straightforward since all we require to do is import the backups back into the original folders or the default folders/directories that PostgreSQL used initially upon installation. This is followed by a minor change in the postgresql.conf file and that’s about all there is to it!
nikhatkhan11
Picked
postgreSQL-managing-database
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PostgreSQL - LIMIT with OFFSET clause
PostgreSQL - REPLACE Function
PostgreSQL - DROP INDEX
PostgreSQL - INSERT
PostgreSQL - ROW_NUMBER Function
PostgreSQL - TIME Data Type
PostgreSQL - CREATE SCHEMA
PostgreSQL - SELECT
PostgreSQL - EXISTS Operator
PostgreSQL - LEFT JOIN
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n16 Jun, 2022"
},
{
"code": null,
"e": 509,
"s": 28,
"text": "All commercial firms and corporations are never 100% free of data threats. Being wary of scenarios like data corruption, host or network failures or even deliberate storage facility destruction is extremely important. Therefore, backing up data is a critical activity that every firm depends on to ensure its existence in the market. The idea behind backups of servers extends beyond just the ability to contend in the market. Here are a few reasons why backups are done so often:"
},
{
"code": null,
"e": 932,
"s": 509,
"text": "Data-loss prevention: In cases of dire situations such as cyber threats or catastrophes, data must be kept alive in its authentic dress.Business Health: all businesses must review their records in order to stay reliant and aware on all levels of database security.Foster responsibility: backing up servers is the most fluent manner by which a firm gathers trust from the consumers regarding the safekeeping of information."
},
{
"code": null,
"e": 1069,
"s": 932,
"text": "Data-loss prevention: In cases of dire situations such as cyber threats or catastrophes, data must be kept alive in its authentic dress."
},
{
"code": null,
"e": 1198,
"s": 1069,
"text": "Business Health: all businesses must review their records in order to stay reliant and aware on all levels of database security."
},
{
"code": null,
"e": 1357,
"s": 1198,
"text": "Foster responsibility: backing up servers is the most fluent manner by which a firm gathers trust from the consumers regarding the safekeeping of information."
},
{
"code": null,
"e": 1631,
"s": 1357,
"text": "PostgreSQL has a noteworthy share in the market, setting aside MySQL as the undisputed leader. As is customary for any Database Management System of such a high standard, PostgreSQL provides a set of both logical and physical backups. For those not aware of the difference:"
},
{
"code": null,
"e": 1792,
"s": 1631,
"text": "Logical backups contain info regarding the database, such as the tables and schemas while physical backups contain the files and directories of the information."
},
{
"code": null,
"e": 1857,
"s": 1792,
"text": "Logical backups are less size when compared to physical backups."
},
{
"code": null,
"e": 2109,
"s": 1857,
"text": "Conceptually, there are several levels of backup (differential, full, incremental etc.) but that is besides the objective of this article. We shall be dealing with the approaches that PostgreSQL offers to its users. Here we shall focus on 3 of them – "
},
{
"code": null,
"e": 2178,
"s": 2109,
"text": "File System Level BackupsSQL DumpsContinuous or Repetitive Archiving"
},
{
"code": null,
"e": 2204,
"s": 2178,
"text": "File System Level Backups"
},
{
"code": null,
"e": 2214,
"s": 2204,
"text": "SQL Dumps"
},
{
"code": null,
"e": 2249,
"s": 2214,
"text": "Continuous or Repetitive Archiving"
},
{
"code": null,
"e": 2922,
"s": 2249,
"text": "A file system level backup is a physical backup. The idea is to make a copy of all files that created the database. This means we are looking at database clusters and directories that are used by PostgreSQL to write the data into the database. One way of interpreting this is by visualizing yourself as the scientist publishing a research paper and using loads of previously written work to give definition to your work. The works you refer to form a framework and layout which guide you throughout your writing process. The files that PostgreSQL attempts to copy are the framework and layout along with guidelines containing the data (specifically a bunch of .dat files)."
},
{
"code": null,
"e": 2946,
"s": 2922,
"text": "The copying statement: "
},
{
"code": null,
"e": 3054,
"s": 2946,
"text": "tar -cf backup.tar /%p $PATH TO DATA FILE/%f $FILENAME\nOR\nrsync -v /var/lib/pgsql/13/backups/ /Directory 2/"
},
{
"code": null,
"e": 3326,
"s": 3054,
"text": "Notice that a .tar file is created i.e., a tape archive. Meanwhile, rsync is a command that SYNCHRONIZES two directories. So, if Directory 2 does not have the same contents as the first directory (/var/lib/....), then it would after execution – a cleaver form of copying."
},
{
"code": null,
"e": 3589,
"s": 3326,
"text": "However, we must enable archiving prior to execution. Obviously, simply copying data is considered as being careless; ongoing transactions will affect the immediate state of files being copied, leading to a questionable status of the backup and its reliability. "
},
{
"code": null,
"e": 3725,
"s": 3589,
"text": "Note: This is a deliberate overlap with the last approach discussed in this article; it helps with improving the quality of the backup."
},
{
"code": null,
"e": 3928,
"s": 3725,
"text": "Therefore, we begin by first enabling WAL archiving. WAL archives are files that maintain all modifications made by transactions in order to keep data in the database and the instance memory consistent."
},
{
"code": null,
"e": 4190,
"s": 3928,
"text": "WAL files are ‘Write-Ahead Log’ files. All transactions performed are first written to the WAL file before those changes are applied to the actual disk space. WAL archives are copies of the WAL files and exist in a separate directory to avoid plausible crashes."
},
{
"code": null,
"e": 4357,
"s": 4190,
"text": "Step 1: Start the backup by first connecting to the database as a privileged user and then running the following. /db is the name of the database you wish to back up."
},
{
"code": null,
"e": 4478,
"s": 4357,
"text": "SELECT pg_start_backup('label',false,false);\ntar -cf -z backup_name.tar /db $the name of the database you wish to backup"
},
{
"code": null,
"e": 4658,
"s": 4478,
"text": "-cf : this indicates a ‘custom format’. By including this, the user states that the archive file will have a custom format. This introduces flexibility when re-importing the file."
},
{
"code": null,
"e": 4746,
"s": 4658,
"text": "-z : this attribute to the command indicates to postgreSQL to compress the output file."
},
{
"code": null,
"e": 4798,
"s": 4746,
"text": "Step 2: Tell the database to terminate backup mode."
},
{
"code": null,
"e": 4841,
"s": 4798,
"text": "SELECT * FROM pg_stop_backup(false, true);"
},
{
"code": null,
"e": 5003,
"s": 4841,
"text": "What this command also does is that it creates a .backup file that helps identify the first and last archive logs. This is important when restoring the database."
},
{
"code": null,
"e": 5106,
"s": 5003,
"text": "In the very likely case that the user forgets to enable WAL archiving, this is displayed on the shell:"
},
{
"code": null,
"e": 5153,
"s": 5106,
"text": "Set the following in the postgresql.conf file:"
},
{
"code": null,
"e": 5224,
"s": 5153,
"text": "-wal_level = replica\n-archive_mode = on\n-archive_command = 'cp %p /%f'"
},
{
"code": null,
"e": 5384,
"s": 5224,
"text": "This enables WAL archiving. %p is the path name and %f is the name of the file. Setting parameters in the configuration file is only possible via command line."
},
{
"code": null,
"e": 5423,
"s": 5384,
"text": "Demerits of File System Level Backups:"
},
{
"code": null,
"e": 5635,
"s": 5423,
"text": "They require for the entire database to be backed-up. Backing up schemas or only specific tables is not an option. The same applies for the restoration process as well i.e., the entire database must be restored."
},
{
"code": null,
"e": 5698,
"s": 5635,
"text": "In consequence, they take up more space on storage by default."
},
{
"code": null,
"e": 5839,
"s": 5698,
"text": "The server must be stopped to obtain a usable backup. This results in unnecessary overhead and disrupts continuity in business transactions."
},
{
"code": null,
"e": 5860,
"s": 5839,
"text": "Closest Alternative:"
},
{
"code": null,
"e": 5948,
"s": 5860,
"text": "Another method of issuing a backup is by using pg_basebackup for the following reasons:"
},
{
"code": null,
"e": 5993,
"s": 5948,
"text": "Recovery from the backup is faster and safer"
},
{
"code": null,
"e": 6029,
"s": 5993,
"text": "It is installation version specific"
},
{
"code": null,
"e": 6073,
"s": 6029,
"text": "Backups are done over replication protocols"
},
{
"code": null,
"e": 6408,
"s": 6073,
"text": "When it comes to smaller Databases, it is much more convenient to execute an SQL Dump. SQL Dumps are logical backups. This implies that the method would backup all instructions that were used to create the schemas and the tables. Therefore, the file that is exported after the backup is literally a file full of DDL and DML commands. "
},
{
"code": null,
"e": 6477,
"s": 6408,
"text": "PostgreSQL offers two methods by which an SQL dump may be performed."
},
{
"code": null,
"e": 6792,
"s": 6477,
"text": "pg_dump is a simple command that creates a copy of one of the databases on the server. Think of it as ‘dumping the object files of only ONE database into a new file. At the end of this process, a new file is created which is human-interpretable (filled with SQL commands). pg_dump works with the following options:"
},
{
"code": null,
"e": 6880,
"s": 6792,
"text": "-Fc : exports the file in custom format – explained above for File System Level backups"
},
{
"code": null,
"e": 6999,
"s": 6880,
"text": "-Z : this is used along with the command to compress the data. As one would expect, this is used with large databases."
},
{
"code": null,
"e": 7056,
"s": 6999,
"text": "-j : used to enable parallel backups using pg_dump again"
},
{
"code": null,
"e": 7117,
"s": 7056,
"text": "-a : this option specifies that only data will be backed up."
},
{
"code": null,
"e": 7175,
"s": 7117,
"text": "-s : used when only schemas are required to be backed up."
},
{
"code": null,
"e": 7244,
"s": 7175,
"text": "-t : used when only tables of the database required to be backed up."
},
{
"code": null,
"e": 7324,
"s": 7244,
"text": "Here is the sample format by which a user may create an SQL dump using pg_dump:"
},
{
"code": null,
"e": 7531,
"s": 7324,
"text": ">> C:\\Program Files\\PostgreSQL\\13\\bin\n>> pg_dump -U username -W -F p database_name > path_to_output_file.sql\n>> Password:\n>>(For example)\n>> pg_dump -U dbuser04 -W -F p My_University > University_backup.sql"
},
{
"code": null,
"e": 8078,
"s": 7531,
"text": "The user must first navigate to the \\bin folder of the PostgreSQL version installed ON THE TERMINAL or CMD. Once that is done, the command – as stated – may be performed. It is suggested that the output file be created in a known location prior to execution (don’t rely on PostgreSQL to create it for you). In the command above, -W is an option which enables verification of the user via the password. -F is used to specify the format of the output file in the following character (remember to change the extension of the output file). Therefore:"
},
{
"code": null,
"e": 8098,
"s": 8078,
"text": "p = plain text file"
},
{
"code": null,
"e": 8111,
"s": 8098,
"text": "t = tar file"
},
{
"code": null,
"e": 8140,
"s": 8111,
"text": "d = directory-format archive"
},
{
"code": null,
"e": 8166,
"s": 8140,
"text": "c = custom format archive"
},
{
"code": null,
"e": 8184,
"s": 8166,
"text": "Using pg_dumpall:"
},
{
"code": null,
"e": 8593,
"s": 8184,
"text": "The apparent caveat is how pg_dump is restricted to creating a copy of a single database at a time. For situations where multiple databases in the server must be backed up, PostgreSQL makes available the pg_dumpall command. For most part, its syntax stays the same and so do the options with the exception of –W (honestly, no one really would want to type the password for every single database they backup)."
},
{
"code": null,
"e": 8688,
"s": 8593,
"text": ">> C:\\Program Files\\PostgreSQL\\13\\bin\n>> pg_dumpall -U username -F p > path_to_output_file.sql"
},
{
"code": null,
"e": 8845,
"s": 8688,
"text": "In many cases, firms might prefer to only make copies of the schemas or certain object definitions and not really the data. This is very much accounted for."
},
{
"code": null,
"e": 9002,
"s": 8845,
"text": ">> pg_dumpall --tablespaces-only > path_to_output_file.sql $for only tablespaces\n>> pg_dumpall --schema-only > path_to_output_file.sql $for only schemas"
},
{
"code": null,
"e": 9211,
"s": 9002,
"text": "Based on multiple IT factions of corporations utilizing PostgreSQL servers for day-to-day procedures, the shortcomings of SQL Dumps easily provide incentive to use other approaches for Backups and Recovery. "
},
{
"code": null,
"e": 9430,
"s": 9211,
"text": "As we have seen, SQL dumps literally recreate every variable based on the instructions stored in the output file. In fact, it works on rebuilding all indexes as well. The cap on restoring speeds is obvious as a result."
},
{
"code": null,
"e": 9520,
"s": 9430,
"text": "A major consequence of the above is the unwanted overhead which businesses never welcome."
},
{
"code": null,
"e": 9613,
"s": 9520,
"text": "Technically, with multiple dumps occurring simultaneously, syntax reversal is a major issue."
},
{
"code": null,
"e": 9673,
"s": 9613,
"text": "Being a logical export, SQL dumps may not be 100% portable."
},
{
"code": null,
"e": 9815,
"s": 9673,
"text": "Consider a database ‘crimedb’ which stores a record of all criminals in the police registry. We shall attempt a regular backup of all tables."
},
{
"code": null,
"e": 9859,
"s": 9815,
"text": "List of all tables in the crimedb database "
},
{
"code": null,
"e": 9880,
"s": 9859,
"text": "Execution of pg_dump"
},
{
"code": null,
"e": 9946,
"s": 9880,
"text": "Instances from the created Postgres dump file criminal_backup.sql"
},
{
"code": null,
"e": 10064,
"s": 9946,
"text": "This is a rather complex procedure when compared to the previous approaches discussed. However, the benefits prevail."
},
{
"code": null,
"e": 10596,
"s": 10064,
"text": "Continuous or repetitive archiving combines the ideas of issuing a File System Level Backup and a backup of the WAL files (technically, enabling WAL archiving separately). It may seem like File System Level Backups all over again, but with the added emphasis on retaining and not just archiving the WAL files while the backup is underway. This enables us to take ‘simultaneous snapshots’ of the database when offline. Another difference is with the restoring procedure – recovery of Continuous Archiving backups is much different. "
},
{
"code": null,
"e": 10832,
"s": 10596,
"text": "This section deals with Point-in-Time-Recovery Backups. This is a form of continuous archiving where the user may back up and restore data to a certain point in time in the past. The wordplay is based on the latest WAL archive created."
},
{
"code": null,
"e": 10872,
"s": 10832,
"text": "In short, the procedure is as follows: "
},
{
"code": null,
"e": 11076,
"s": 10872,
"text": "Enable WAL ArchivingCreate a way by which the WAL files are retained.Make a File System Level backup (we will use pg_basebackup this time).Retain the backup so that the DB is replayed to a point in time."
},
{
"code": null,
"e": 11097,
"s": 11076,
"text": "Enable WAL Archiving"
},
{
"code": null,
"e": 11147,
"s": 11097,
"text": "Create a way by which the WAL files are retained."
},
{
"code": null,
"e": 11218,
"s": 11147,
"text": "Make a File System Level backup (we will use pg_basebackup this time)."
},
{
"code": null,
"e": 11283,
"s": 11218,
"text": "Retain the backup so that the DB is replayed to a point in time."
},
{
"code": null,
"e": 11363,
"s": 11283,
"text": "First, let’s connect to the server and execute the following in the psql shell:"
},
{
"code": null,
"e": 11385,
"s": 11363,
"text": ">> show archive_mode;"
},
{
"code": null,
"e": 11443,
"s": 11385,
"text": "If archiving is disabled then the following is displayed:"
},
{
"code": null,
"e": 11620,
"s": 11443,
"text": "The first step (enabling archiving) varies from system to system based on the OS and sometimes the version of Postgres installed. All remaining steps follow a common procedure."
},
{
"code": null,
"e": 11638,
"s": 11620,
"text": "Step 1 (Windows):"
},
{
"code": null,
"e": 11719,
"s": 11638,
"text": "First things first, stop the Postgres service from the Windows service manager. "
},
{
"code": null,
"e": 11785,
"s": 11719,
"text": "Type services.msc in the taskbar and run it to access this panel."
},
{
"code": null,
"e": 11935,
"s": 11785,
"text": "Now, head to the Postgres.conf file in the \\data directory. For example C:\\Program Files\\PostgreSQL\\13\\data and make the following parameter changes:"
},
{
"code": null,
"e": 12041,
"s": 11935,
"text": ">> archive_mode = on\n>> archive_command = 'copy \"%p\" \"C:\\\\server\\\\archivedir\\\\%f\"'\n>> wal_level = replica"
},
{
"code": null,
"e": 12208,
"s": 12041,
"text": "Replace %p with the path of the file we wish to archive which is pg_wal and replace %f with the filename. Be sure to use ‘\\\\’ for the directories to avoid any issues."
},
{
"code": null,
"e": 12242,
"s": 12208,
"text": "Now, Start the Postgres services."
},
{
"code": null,
"e": 12258,
"s": 12242,
"text": "Step 1 (Linux):"
},
{
"code": null,
"e": 12307,
"s": 12258,
"text": "Follow the procedure dictated in the code below:"
},
{
"code": null,
"e": 12368,
"s": 12307,
"text": "$ mkdir db_archive\n$ sudo chown postgres:postgres db_archive"
},
{
"code": null,
"e": 12778,
"s": 12368,
"text": "Now, we have a directory created to which we shall write the archives. Also, we have given permission to the Postgres user to write to this directory. We must configure our parameters in the postgresql.conf file. Find the file in the data directory or the main directory of the PostgreSQL version you have installed, manually. Then make the following changes to the file (open the file and edit its contents):"
},
{
"code": null,
"e": 12987,
"s": 12778,
"text": "# uncomment archive parameter and set it to the following:\narchive_mode = on\narchive_command = 'test ! -f /path/to/db_archive/%f && cp %p /path/to/db_archive/%f'\n# change wal_level as well\nwal_level = replica"
},
{
"code": null,
"e": 13033,
"s": 12987,
"text": "PostgreSQL.conf file after enabling archiving"
},
{
"code": null,
"e": 13168,
"s": 13033,
"text": "Save and exit the file. You must restart the database server now to apply these changes to the setup. The Linux equivalent of this is:"
},
{
"code": null,
"e": 13212,
"s": 13168,
"text": "$ sudo systemctl restart postgresql.service"
},
{
"code": null,
"e": 13253,
"s": 13212,
"text": "Steps 2 – 4 (common for both platforms):"
},
{
"code": null,
"e": 13382,
"s": 13253,
"text": "Open the SQL prompt or SQL Shell (psql) on your system. Connect to the server. Now execute the following query to make a backup."
},
{
"code": null,
"e": 13546,
"s": 13382,
"text": "postgres=# SELECT pg_start_backup('label',false,false)\npostgres=# pg_basebackup -Ft -D directory_you_wish_to_backup_to\npostgres=# SELECT pg_stop_backup(true,false)"
},
{
"code": null,
"e": 13886,
"s": 13546,
"text": "pg_start_backup( ) and pg_stop_backup( ) may be omitted since, pg_basebackup( ) is capable of handling control on its own. Once the prompt is returned, users may check the directory to which the backup was created and be reassured to find a .tar backup file. It is up to the user to specify the kind of file format preferred (p or t or c)."
},
{
"code": null,
"e": 14100,
"s": 13886,
"text": "Now that we have a file system level backup and the WAL archives, we can execute a Point in Time Recovery. Let us assume that our Database crashed and as a result, our data was corrupted or damaged, or destroyed. "
},
{
"code": null,
"e": 14283,
"s": 14100,
"text": "Stop the services of the database once the backup has been created and delete all the data within the data directory since the data is no longer validated on account of the DB crash."
},
{
"code": null,
"e": 14381,
"s": 14283,
"text": "$ sudo systemctl stop postgres.services \n$ or use the windows services panel (if you use Windows)"
},
{
"code": null,
"e": 14826,
"s": 14381,
"text": "This is the extent to which continuous archiving can be dealt with (we are only creating a backup, not restoring it yet). However, the process is rather simple and straightforward since all we require to do is import the backups back into the original folders or the default folders/directories that PostgreSQL used initially upon installation. This is followed by a minor change in the postgresql.conf file and that’s about all there is to it!"
},
{
"code": null,
"e": 14839,
"s": 14826,
"text": "nikhatkhan11"
},
{
"code": null,
"e": 14846,
"s": 14839,
"text": "Picked"
},
{
"code": null,
"e": 14875,
"s": 14846,
"text": "postgreSQL-managing-database"
},
{
"code": null,
"e": 14886,
"s": 14875,
"text": "PostgreSQL"
},
{
"code": null,
"e": 14984,
"s": 14886,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 15022,
"s": 14984,
"text": "PostgreSQL - LIMIT with OFFSET clause"
},
{
"code": null,
"e": 15052,
"s": 15022,
"text": "PostgreSQL - REPLACE Function"
},
{
"code": null,
"e": 15076,
"s": 15052,
"text": "PostgreSQL - DROP INDEX"
},
{
"code": null,
"e": 15096,
"s": 15076,
"text": "PostgreSQL - INSERT"
},
{
"code": null,
"e": 15129,
"s": 15096,
"text": "PostgreSQL - ROW_NUMBER Function"
},
{
"code": null,
"e": 15157,
"s": 15129,
"text": "PostgreSQL - TIME Data Type"
},
{
"code": null,
"e": 15184,
"s": 15157,
"text": "PostgreSQL - CREATE SCHEMA"
},
{
"code": null,
"e": 15204,
"s": 15184,
"text": "PostgreSQL - SELECT"
},
{
"code": null,
"e": 15233,
"s": 15204,
"text": "PostgreSQL - EXISTS Operator"
}
] |
replace() in Python to replace a substring
|
23 Nov, 2020
Given a string str that may contain one more occurrences of “AB”. Replace all occurrences of “AB” with “C” in str.
Examples:
Input : str = "helloABworld"
Output : str = "helloCworld"
Input : str = "fghABsdfABysu"
Output : str = "fghCsdfCysu"
This problem has existing solution please refer Replace all occurrences of string AB with C without using extra space link. We solve this problem in python quickly using replace() method of string data type.
How does replace() function works ?str.replace(pattern,replaceWith,maxCount) takes minimum two parameters and replaces all occurrences of pattern with specified sub-string replaceWith. Third parameter maxCount is optional, if we do not pass this parameter then replace function will do it for all occurrences of pattern otherwise it will replace only maxCount times occurrences of pattern.
# Function to replace all occurrences of AB with C def replaceABwithC(input, pattern, replaceWith): return input.replace(pattern, replaceWith) # Driver programif __name__ == "__main__": input = 'helloABworld' pattern = 'AB' replaceWith = 'C' print (replaceABwithC(input,pattern,replaceWith))
Output:
'helloCworld'
vaibhav2992
python-string
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Convert integer to string in Python
How to drop one or multiple columns in Pandas Dataframe
Create a Pandas DataFrame from Lists
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n23 Nov, 2020"
},
{
"code": null,
"e": 168,
"s": 53,
"text": "Given a string str that may contain one more occurrences of “AB”. Replace all occurrences of “AB” with “C” in str."
},
{
"code": null,
"e": 178,
"s": 168,
"text": "Examples:"
},
{
"code": null,
"e": 299,
"s": 178,
"text": "Input : str = \"helloABworld\"\nOutput : str = \"helloCworld\"\n\nInput : str = \"fghABsdfABysu\"\nOutput : str = \"fghCsdfCysu\"\n"
},
{
"code": null,
"e": 507,
"s": 299,
"text": "This problem has existing solution please refer Replace all occurrences of string AB with C without using extra space link. We solve this problem in python quickly using replace() method of string data type."
},
{
"code": null,
"e": 897,
"s": 507,
"text": "How does replace() function works ?str.replace(pattern,replaceWith,maxCount) takes minimum two parameters and replaces all occurrences of pattern with specified sub-string replaceWith. Third parameter maxCount is optional, if we do not pass this parameter then replace function will do it for all occurrences of pattern otherwise it will replace only maxCount times occurrences of pattern."
},
{
"code": "# Function to replace all occurrences of AB with C def replaceABwithC(input, pattern, replaceWith): return input.replace(pattern, replaceWith) # Driver programif __name__ == \"__main__\": input = 'helloABworld' pattern = 'AB' replaceWith = 'C' print (replaceABwithC(input,pattern,replaceWith))",
"e": 1208,
"s": 897,
"text": null
},
{
"code": null,
"e": 1216,
"s": 1208,
"text": "Output:"
},
{
"code": null,
"e": 1231,
"s": 1216,
"text": "'helloCworld'\n"
},
{
"code": null,
"e": 1243,
"s": 1231,
"text": "vaibhav2992"
},
{
"code": null,
"e": 1257,
"s": 1243,
"text": "python-string"
},
{
"code": null,
"e": 1264,
"s": 1257,
"text": "Python"
},
{
"code": null,
"e": 1362,
"s": 1264,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1404,
"s": 1362,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1426,
"s": 1404,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1458,
"s": 1426,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1487,
"s": 1458,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 1514,
"s": 1487,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1535,
"s": 1514,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1558,
"s": 1535,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 1594,
"s": 1558,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 1650,
"s": 1594,
"text": "How to drop one or multiple columns in Pandas Dataframe"
}
] |
D3.JS (Data Driven Documents) - GeeksforGeeks
|
15 Jan, 2019
Introduction: The D3 is an abbreviation of Data Driven Documents, and D3.js is a resource JavaScript library for managing documents based on data. D3 is one of the most effective framework to work on data visualization. It allows the developer to create dynamic, interactive data visualizations in the browser with the help of HTML, CSS and SVG. The data visualization is the representation of filtered data in the form of picture and graphics. Graphical or pictorial representations presenting even complex data sets with ease. Also, comparative analytics or patterns can be easily traced with the help of data visualization, thus enabling the client to make decisions without much brainstorming. Such visualizations can be easily developed using frameworks such as D3.js. Mike Bostock wrote the D3 framework. Before D3, Protovis toolkit was widely used for Data Visualizations. Though there are many other frameworks for Data visualization, but D3.js has left its footmark because of its flexibility and learnability.Instead of working as a monolithic framework providing every conceivable feature, D3 solves the core of a problem by providing efficient manipulation of data. It reduces the overhead and allows flexibility.
Features: There are many other platforms or frameworks available for managing data visualization, but D3 has left all the other frameworks behind because of being extremely flexible. Following are the major features which separate D3 from other frameworks:
As D3 uses the web standards such as HTML, CSS, SVG. It renders powerful visualization graphics.
Data driven approach allows D3 to retrieve the data from different web nodes or servers and analyze it furthermore to render visualizations. Moreover, it can also use static data for processing.
D3 allows variations in tools for creation of graphics. It is a basic structured table or a well analyzed pie chart. It’s libraries varies from the most basic tools to advanced set of resources. Even complex GIS Mapping can be done using D3. Even it allows the customize visualizations as per the need. Nevertheless, its all possible due to its support to Web Standards.
It even supports large datasets and makes the most use of its predefined libraries, thus enabling the users to reuse code.
Transitions and animations are supported and D3 manages the logic implicitly. Thus one doesn’t need to manage or create them explicitly. Animation rendering is responsive and supports fast transmission between internal states.
One of the key feature of D3 is that it supports DOM manipulation and is flexible enough to dynamically manage the properties of it’s handlers.
Syntax:D3 uses the JavaScript functions to carry out most of the selection, transition and data binding tasks. CSS also plays a key role in styling the components. Moreover, JavaScript functions can be scripted in such a way that they can read out data present in other formats.
Selection: Before working on a dataset, the major task to be carried out is selection, i.e. retrieval of data from dataset. D3 enables the selection task by passing a predetermined tag as a parameter to the select function.d3.selectAll("pre") // It select all elements defined under the <pre> tag .style("color", "cyan"); // set style "color" to value "cyan" colorSimilarly, one can work up on various datasets defined under specific tags. Parameters to selectAll() can be tag, class, identifier or attribute. Elements can be modified or added or removed or manipulated and all this is based entirely on data.
d3.selectAll("pre") // It select all elements defined under the <pre> tag .style("color", "cyan"); // set style "color" to value "cyan" color
Similarly, one can work up on various datasets defined under specific tags. Parameters to selectAll() can be tag, class, identifier or attribute. Elements can be modified or added or removed or manipulated and all this is based entirely on data.
Transitions: Transitions can make the values and attributes for a dataset dynamic.d3.selectAll("pre") // select all <pre> elements .transition("transitionEx") // Declaring transition named as "transitionEx" .delay(10) // transition starting after 10ms .duration(50); // transitioning during 50msIn above scenario, notice that for all the elements coming as a subset of pre tag, transitioned accordingly.
d3.selectAll("pre") // select all <pre> elements .transition("transitionEx") // Declaring transition named as "transitionEx" .delay(10) // transition starting after 10ms .duration(50); // transitioning during 50ms
In above scenario, notice that for all the elements coming as a subset of pre tag, transitioned accordingly.
For more advanced usages, D3 makes the use of loaded data for creation of objects and manipulation, attributes addition and transitioning is done accordingly. All these operations come under the Data Binding part.
Setting up D3.js environment: In order to make use of D3 for a website or webpage, first thing that needs to be taken care of is its installation or import of library into the webpage.
The D3 is an open source library. The source code is freely available on the D3.js website. Download the latest version of the library.(5.7.0 currently) Download D3 library from the source link[/caption]Unzip the .zip file which obtained after the completion of download. Locate the d3.min.js file which is the minimal version of D3 source code. Copy that file and include it in the root folder or the main library directory of web page. In webpage, include the d3.min.js file as shown.<!DOCTYPE html><html lang="en"> <head> <!--Adding the source file of D3 here --> <script src="../d3.min.js"></script> </head> <body> <script> // write your own d3 code here </script> </body></html>Note: D3 doesn’t support Internet Explorer 8 or its lower versions. Preferably use Safari/ Mozilla Firefox or Chrome.Example: The basic example shown below demonstrates the use of D3 for SVG object creation i.e. circle in scenario within in a HTML document.<!DOCTYPE html><htm><meta charset="utf-8"><body><svg width="960" height="500"></svg><script src="https://d3js.org/d3.v4.min.js"></script> <body> <div id="circle"></div> // Declaring the script type <script type="text/javascript"> // Creating a variable to store SVG attributes var myGraphic = d3.select("#circle") // applying the svg type attribute .append("svg") // initializing the width of the object pane .attr("width", 500) // initializing the height of the object pane .attr("height", 500); myGraphic.append("circle") // Outline color attribute set to blue .style("stroke", "blue") // Fill color attribute set to red .style("fill", "red") // Radius attribute set to 100 .attr("r", 100) // X-coordinate set to 300px .attr("cx", 300) // Y-coordinate set to 100px .attr("cy", 100) // applying action when the mouse pointer hovers over the circle .on("mouseover", function(){d3.select(this).style("fill", "lavender");}) .on("mouseout", function(){d3.select(this).style("fill", "red");}); </script></body></html>Output:Before Mouse move over:After Mouse move over:Moreover, animations, transitions, attributes can be added and manipulated with less efforts using a D3 framework. All the work of action handling can be done using helper functions. In above example, select() function performs the task of retrieval of an argument whereas append() adds attribute as a child to the selected argument. D3 focuses on abstraction and thus most of the inner actions or executions are hidden from the end user, thus making it more easy to use. The task of binding event is done in the above case with the help of .on() function which passes mouse events as an argument. Noticeably, anonymous function concepts are used in the D3 framework. Herein, anonymous function is passed as an argument.More complex actions can be done using the D3 framework such as retrieval of data from a different format of dataset such as .csv or JSON file.Advantages:D3 supports web standards such as HTML, CSS, SVG which are known to all programmers, thus it can be used easily by anyone. In short, D3 exposes the capabilities of web standards such as HTML5, CSS3 and SVG.It is quite lightweight and flexible with the code which is reusable, thus preferable.It gives a wider control to the user to manage the visualization and data then the other API’s or frameworks available.Being an open source framework, one can easily manipulate the source code of D3 as per his/her need.Disadvantages:D3 is not compatible with older versions of browsers. In case, if someone wishes to visualize the data with backward compatibility, the visualization might necessarily be static, because of poor compatibility.Security is still a challenge for D3. Data can’t easily be hidden or protected using D3.Applications: Its advantages is preferable in various data visualization fields. Some of the major domains wherein D3 is used is as follows:Basic charting and graph analytic visualizations.Network visualizations.Data dashboard development modules.Web Maps creation and synthesis.Interactive data representation.Related Article: HTML | SVG-BasicsMy Personal Notes
arrow_drop_upSave
The D3 is an open source library. The source code is freely available on the D3.js website. Download the latest version of the library.(5.7.0 currently) Download D3 library from the source link[/caption]
Unzip the .zip file which obtained after the completion of download. Locate the d3.min.js file which is the minimal version of D3 source code. Copy that file and include it in the root folder or the main library directory of web page. In webpage, include the d3.min.js file as shown.<!DOCTYPE html><html lang="en"> <head> <!--Adding the source file of D3 here --> <script src="../d3.min.js"></script> </head> <body> <script> // write your own d3 code here </script> </body></html>Note: D3 doesn’t support Internet Explorer 8 or its lower versions. Preferably use Safari/ Mozilla Firefox or Chrome.
<!DOCTYPE html><html lang="en"> <head> <!--Adding the source file of D3 here --> <script src="../d3.min.js"></script> </head> <body> <script> // write your own d3 code here </script> </body></html>
Note: D3 doesn’t support Internet Explorer 8 or its lower versions. Preferably use Safari/ Mozilla Firefox or Chrome.
Example: The basic example shown below demonstrates the use of D3 for SVG object creation i.e. circle in scenario within in a HTML document.<!DOCTYPE html><htm><meta charset="utf-8"><body><svg width="960" height="500"></svg><script src="https://d3js.org/d3.v4.min.js"></script> <body> <div id="circle"></div> // Declaring the script type <script type="text/javascript"> // Creating a variable to store SVG attributes var myGraphic = d3.select("#circle") // applying the svg type attribute .append("svg") // initializing the width of the object pane .attr("width", 500) // initializing the height of the object pane .attr("height", 500); myGraphic.append("circle") // Outline color attribute set to blue .style("stroke", "blue") // Fill color attribute set to red .style("fill", "red") // Radius attribute set to 100 .attr("r", 100) // X-coordinate set to 300px .attr("cx", 300) // Y-coordinate set to 100px .attr("cy", 100) // applying action when the mouse pointer hovers over the circle .on("mouseover", function(){d3.select(this).style("fill", "lavender");}) .on("mouseout", function(){d3.select(this).style("fill", "red");}); </script></body></html>Output:Before Mouse move over:After Mouse move over:Moreover, animations, transitions, attributes can be added and manipulated with less efforts using a D3 framework. All the work of action handling can be done using helper functions. In above example, select() function performs the task of retrieval of an argument whereas append() adds attribute as a child to the selected argument. D3 focuses on abstraction and thus most of the inner actions or executions are hidden from the end user, thus making it more easy to use. The task of binding event is done in the above case with the help of .on() function which passes mouse events as an argument. Noticeably, anonymous function concepts are used in the D3 framework. Herein, anonymous function is passed as an argument.More complex actions can be done using the D3 framework such as retrieval of data from a different format of dataset such as .csv or JSON file.Advantages:D3 supports web standards such as HTML, CSS, SVG which are known to all programmers, thus it can be used easily by anyone. In short, D3 exposes the capabilities of web standards such as HTML5, CSS3 and SVG.It is quite lightweight and flexible with the code which is reusable, thus preferable.It gives a wider control to the user to manage the visualization and data then the other API’s or frameworks available.Being an open source framework, one can easily manipulate the source code of D3 as per his/her need.Disadvantages:D3 is not compatible with older versions of browsers. In case, if someone wishes to visualize the data with backward compatibility, the visualization might necessarily be static, because of poor compatibility.Security is still a challenge for D3. Data can’t easily be hidden or protected using D3.Applications: Its advantages is preferable in various data visualization fields. Some of the major domains wherein D3 is used is as follows:Basic charting and graph analytic visualizations.Network visualizations.Data dashboard development modules.Web Maps creation and synthesis.Interactive data representation.Related Article: HTML | SVG-BasicsMy Personal Notes
arrow_drop_upSave
<!DOCTYPE html><htm><meta charset="utf-8"><body><svg width="960" height="500"></svg><script src="https://d3js.org/d3.v4.min.js"></script> <body> <div id="circle"></div> // Declaring the script type <script type="text/javascript"> // Creating a variable to store SVG attributes var myGraphic = d3.select("#circle") // applying the svg type attribute .append("svg") // initializing the width of the object pane .attr("width", 500) // initializing the height of the object pane .attr("height", 500); myGraphic.append("circle") // Outline color attribute set to blue .style("stroke", "blue") // Fill color attribute set to red .style("fill", "red") // Radius attribute set to 100 .attr("r", 100) // X-coordinate set to 300px .attr("cx", 300) // Y-coordinate set to 100px .attr("cy", 100) // applying action when the mouse pointer hovers over the circle .on("mouseover", function(){d3.select(this).style("fill", "lavender");}) .on("mouseout", function(){d3.select(this).style("fill", "red");}); </script></body></html>
Output:Before Mouse move over:After Mouse move over:
Moreover, animations, transitions, attributes can be added and manipulated with less efforts using a D3 framework. All the work of action handling can be done using helper functions. In above example, select() function performs the task of retrieval of an argument whereas append() adds attribute as a child to the selected argument. D3 focuses on abstraction and thus most of the inner actions or executions are hidden from the end user, thus making it more easy to use. The task of binding event is done in the above case with the help of .on() function which passes mouse events as an argument. Noticeably, anonymous function concepts are used in the D3 framework. Herein, anonymous function is passed as an argument.More complex actions can be done using the D3 framework such as retrieval of data from a different format of dataset such as .csv or JSON file.
Advantages:
D3 supports web standards such as HTML, CSS, SVG which are known to all programmers, thus it can be used easily by anyone. In short, D3 exposes the capabilities of web standards such as HTML5, CSS3 and SVG.
It is quite lightweight and flexible with the code which is reusable, thus preferable.
It gives a wider control to the user to manage the visualization and data then the other API’s or frameworks available.
Being an open source framework, one can easily manipulate the source code of D3 as per his/her need.
Disadvantages:
D3 is not compatible with older versions of browsers. In case, if someone wishes to visualize the data with backward compatibility, the visualization might necessarily be static, because of poor compatibility.
Security is still a challenge for D3. Data can’t easily be hidden or protected using D3.
Applications: Its advantages is preferable in various data visualization fields. Some of the major domains wherein D3 is used is as follows:
Basic charting and graph analytic visualizations.
Network visualizations.
Data dashboard development modules.
Web Maps creation and synthesis.
Interactive data representation.Related Article: HTML | SVG-BasicsMy Personal Notes
arrow_drop_upSave
Related Article: HTML | SVG-Basics
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to Open URL in New Tab using JavaScript ?
Set the value of an input field in JavaScript
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 24628,
"s": 24600,
"text": "\n15 Jan, 2019"
},
{
"code": null,
"e": 25854,
"s": 24628,
"text": "Introduction: The D3 is an abbreviation of Data Driven Documents, and D3.js is a resource JavaScript library for managing documents based on data. D3 is one of the most effective framework to work on data visualization. It allows the developer to create dynamic, interactive data visualizations in the browser with the help of HTML, CSS and SVG. The data visualization is the representation of filtered data in the form of picture and graphics. Graphical or pictorial representations presenting even complex data sets with ease. Also, comparative analytics or patterns can be easily traced with the help of data visualization, thus enabling the client to make decisions without much brainstorming. Such visualizations can be easily developed using frameworks such as D3.js. Mike Bostock wrote the D3 framework. Before D3, Protovis toolkit was widely used for Data Visualizations. Though there are many other frameworks for Data visualization, but D3.js has left its footmark because of its flexibility and learnability.Instead of working as a monolithic framework providing every conceivable feature, D3 solves the core of a problem by providing efficient manipulation of data. It reduces the overhead and allows flexibility."
},
{
"code": null,
"e": 26111,
"s": 25854,
"text": "Features: There are many other platforms or frameworks available for managing data visualization, but D3 has left all the other frameworks behind because of being extremely flexible. Following are the major features which separate D3 from other frameworks:"
},
{
"code": null,
"e": 26208,
"s": 26111,
"text": "As D3 uses the web standards such as HTML, CSS, SVG. It renders powerful visualization graphics."
},
{
"code": null,
"e": 26403,
"s": 26208,
"text": "Data driven approach allows D3 to retrieve the data from different web nodes or servers and analyze it furthermore to render visualizations. Moreover, it can also use static data for processing."
},
{
"code": null,
"e": 26774,
"s": 26403,
"text": "D3 allows variations in tools for creation of graphics. It is a basic structured table or a well analyzed pie chart. It’s libraries varies from the most basic tools to advanced set of resources. Even complex GIS Mapping can be done using D3. Even it allows the customize visualizations as per the need. Nevertheless, its all possible due to its support to Web Standards."
},
{
"code": null,
"e": 26897,
"s": 26774,
"text": "It even supports large datasets and makes the most use of its predefined libraries, thus enabling the users to reuse code."
},
{
"code": null,
"e": 27124,
"s": 26897,
"text": "Transitions and animations are supported and D3 manages the logic implicitly. Thus one doesn’t need to manage or create them explicitly. Animation rendering is responsive and supports fast transmission between internal states."
},
{
"code": null,
"e": 27268,
"s": 27124,
"text": "One of the key feature of D3 is that it supports DOM manipulation and is flexible enough to dynamically manage the properties of it’s handlers."
},
{
"code": null,
"e": 27547,
"s": 27268,
"text": "Syntax:D3 uses the JavaScript functions to carry out most of the selection, transition and data binding tasks. CSS also plays a key role in styling the components. Moreover, JavaScript functions can be scripted in such a way that they can read out data present in other formats."
},
{
"code": null,
"e": 28160,
"s": 27547,
"text": "Selection: Before working on a dataset, the major task to be carried out is selection, i.e. retrieval of data from dataset. D3 enables the selection task by passing a predetermined tag as a parameter to the select function.d3.selectAll(\"pre\") // It select all elements defined under the <pre> tag .style(\"color\", \"cyan\"); // set style \"color\" to value \"cyan\" colorSimilarly, one can work up on various datasets defined under specific tags. Parameters to selectAll() can be tag, class, identifier or attribute. Elements can be modified or added or removed or manipulated and all this is based entirely on data."
},
{
"code": "d3.selectAll(\"pre\") // It select all elements defined under the <pre> tag .style(\"color\", \"cyan\"); // set style \"color\" to value \"cyan\" color",
"e": 28305,
"s": 28160,
"text": null
},
{
"code": null,
"e": 28551,
"s": 28305,
"text": "Similarly, one can work up on various datasets defined under specific tags. Parameters to selectAll() can be tag, class, identifier or attribute. Elements can be modified or added or removed or manipulated and all this is based entirely on data."
},
{
"code": null,
"e": 28983,
"s": 28551,
"text": "Transitions: Transitions can make the values and attributes for a dataset dynamic.d3.selectAll(\"pre\") // select all <pre> elements .transition(\"transitionEx\") // Declaring transition named as \"transitionEx\" .delay(10) // transition starting after 10ms .duration(50); // transitioning during 50msIn above scenario, notice that for all the elements coming as a subset of pre tag, transitioned accordingly."
},
{
"code": "d3.selectAll(\"pre\") // select all <pre> elements .transition(\"transitionEx\") // Declaring transition named as \"transitionEx\" .delay(10) // transition starting after 10ms .duration(50); // transitioning during 50ms",
"e": 29225,
"s": 28983,
"text": null
},
{
"code": null,
"e": 29334,
"s": 29225,
"text": "In above scenario, notice that for all the elements coming as a subset of pre tag, transitioned accordingly."
},
{
"code": null,
"e": 29548,
"s": 29334,
"text": "For more advanced usages, D3 makes the use of loaded data for creation of objects and manipulation, attributes addition and transitioning is done accordingly. All these operations come under the Data Binding part."
},
{
"code": null,
"e": 29733,
"s": 29548,
"text": "Setting up D3.js environment: In order to make use of D3 for a website or webpage, first thing that needs to be taken care of is its installation or import of library into the webpage."
},
{
"code": null,
"e": 34191,
"s": 29733,
"text": "The D3 is an open source library. The source code is freely available on the D3.js website. Download the latest version of the library.(5.7.0 currently) Download D3 library from the source link[/caption]Unzip the .zip file which obtained after the completion of download. Locate the d3.min.js file which is the minimal version of D3 source code. Copy that file and include it in the root folder or the main library directory of web page. In webpage, include the d3.min.js file as shown.<!DOCTYPE html><html lang=\"en\"> <head> <!--Adding the source file of D3 here --> <script src=\"../d3.min.js\"></script> </head> <body> <script> // write your own d3 code here </script> </body></html>Note: D3 doesn’t support Internet Explorer 8 or its lower versions. Preferably use Safari/ Mozilla Firefox or Chrome.Example: The basic example shown below demonstrates the use of D3 for SVG object creation i.e. circle in scenario within in a HTML document.<!DOCTYPE html><htm><meta charset=\"utf-8\"><body><svg width=\"960\" height=\"500\"></svg><script src=\"https://d3js.org/d3.v4.min.js\"></script> <body> <div id=\"circle\"></div> // Declaring the script type <script type=\"text/javascript\"> // Creating a variable to store SVG attributes var myGraphic = d3.select(\"#circle\") // applying the svg type attribute .append(\"svg\") // initializing the width of the object pane .attr(\"width\", 500) // initializing the height of the object pane .attr(\"height\", 500); myGraphic.append(\"circle\") // Outline color attribute set to blue .style(\"stroke\", \"blue\") // Fill color attribute set to red .style(\"fill\", \"red\") // Radius attribute set to 100 .attr(\"r\", 100) // X-coordinate set to 300px .attr(\"cx\", 300) // Y-coordinate set to 100px .attr(\"cy\", 100) // applying action when the mouse pointer hovers over the circle .on(\"mouseover\", function(){d3.select(this).style(\"fill\", \"lavender\");}) .on(\"mouseout\", function(){d3.select(this).style(\"fill\", \"red\");}); </script></body></html>Output:Before Mouse move over:After Mouse move over:Moreover, animations, transitions, attributes can be added and manipulated with less efforts using a D3 framework. All the work of action handling can be done using helper functions. In above example, select() function performs the task of retrieval of an argument whereas append() adds attribute as a child to the selected argument. D3 focuses on abstraction and thus most of the inner actions or executions are hidden from the end user, thus making it more easy to use. The task of binding event is done in the above case with the help of .on() function which passes mouse events as an argument. Noticeably, anonymous function concepts are used in the D3 framework. Herein, anonymous function is passed as an argument.More complex actions can be done using the D3 framework such as retrieval of data from a different format of dataset such as .csv or JSON file.Advantages:D3 supports web standards such as HTML, CSS, SVG which are known to all programmers, thus it can be used easily by anyone. In short, D3 exposes the capabilities of web standards such as HTML5, CSS3 and SVG.It is quite lightweight and flexible with the code which is reusable, thus preferable.It gives a wider control to the user to manage the visualization and data then the other API’s or frameworks available.Being an open source framework, one can easily manipulate the source code of D3 as per his/her need.Disadvantages:D3 is not compatible with older versions of browsers. In case, if someone wishes to visualize the data with backward compatibility, the visualization might necessarily be static, because of poor compatibility.Security is still a challenge for D3. Data can’t easily be hidden or protected using D3.Applications: Its advantages is preferable in various data visualization fields. Some of the major domains wherein D3 is used is as follows:Basic charting and graph analytic visualizations.Network visualizations.Data dashboard development modules.Web Maps creation and synthesis.Interactive data representation.Related Article: HTML | SVG-BasicsMy Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 34395,
"s": 34191,
"text": "The D3 is an open source library. The source code is freely available on the D3.js website. Download the latest version of the library.(5.7.0 currently) Download D3 library from the source link[/caption]"
},
{
"code": null,
"e": 35071,
"s": 34395,
"text": "Unzip the .zip file which obtained after the completion of download. Locate the d3.min.js file which is the minimal version of D3 source code. Copy that file and include it in the root folder or the main library directory of web page. In webpage, include the d3.min.js file as shown.<!DOCTYPE html><html lang=\"en\"> <head> <!--Adding the source file of D3 here --> <script src=\"../d3.min.js\"></script> </head> <body> <script> // write your own d3 code here </script> </body></html>Note: D3 doesn’t support Internet Explorer 8 or its lower versions. Preferably use Safari/ Mozilla Firefox or Chrome."
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <!--Adding the source file of D3 here --> <script src=\"../d3.min.js\"></script> </head> <body> <script> // write your own d3 code here </script> </body></html>",
"e": 35347,
"s": 35071,
"text": null
},
{
"code": null,
"e": 35465,
"s": 35347,
"text": "Note: D3 doesn’t support Internet Explorer 8 or its lower versions. Preferably use Safari/ Mozilla Firefox or Chrome."
},
{
"code": null,
"e": 39045,
"s": 35465,
"text": "Example: The basic example shown below demonstrates the use of D3 for SVG object creation i.e. circle in scenario within in a HTML document.<!DOCTYPE html><htm><meta charset=\"utf-8\"><body><svg width=\"960\" height=\"500\"></svg><script src=\"https://d3js.org/d3.v4.min.js\"></script> <body> <div id=\"circle\"></div> // Declaring the script type <script type=\"text/javascript\"> // Creating a variable to store SVG attributes var myGraphic = d3.select(\"#circle\") // applying the svg type attribute .append(\"svg\") // initializing the width of the object pane .attr(\"width\", 500) // initializing the height of the object pane .attr(\"height\", 500); myGraphic.append(\"circle\") // Outline color attribute set to blue .style(\"stroke\", \"blue\") // Fill color attribute set to red .style(\"fill\", \"red\") // Radius attribute set to 100 .attr(\"r\", 100) // X-coordinate set to 300px .attr(\"cx\", 300) // Y-coordinate set to 100px .attr(\"cy\", 100) // applying action when the mouse pointer hovers over the circle .on(\"mouseover\", function(){d3.select(this).style(\"fill\", \"lavender\");}) .on(\"mouseout\", function(){d3.select(this).style(\"fill\", \"red\");}); </script></body></html>Output:Before Mouse move over:After Mouse move over:Moreover, animations, transitions, attributes can be added and manipulated with less efforts using a D3 framework. All the work of action handling can be done using helper functions. In above example, select() function performs the task of retrieval of an argument whereas append() adds attribute as a child to the selected argument. D3 focuses on abstraction and thus most of the inner actions or executions are hidden from the end user, thus making it more easy to use. The task of binding event is done in the above case with the help of .on() function which passes mouse events as an argument. Noticeably, anonymous function concepts are used in the D3 framework. Herein, anonymous function is passed as an argument.More complex actions can be done using the D3 framework such as retrieval of data from a different format of dataset such as .csv or JSON file.Advantages:D3 supports web standards such as HTML, CSS, SVG which are known to all programmers, thus it can be used easily by anyone. In short, D3 exposes the capabilities of web standards such as HTML5, CSS3 and SVG.It is quite lightweight and flexible with the code which is reusable, thus preferable.It gives a wider control to the user to manage the visualization and data then the other API’s or frameworks available.Being an open source framework, one can easily manipulate the source code of D3 as per his/her need.Disadvantages:D3 is not compatible with older versions of browsers. In case, if someone wishes to visualize the data with backward compatibility, the visualization might necessarily be static, because of poor compatibility.Security is still a challenge for D3. Data can’t easily be hidden or protected using D3.Applications: Its advantages is preferable in various data visualization fields. Some of the major domains wherein D3 is used is as follows:Basic charting and graph analytic visualizations.Network visualizations.Data dashboard development modules.Web Maps creation and synthesis.Interactive data representation.Related Article: HTML | SVG-BasicsMy Personal Notes\narrow_drop_upSave"
},
{
"code": "<!DOCTYPE html><htm><meta charset=\"utf-8\"><body><svg width=\"960\" height=\"500\"></svg><script src=\"https://d3js.org/d3.v4.min.js\"></script> <body> <div id=\"circle\"></div> // Declaring the script type <script type=\"text/javascript\"> // Creating a variable to store SVG attributes var myGraphic = d3.select(\"#circle\") // applying the svg type attribute .append(\"svg\") // initializing the width of the object pane .attr(\"width\", 500) // initializing the height of the object pane .attr(\"height\", 500); myGraphic.append(\"circle\") // Outline color attribute set to blue .style(\"stroke\", \"blue\") // Fill color attribute set to red .style(\"fill\", \"red\") // Radius attribute set to 100 .attr(\"r\", 100) // X-coordinate set to 300px .attr(\"cx\", 300) // Y-coordinate set to 100px .attr(\"cy\", 100) // applying action when the mouse pointer hovers over the circle .on(\"mouseover\", function(){d3.select(this).style(\"fill\", \"lavender\");}) .on(\"mouseout\", function(){d3.select(this).style(\"fill\", \"red\");}); </script></body></html>",
"e": 40357,
"s": 39045,
"text": null
},
{
"code": null,
"e": 40410,
"s": 40357,
"text": "Output:Before Mouse move over:After Mouse move over:"
},
{
"code": null,
"e": 41274,
"s": 40410,
"text": "Moreover, animations, transitions, attributes can be added and manipulated with less efforts using a D3 framework. All the work of action handling can be done using helper functions. In above example, select() function performs the task of retrieval of an argument whereas append() adds attribute as a child to the selected argument. D3 focuses on abstraction and thus most of the inner actions or executions are hidden from the end user, thus making it more easy to use. The task of binding event is done in the above case with the help of .on() function which passes mouse events as an argument. Noticeably, anonymous function concepts are used in the D3 framework. Herein, anonymous function is passed as an argument.More complex actions can be done using the D3 framework such as retrieval of data from a different format of dataset such as .csv or JSON file."
},
{
"code": null,
"e": 41286,
"s": 41274,
"text": "Advantages:"
},
{
"code": null,
"e": 41493,
"s": 41286,
"text": "D3 supports web standards such as HTML, CSS, SVG which are known to all programmers, thus it can be used easily by anyone. In short, D3 exposes the capabilities of web standards such as HTML5, CSS3 and SVG."
},
{
"code": null,
"e": 41580,
"s": 41493,
"text": "It is quite lightweight and flexible with the code which is reusable, thus preferable."
},
{
"code": null,
"e": 41700,
"s": 41580,
"text": "It gives a wider control to the user to manage the visualization and data then the other API’s or frameworks available."
},
{
"code": null,
"e": 41801,
"s": 41700,
"text": "Being an open source framework, one can easily manipulate the source code of D3 as per his/her need."
},
{
"code": null,
"e": 41816,
"s": 41801,
"text": "Disadvantages:"
},
{
"code": null,
"e": 42026,
"s": 41816,
"text": "D3 is not compatible with older versions of browsers. In case, if someone wishes to visualize the data with backward compatibility, the visualization might necessarily be static, because of poor compatibility."
},
{
"code": null,
"e": 42115,
"s": 42026,
"text": "Security is still a challenge for D3. Data can’t easily be hidden or protected using D3."
},
{
"code": null,
"e": 42256,
"s": 42115,
"text": "Applications: Its advantages is preferable in various data visualization fields. Some of the major domains wherein D3 is used is as follows:"
},
{
"code": null,
"e": 42306,
"s": 42256,
"text": "Basic charting and graph analytic visualizations."
},
{
"code": null,
"e": 42330,
"s": 42306,
"text": "Network visualizations."
},
{
"code": null,
"e": 42366,
"s": 42330,
"text": "Data dashboard development modules."
},
{
"code": null,
"e": 42399,
"s": 42366,
"text": "Web Maps creation and synthesis."
},
{
"code": null,
"e": 42501,
"s": 42399,
"text": "Interactive data representation.Related Article: HTML | SVG-BasicsMy Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 42536,
"s": 42501,
"text": "Related Article: HTML | SVG-Basics"
},
{
"code": null,
"e": 42543,
"s": 42536,
"text": "Picked"
},
{
"code": null,
"e": 42554,
"s": 42543,
"text": "JavaScript"
},
{
"code": null,
"e": 42571,
"s": 42554,
"text": "Web Technologies"
},
{
"code": null,
"e": 42669,
"s": 42571,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 42678,
"s": 42669,
"text": "Comments"
},
{
"code": null,
"e": 42691,
"s": 42678,
"text": "Old Comments"
},
{
"code": null,
"e": 42736,
"s": 42691,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 42797,
"s": 42736,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 42869,
"s": 42797,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 42915,
"s": 42869,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 42961,
"s": 42915,
"text": "Set the value of an input field in JavaScript"
},
{
"code": null,
"e": 43003,
"s": 42961,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 43036,
"s": 43003,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 43098,
"s": 43036,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 43141,
"s": 43098,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Consensus Theorem in Digital Logic - GeeksforGeeks
|
13 Dec, 2019
Prerequisite – Properties of Boolean algebra, Minimization of Boolean Functions
Redundancy theorem is used as a Boolean algebra trick in Digital Electronics. It is also known as Consensus Theorem:
AB + A'C + BC = AB + A'C
The consensus or resolvent of the terms AB and A’C is BC. It is the conjunction of all the unique literals of the terms, excluding the literal that appears unnegated in one term and negated in the other.
The conjunctive dual of this equation is:
(A+B).(A'+C).(B+C) = (A+B).(A'+C)
In the second line, we omit the third product term BC.Here, the term BC is known as Redundant term. In this way we use this theorem to simply the Boolean Algebra. Conditions for applying Redundancy theorem are:
Three variables must present in the expression.Here A, B and C are used as variables.Each variables is repeated twice.One variable must present in complemented form.
Three variables must present in the expression.Here A, B and C are used as variables.
Each variables is repeated twice.
One variable must present in complemented form.
After applying this theorem we can only take those terms which contains the complemented variable.
Proof – We can also prove it like this:
Y = AB + A'C + BC
Y = AB + A'C + BC.1
Y = AB + A'C + BC.(A + A')
Y = AB + A'C + ABC + A'BC
Y = AB(1 + C) + A'C(1 + B)
Y = AB + A'C
Example-1.
F = AB + BC' + AC
Here, we have three variables A, B and C and all are repeated twice. The variable C is present in complemented form. So, all the conditions are satisfied for applying this theorem.
After applying Redundancy theorem we can write only the terms containing complemented variables (i.e, C) and omit the Redundancy term i.e., AB.
.'. F = BC' + AC
Example-2.
F = (A + B).(A' + C).(B + C)
Three variables are present and all are repeated twice. The variable A is present in complemented form.Thus, all the three conditions of this theorem is satisfied.
After applying Redundancy theorem we can write only the terms containing complemented variables (i.e, A) and omit the Redundancy term i.e., (B + C).
.'. F = (A + B).(A' + C)
Consider the following equation:
Y = AB + A'C + BC
The third product term BC is a redundant consensus term. If A switches from 1 to 0 while B=1 and C=1, Y remains 1. During the transition of signal A in logic gates, both the first and second term may be 0 momentarily. The third term prevents a glitch since its value of 1 in this case is not affected by the transition of signal A.
Thus. it is important to remove Logic Redundancy because it causes unnecessary network complexity and raises the cost of implementation.
So, in this way we can minimize a Boolean expression to solve it.
Discrete Mathematics
Digital Electronics & Logic Design
Engineering Mathematics
GATE CS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
4-bit binary Adder-Subtractor
IEEE Standard 754 Floating Point Numbers
Difference between RAM and ROM
Difference between Unipolar, Polar and Bipolar Line Coding Schemes
Analog to Digital Conversion
Relationship between number of nodes and height of binary tree
Inequalities in LaTeX
Newton's Divided Difference Interpolation Formula
Discrete Mathematics | Hasse Diagrams
Mathematics | Walks, Trails, Paths, Cycles and Circuits in Graph
|
[
{
"code": null,
"e": 26836,
"s": 26808,
"text": "\n13 Dec, 2019"
},
{
"code": null,
"e": 26916,
"s": 26836,
"text": "Prerequisite – Properties of Boolean algebra, Minimization of Boolean Functions"
},
{
"code": null,
"e": 27033,
"s": 26916,
"text": "Redundancy theorem is used as a Boolean algebra trick in Digital Electronics. It is also known as Consensus Theorem:"
},
{
"code": null,
"e": 27060,
"s": 27033,
"text": " AB + A'C + BC = AB + A'C"
},
{
"code": null,
"e": 27264,
"s": 27060,
"text": "The consensus or resolvent of the terms AB and A’C is BC. It is the conjunction of all the unique literals of the terms, excluding the literal that appears unnegated in one term and negated in the other."
},
{
"code": null,
"e": 27306,
"s": 27264,
"text": "The conjunctive dual of this equation is:"
},
{
"code": null,
"e": 27340,
"s": 27306,
"text": "(A+B).(A'+C).(B+C) = (A+B).(A'+C)"
},
{
"code": null,
"e": 27551,
"s": 27340,
"text": "In the second line, we omit the third product term BC.Here, the term BC is known as Redundant term. In this way we use this theorem to simply the Boolean Algebra. Conditions for applying Redundancy theorem are:"
},
{
"code": null,
"e": 27717,
"s": 27551,
"text": "Three variables must present in the expression.Here A, B and C are used as variables.Each variables is repeated twice.One variable must present in complemented form."
},
{
"code": null,
"e": 27803,
"s": 27717,
"text": "Three variables must present in the expression.Here A, B and C are used as variables."
},
{
"code": null,
"e": 27837,
"s": 27803,
"text": "Each variables is repeated twice."
},
{
"code": null,
"e": 27885,
"s": 27837,
"text": "One variable must present in complemented form."
},
{
"code": null,
"e": 27984,
"s": 27885,
"text": "After applying this theorem we can only take those terms which contains the complemented variable."
},
{
"code": null,
"e": 28024,
"s": 27984,
"text": "Proof – We can also prove it like this:"
},
{
"code": null,
"e": 28168,
"s": 28024,
"text": "Y = AB + A'C + BC\nY = AB + A'C + BC.1\nY = AB + A'C + BC.(A + A')\nY = AB + A'C + ABC + A'BC\nY = AB(1 + C) + A'C(1 + B)\nY = AB + A'C "
},
{
"code": null,
"e": 28179,
"s": 28168,
"text": "Example-1."
},
{
"code": null,
"e": 28197,
"s": 28179,
"text": "F = AB + BC' + AC"
},
{
"code": null,
"e": 28378,
"s": 28197,
"text": "Here, we have three variables A, B and C and all are repeated twice. The variable C is present in complemented form. So, all the conditions are satisfied for applying this theorem."
},
{
"code": null,
"e": 28522,
"s": 28378,
"text": "After applying Redundancy theorem we can write only the terms containing complemented variables (i.e, C) and omit the Redundancy term i.e., AB."
},
{
"code": null,
"e": 28540,
"s": 28522,
"text": " .'. F = BC' + AC"
},
{
"code": null,
"e": 28551,
"s": 28540,
"text": "Example-2."
},
{
"code": null,
"e": 28580,
"s": 28551,
"text": "F = (A + B).(A' + C).(B + C)"
},
{
"code": null,
"e": 28744,
"s": 28580,
"text": "Three variables are present and all are repeated twice. The variable A is present in complemented form.Thus, all the three conditions of this theorem is satisfied."
},
{
"code": null,
"e": 28893,
"s": 28744,
"text": "After applying Redundancy theorem we can write only the terms containing complemented variables (i.e, A) and omit the Redundancy term i.e., (B + C)."
},
{
"code": null,
"e": 28918,
"s": 28893,
"text": ".'. F = (A + B).(A' + C)"
},
{
"code": null,
"e": 28951,
"s": 28918,
"text": "Consider the following equation:"
},
{
"code": null,
"e": 28969,
"s": 28951,
"text": "Y = AB + A'C + BC"
},
{
"code": null,
"e": 29301,
"s": 28969,
"text": "The third product term BC is a redundant consensus term. If A switches from 1 to 0 while B=1 and C=1, Y remains 1. During the transition of signal A in logic gates, both the first and second term may be 0 momentarily. The third term prevents a glitch since its value of 1 in this case is not affected by the transition of signal A."
},
{
"code": null,
"e": 29438,
"s": 29301,
"text": "Thus. it is important to remove Logic Redundancy because it causes unnecessary network complexity and raises the cost of implementation."
},
{
"code": null,
"e": 29504,
"s": 29438,
"text": "So, in this way we can minimize a Boolean expression to solve it."
},
{
"code": null,
"e": 29525,
"s": 29504,
"text": "Discrete Mathematics"
},
{
"code": null,
"e": 29560,
"s": 29525,
"text": "Digital Electronics & Logic Design"
},
{
"code": null,
"e": 29584,
"s": 29560,
"text": "Engineering Mathematics"
},
{
"code": null,
"e": 29592,
"s": 29584,
"text": "GATE CS"
},
{
"code": null,
"e": 29690,
"s": 29592,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29699,
"s": 29690,
"text": "Comments"
},
{
"code": null,
"e": 29712,
"s": 29699,
"text": "Old Comments"
},
{
"code": null,
"e": 29742,
"s": 29712,
"text": "4-bit binary Adder-Subtractor"
},
{
"code": null,
"e": 29783,
"s": 29742,
"text": "IEEE Standard 754 Floating Point Numbers"
},
{
"code": null,
"e": 29814,
"s": 29783,
"text": "Difference between RAM and ROM"
},
{
"code": null,
"e": 29881,
"s": 29814,
"text": "Difference between Unipolar, Polar and Bipolar Line Coding Schemes"
},
{
"code": null,
"e": 29910,
"s": 29881,
"text": "Analog to Digital Conversion"
},
{
"code": null,
"e": 29973,
"s": 29910,
"text": "Relationship between number of nodes and height of binary tree"
},
{
"code": null,
"e": 29995,
"s": 29973,
"text": "Inequalities in LaTeX"
},
{
"code": null,
"e": 30045,
"s": 29995,
"text": "Newton's Divided Difference Interpolation Formula"
},
{
"code": null,
"e": 30083,
"s": 30045,
"text": "Discrete Mathematics | Hasse Diagrams"
}
] |
C library function - strxfrm()
|
The C library function size_t strxfrm(char *dest, const char *src, size_t n) transforms the first n characters of the string src into current locale and place them in the string dest.
Following is the declaration for strxfrm() function.
size_t strxfrm(char *dest, const char *src, size_t n)
dest − This is the pointer to the destination array where the content is to be copied. It can be a null pointer if the argument for n is zero.
dest − This is the pointer to the destination array where the content is to be copied. It can be a null pointer if the argument for n is zero.
src − This is the C string to be transformed into current locale.
src − This is the C string to be transformed into current locale.
n − The maximum number of characters to be copied to str1.
n − The maximum number of characters to be copied to str1.
This function returns the length of the transformed string, not including the terminating null-character.
The following example shows the usage of strxfrm() function.
#include <stdio.h>
#include <string.h>
int main () {
char dest[20];
char src[20];
int len;
strcpy(src, "Tutorials Point");
len = strxfrm(dest, src, 20);
printf("Length of string |%s| is: |%d|", dest, len);
return(0);
}
Let us compile and run the above program that will produce the following result −
Length of string |Tutorials Point| is: |15|
12 Lectures
2 hours
Nishant Malik
12 Lectures
2.5 hours
Nishant Malik
48 Lectures
6.5 hours
Asif Hussain
12 Lectures
2 hours
Richa Maheshwari
20 Lectures
3.5 hours
Vandana Annavaram
44 Lectures
1 hours
Amit Diwan
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2191,
"s": 2007,
"text": "The C library function size_t strxfrm(char *dest, const char *src, size_t n) transforms the first n characters of the string src into current locale and place them in the string dest."
},
{
"code": null,
"e": 2244,
"s": 2191,
"text": "Following is the declaration for strxfrm() function."
},
{
"code": null,
"e": 2298,
"s": 2244,
"text": "size_t strxfrm(char *dest, const char *src, size_t n)"
},
{
"code": null,
"e": 2441,
"s": 2298,
"text": "dest − This is the pointer to the destination array where the content is to be copied. It can be a null pointer if the argument for n is zero."
},
{
"code": null,
"e": 2584,
"s": 2441,
"text": "dest − This is the pointer to the destination array where the content is to be copied. It can be a null pointer if the argument for n is zero."
},
{
"code": null,
"e": 2650,
"s": 2584,
"text": "src − This is the C string to be transformed into current locale."
},
{
"code": null,
"e": 2716,
"s": 2650,
"text": "src − This is the C string to be transformed into current locale."
},
{
"code": null,
"e": 2775,
"s": 2716,
"text": "n − The maximum number of characters to be copied to str1."
},
{
"code": null,
"e": 2834,
"s": 2775,
"text": "n − The maximum number of characters to be copied to str1."
},
{
"code": null,
"e": 2940,
"s": 2834,
"text": "This function returns the length of the transformed string, not including the terminating null-character."
},
{
"code": null,
"e": 3001,
"s": 2940,
"text": "The following example shows the usage of strxfrm() function."
},
{
"code": null,
"e": 3248,
"s": 3001,
"text": "#include <stdio.h>\n#include <string.h>\n\nint main () {\n char dest[20];\n char src[20];\n int len;\n\n strcpy(src, \"Tutorials Point\");\n len = strxfrm(dest, src, 20);\n\n printf(\"Length of string |%s| is: |%d|\", dest, len);\n \n return(0);\n}"
},
{
"code": null,
"e": 3330,
"s": 3248,
"text": "Let us compile and run the above program that will produce the following result −"
},
{
"code": null,
"e": 3375,
"s": 3330,
"text": "Length of string |Tutorials Point| is: |15|\n"
},
{
"code": null,
"e": 3408,
"s": 3375,
"text": "\n 12 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3423,
"s": 3408,
"text": " Nishant Malik"
},
{
"code": null,
"e": 3458,
"s": 3423,
"text": "\n 12 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3473,
"s": 3458,
"text": " Nishant Malik"
},
{
"code": null,
"e": 3508,
"s": 3473,
"text": "\n 48 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 3522,
"s": 3508,
"text": " Asif Hussain"
},
{
"code": null,
"e": 3555,
"s": 3522,
"text": "\n 12 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3573,
"s": 3555,
"text": " Richa Maheshwari"
},
{
"code": null,
"e": 3608,
"s": 3573,
"text": "\n 20 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 3627,
"s": 3608,
"text": " Vandana Annavaram"
},
{
"code": null,
"e": 3660,
"s": 3627,
"text": "\n 44 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3672,
"s": 3660,
"text": " Amit Diwan"
},
{
"code": null,
"e": 3679,
"s": 3672,
"text": " Print"
},
{
"code": null,
"e": 3690,
"s": 3679,
"text": " Add Notes"
}
] |
Introduction to Regression in Python with PyCaret | by Moez Ali | Towards Data Science
|
PyCaret is an open-source, low-code machine learning library in Python that automates machine learning workflows. It is an end-to-end machine learning and model management tool that speeds up the experiment cycle exponentially and makes you more productive.
In comparison with the other open-source machine learning libraries, PyCaret is an alternate low-code library that can be used to replace hundreds of lines of code with few lines only. This makes experiments exponentially fast and efficient. PyCaret is essentially a Python wrapper around several machine learning libraries and frameworks such as scikit-learn, XGBoost, LightGBM, CatBoost, spaCy, Optuna, Hyperopt, Ray, and a few more.
The design and simplicity of PyCaret are inspired by the emerging role of citizen data scientists, a term first used by Gartner. Citizen Data Scientists are power users who can perform both simple and moderately sophisticated analytical tasks that would previously have required more technical expertise.
To learn more about PyCaret, you can check the official website or GitHub.
In this tutorial we will learn:
Getting Data: How to import data from the PyCaret repository.
Setting up Environment: How to set up a regression experiment in PyCaret and get started with building regression models.
Create Model: How to create a model, perform cross-validation and evaluate regression metrics.
Tune Model: How to automatically tune the hyperparameters of a regression model.
Plot Model: How to analyze model performance using various plots.
Predict Model: How to make predictions on new/unseen data.
Save / Load Model: How to save/load a model for future use.
Installation is easy and will only take a few minutes. PyCaret’s default installation from pip only installs hard dependencies as listed in the requirements.txt file.
pip install pycaret
To install the full version:
pip install pycaret[full]
Regression analysis is a set of statistical processes for estimating the relationships between a dependent variable (often called the ‘outcome variable’, or ‘target’) and one or more independent variables (often called ‘features’, ‘predictors’, or ‘covariates’). The objective of regression in machine learning is to predict continuous values such as sales amount, quantity, temperature, etc.
Learn More about Regression
PyCaret’s Regression module (pycaret.regression) is a supervised machine learning module that is used for predicting continuous values/outcomes using various techniques and algorithms. Regression can be used for predicting values/outcomes such as sales, units sold, temperature, or any number which is continuous.
The PyCaret’s regression module has over 25 algorithms and 10 plots to analyze the performance of models. Be it hyper-parameter tuning, ensembling, or advanced techniques like stacking, PyCaret’s regression module has it all.
In this tutorial, we will use the dataset from PyCaret’s dataset repository. The data contains 6000 records for training. Short descriptions of each column are as follows:
ID: Uniquely identifies each observation (diamond)
Carat Weight: The weight of the diamond in metric carats. One carat is equal to 0.2 grams, roughly the same weight as a paperclip
Cut: One of five values indicating the cut of the diamond in the following order of desirability (Signature-Ideal, Ideal, Very Good, Good, Fair)
Color: One of six values indicating the diamond’s color in the following order of desirability (D, E, F — Colorless, G, H, I — Near-colorless)
Clarity: One of seven values indicating the diamond’s clarity in the following order of desirability (F — Flawless, IF — Internally Flawless, VVS1 or VVS2 — Very, Very Slightly Included, or VS1 or VS2 — Very Slightly Included, SI1 — Slightly Included)
Polish: One of four values indicating the diamond’s polish (ID — Ideal, EX — Excellent, VG — Very Good, G — Good)
Symmetry: One of four values indicating the diamond’s symmetry (ID — Ideal, EX — Excellent, VG — Very Good, G — Good)
Report: One of two values “AGSL” or “GIA” indicates which grading agency reported the qualities of the diamond qualities
Price: The amount in USD that the diamond is valued Target Column
from pycaret.datasets import get_datadataset = get_data('diamond')
#check the shape of datadataset.shape(6000, 8)
In order to demonstrate the use of the predict_model function on unseen data, a sample of 600 records has been withheld from the original dataset to be used for predictions. This should not be confused with a train/test split as this particular split is performed to simulate a real-life scenario. Another way to think about this is that these 600 records are not available at the time when this machine learning experiment was performed.
data = dataset.sample(frac=0.9, random_state=786)data_unseen = dataset.drop(data.index)data.reset_index(drop=True, inplace=True)data_unseen.reset_index(drop=True, inplace=True)print('Data for Modeling: ' + str(data.shape))print('Unseen Data For Predictions: ' + str(data_unseen.shape))>>> Data for Modeling: (5400, 8)>>> Unseen Data For Predictions: (600, 8)
The setup function initializes the environment in pycaret and creates the transformation pipeline to prepare the data for modeling and deployment. setup must be called before executing any other function in pycaret. It takes two mandatory parameters: a pandas dataframe and the name of the target column. All other parameters are optional and are used to customize the pre-processing pipeline (we will see them in later tutorials).
When setup is executed, PyCaret's inference algorithm will automatically infer the data types for all features based on certain properties. The data type should be inferred correctly but this is not always the case. To account for this, PyCaret displays a table containing the features and their inferred data types after setup function is executed. If all of the data types are correctly identified enter can be pressed to continue or quit can be typed to end the experiment.
Ensuring that the data types are correct is really important in PyCaret as it automatically performs multiple type-specific preprocessing tasks which are imperative for machine learning models.
Alternatively, you can also use numeric_features and categorical_features parameters in the setup to pre-define the data types.
from pycaret.regression import *s = setup(data = data, target = 'Price', session_id=123)
Once the setup has been successfully executed it displays the information grid which contains several important pieces of information. Most of the information is related to the pre-processing pipeline which is constructed when setup is executed. The majority of these features are out of scope for the purposes of this tutorial. However, a few important things to note at this stage include:
session_id: A pseudo-random number distributed as a seed in all functions for later reproducibility. If no session_id is passed, a random number is automatically generated that is distributed to all functions. In this experiment, the session_id is set as 123 for later reproducibility.
Original Data: Displays the original shape of the dataset. For this experiment, (5400, 8) means 5400 samples and 8 features including the target column.
Missing Values: When there are missing values in the original data, this will show as True. For this experiment, there are no missing values in the dataset.
Numeric Features: Number of features inferred as numeric. In this dataset, 1 out of 8 features is inferred as numeric.
Categorical Features: Number of features inferred as categorical. In this dataset, 6 out of 8 features are inferred as categorical.
Transformed Train Set: Displays the shape of the transformed training set. Notice that the original shape of (5400, 8) is transformed into (3779, 28) for the transformed train set. The number of features has increased from 8 to 28 due to categorical encoding
Transformed Test Set: Displays the shape of the transformed test/hold-out set. There are 1621 samples in the test/hold-out set. This split is based on the default value of 70/30 that can be changed using the train_size parameter in the setup .
Notice how a few tasks that are imperative to perform modeling are automatically handled, such as missing value imputation (in this case there are no missing values in training data, but we still need imputers for unseen data), categorical encoding, etc. Most of the parameters in the setup are optional and used for customizing the pre-processing pipeline. These parameters are out of scope for this tutorial but as you progress to the intermediate and expert levels, we will cover them in much greater detail.
Comparing all models to evaluate performance is the recommended starting point for modeling once the setup is completed (unless you exactly know what kind of model you need, which is often not the case). This function trains all models in the model library and scores them using k-fold cross-validation for metric evaluation. The output prints a scoring grid that shows average MAE, MSE, RMSE, R2, RMSLE, and MAPE across the folds (10 by default) along with the training time each model took.
best = compare_models()
One line of code and we have trained and evaluated over 20 models using cross-validation. The scoring grid printed above highlights the highest performing metric for comparison purposes only. The grid by default is sorted using R2 (highest to lowest) which can be changed by passing sort parameter. For example, compare_models(sort = 'RMSLE') will sort the grid by RMSLE (lower to higher since lower is better).
If you want to change the fold parameter from the default value 10 to a different value then you can use the fold parameter. For example compare_models(fold = 5) will compare all models on 5 fold cross-validation. Reducing the number of folds will improve the training time.
By default, the compare_models return the best performing model based on default sort order but can be used to return a list of top N models by using n_select parameter.
create_model is the most granular function in PyCaret and is often the foundation behind most of the PyCaret functionalities. As the name suggests this function trains and evaluates a model using cross-validation that can be set with the fold parameter. The output prints a scoring grid that shows MAE, MSE, RMSE, R2, RMSLE, and MAPE by fold.
For the remaining part of this tutorial, we will work with the below models as our candidate models. The selections are for illustration purposes only and do not necessarily mean they are the top-performing or ideal for this type of data.
AdaBoost Regressor (‘ada’)
Light Gradient Boosting Machine (‘lightgbm’)
Decision Tree (‘dt’)
There are 25 regressors available in the model library of PyCaret. To see a complete list of all regressors either check the docstring or use models function to see the library.
models()
ada = create_model('ada')
print(ada)>>> OUTPUTAdaBoostRegressor(base_estimator=None, learning_rate=1.0, loss='linear', n_estimators=50, random_state=123)
lightgbm = create_model('lightgbm')
dt = create_model('dt')
Notice that the Mean score of all models matches with the score printed in compare_models. This is because the metrics printed in the compare_models score grid are the average scores across all CV folds. Similar to the compare_models, if you want to change the fold parameter from the default value of 10 to a different value then you can use the fold parameter in the create_model function. For Example: create_model('dt', fold = 5) to create a Decision Tree using 5 fold cross-validation.
When a model is created using the create_model function it uses the default hyperparameters to train the model. In order to tune hyperparameters, the tune_model function is used. This function automatically tunes the hyperparameters of a model using RandomGridSearch on a pre-defined search space. The output prints a scoring grid that shows MAE, MSE, RMSE, R2, RMSLE, and MAPE by fold. To use the custom search grid, you can pass custom_grid parameter in the tune_model function.
tuned_ada = tune_model(ada)
print(tuned_ada)>>> OUTPUTAdaBoostRegressor(base_estimator=None, learning_rate=0.05, loss='linear',n_estimators=90, random_state=123)
import numpy as nplgbm_params = {'num_leaves': np.arange(10,200,10), 'max_depth': [int(x) for x in np.linspace(10, 110, num = 11)], 'learning_rate': np.arange(0.1,1,0.1) }tuned_lightgbm = tune_model(lightgbm, custom_grid = lgbm_params)
print(tuned_lightgbm)>>> OUTPUTLGBMRegressor(boosting_type='gbdt', class_weight=None, colsample_bytree=1.0, importance_type='split', learning_rate=0.1, max_depth=60, min_child_samples=20, min_child_weight=0.001, min_split_gain=0.0, n_estimators=100, n_jobs=-1, num_leaves=120, objective=None, random_state=123, reg_alpha=0.0, reg_lambda=0.0, silent=True, subsample=1.0, subsample_for_bin=200000, subsample_freq=0)
tuned_dt = tune_model(dt)
By default, tune_model optimizes R2 but this can be changed using THE optimize parameter. For example, tune_model(dt, optimize = 'MAE')will search for the hyperparameters of a Decision Tree Regressor that results in the lowest MAE instead of highest R2. For the purposes of this example, we have used the default metric R2 for the sake of simplicity only. The methodology behind selecting the right metric to evaluate a regressor is beyond the scope of this tutorial but if you would like to learn more about it, you can click here to develop an understanding of regression error metrics.
Metrics alone are not the only criteria you should consider when finalizing the best model for production. Other factors to consider include training time, the standard deviation of k-folds, etc. For now, let’s move forward considering the Tuned Light Gradient Boosting Machine stored in the tuned_lightgbm variable as our best model for the remainder of this tutorial.
Before model finalization, the plot_model function can be used to analyze the performance across different aspects such as Residuals Plot, Prediction Error, Feature Importance, etc. This function takes a trained model object and returns a plot based on the test / hold-out set.
There are over 10 plots available, please see the plot_model documentation for the list of available plots.
plot_model(tuned_lightgbm)
plot_model(tuned_lightgbm, plot = 'error')
plot_model(tuned_lightgbm, plot='feature')
Another way to analyze the performance of models is to use the evaluate_model function which displays a user interface for all of the available plots for a given model. It internally uses the plot_model function.
evaluate_model(tuned_lightgbm)
Before finalizing the model, it is advisable to perform one final check by predicting the test/hold-out set and reviewing the evaluation metrics. If you look at the information grid in Section 6 above, you will see that 30% (1621 samples) of the data has been separated out as a test/hold-out sample. All of the evaluation metrics we have seen above are cross-validated results based on the training set (70%) only. Now, using our final trained model stored in the tuned_lightgbm , we will predict the hold-out sample and evaluate the metrics to see if they are materially different than the CV results.
predict_model(tuned_lightgbm);
The R2 on the test/hold-out set is 0.9652 compared to 0.9708 achieved on tuned_lightgbm CV results (in section 10.2 above). This is not a significant difference. If there is a large variation between the test/hold-out and CV results, then this would normally indicate over-fitting but could also be due to several other factors and would require further investigation. In this case, we will move forward with finalizing the model and predicting on unseen data (the 10% that we had separated in the beginning and never exposed to PyCaret).
Model finalization is the last step in the experiment. A machine learning workflow in PyCaret starts with the setup, followed by comparing all models using compare_models and shortlisting a few candidate models (based on the metric of interest) to perform several modeling techniques such as hyperparameter tuning, ensembling, stacking, etc. This workflow will eventually lead you to the best model for use in making predictions on new and unseen data.
The finalize_model function fits the model onto the complete dataset including the test/hold-out sample (30% in this case). The purpose of this function is to train the model on the complete dataset before it is deployed in production.
final_lightgbm = finalize_model(tuned_lightgbm)print(final_lightgbm)>>> OUTPUTLGBMRegressor(boosting_type='gbdt', class_weight=None, colsample_bytree=1.0, importance_type='split', learning_rate=0.1, max_depth=60, min_child_samples=20, min_child_weight=0.001, min_split_gain=0.0, n_estimators=100, n_jobs=-1, num_leaves=120, objective=None, random_state=123, reg_alpha=0.0, reg_lambda=0.0, silent=True, subsample=1.0, subsample_for_bin=200000, subsample_freq=0)
Caution: One final word of caution. Once the model is finalized using the finalize_model, the entire dataset including the test/hold-out set is used for training. As such, if the model is used for predictions on the hold-out set after finalize_model is used, the information grid printed will be misleading as you are trying to predict on the same data that was used for modeling.
In order to demonstrate this point only, we will use final_lightgbm under predict_model to compare the information grid with the one above in section 12.
predict_model(final_lightgbm);
Notice how the R2 in the final_lightgbm has increased to 0.9891 from 0.9652, even though the model is the same. This is because the final_lightgbm variable is trained on the complete dataset including the test/hold-out set.
The predict_model function is used to predict the unseen/new dataset. The only difference from the section above is that this time we will pass the data_unseen parameter. data_unseen is the variable created at the beginning of the tutorial and contains 10% (600 samples) of the original dataset which was never exposed to PyCaret. (see section 5 for explanation)
unseen_predictions = predict_model(final_lightgbm, data=data_unseen)unseen_predictions.head()
The Label column is added onto the data_unseen set. The label is the predicted value using the final_lightgbm model. If you want predictions to be rounded, you can use the round parameter inside the predict_model. You can also check the metrics on this since you have an actual target column Price available. To do that we will use the pycaret.utils module.
from pycaret.utils import check_metriccheck_metric(unseen_predictions.Price, unseen_predictions.Label, 'R2')>>> OUTPUT0.9779
We have now finished the experiment by finalizing the tuned_lightgbm model which is now stored in final_lightgbm variable. We have also used the model stored in final_lightgbm to predict data_unseen. This brings us to the end of our experiment, but one question is still to be asked: What happens when you have more new data to predict? Do you have to go through the entire experiment again? The answer is no, PyCaret's inbuilt function save_model allows you to save the model along with the entire transformation pipeline for later use.
save_model(final_lightgbm,'Final LightGBM Model 25Nov2020')Transformation Pipeline and Model Successfully Saved>>> OUTPUT(Pipeline(memory=None, steps=[('dtypes', DataTypes_Auto_infer(categorical_features=[], display_types=True, features_todrop=[], id_columns=[], ml_usecase='regression', numerical_features=[], target='Price', time_features=[])), ('imputer', Simple_Imputer(categorical_strategy='not_available', fill_value_categorical=None, fill_value_numerical=None, numeric_strategy='... LGBMRegressor(boosting_type='gbdt', class_weight=None, colsample_bytree=1.0, importance_type='split', learning_rate=0.1, max_depth=60, min_child_samples=20, min_child_weight=0.001, min_split_gain=0.0, n_estimators=100, n_jobs=-1, num_leaves=120, objective=None, random_state=123, reg_alpha=0.0, reg_lambda=0.0, silent=True, subsample=1.0, subsample_for_bin=200000, subsample_freq=0)]], verbose=False), 'Final LightGBM Model 25Nov2020.pkl')
To load a saved model at a future date in the same or an alternative environment, we would use PyCaret’s load_model function and then easily apply the saved model on new unseen data for prediction.
saved_final_lightgbm = load_model('Final LightGBM Model 25Nov2020')Transformation Pipeline and Model Successfully Loaded
Once the model is loaded in the environment, you can simply use it to predict any new data using the same predict_model function. Below we have applied the loaded model to predict the same data_unseen that we used in section 13 above.
new_prediction = predict_model(saved_final_lightgbm, data=data_unseen)new_prediction.head()
Notice that the results of unseen_predictions and new_prediction are identical.
from pycaret.utils import check_metriccheck_metric(new_prediction.Price, new_prediction.Label, 'R2')0.9779
This tutorial has covered the entire machine learning pipeline from data ingestion, pre-processing, training the model, hyperparameter tuning, prediction, and saving the model for later use. We have completed all of these steps in less than 10 commands which are naturally constructed and very intuitive to remember such as create_model(), tune_model(), compare_models(). Re-creating the entire experiment without PyCaret would have taken well over 100 lines of code in most libraries.
We have only covered the basics of pycaret.regression. In the future tutorials we will go deeper into advanced pre-processing, ensembling, generalized stacking, and other techniques that allow you to fully customize your machine learning pipeline and are must know for any data scientist.
Thank you for reading 🙏
⭐ Tutorials New to PyCaret? Check out our official notebooks!📋 Example Notebooks created by the community.📙 Blog Tutorials and articles by contributors.📚 Documentation The detailed API docs of PyCaret📺 Video Tutorials Our video tutorial from various events.📢 Discussions Have questions? Engage with community and contributors.🛠️ Changelog Changes and version history.🌳 Roadmap PyCaret’s software and community development plan.
I write about PyCaret and its use-cases in the real world, If you would like to be notified automatically, you can follow me on Medium, LinkedIn, and Twitter.
|
[
{
"code": null,
"e": 305,
"s": 47,
"text": "PyCaret is an open-source, low-code machine learning library in Python that automates machine learning workflows. It is an end-to-end machine learning and model management tool that speeds up the experiment cycle exponentially and makes you more productive."
},
{
"code": null,
"e": 741,
"s": 305,
"text": "In comparison with the other open-source machine learning libraries, PyCaret is an alternate low-code library that can be used to replace hundreds of lines of code with few lines only. This makes experiments exponentially fast and efficient. PyCaret is essentially a Python wrapper around several machine learning libraries and frameworks such as scikit-learn, XGBoost, LightGBM, CatBoost, spaCy, Optuna, Hyperopt, Ray, and a few more."
},
{
"code": null,
"e": 1046,
"s": 741,
"text": "The design and simplicity of PyCaret are inspired by the emerging role of citizen data scientists, a term first used by Gartner. Citizen Data Scientists are power users who can perform both simple and moderately sophisticated analytical tasks that would previously have required more technical expertise."
},
{
"code": null,
"e": 1121,
"s": 1046,
"text": "To learn more about PyCaret, you can check the official website or GitHub."
},
{
"code": null,
"e": 1153,
"s": 1121,
"text": "In this tutorial we will learn:"
},
{
"code": null,
"e": 1215,
"s": 1153,
"text": "Getting Data: How to import data from the PyCaret repository."
},
{
"code": null,
"e": 1337,
"s": 1215,
"text": "Setting up Environment: How to set up a regression experiment in PyCaret and get started with building regression models."
},
{
"code": null,
"e": 1432,
"s": 1337,
"text": "Create Model: How to create a model, perform cross-validation and evaluate regression metrics."
},
{
"code": null,
"e": 1513,
"s": 1432,
"text": "Tune Model: How to automatically tune the hyperparameters of a regression model."
},
{
"code": null,
"e": 1579,
"s": 1513,
"text": "Plot Model: How to analyze model performance using various plots."
},
{
"code": null,
"e": 1638,
"s": 1579,
"text": "Predict Model: How to make predictions on new/unseen data."
},
{
"code": null,
"e": 1698,
"s": 1638,
"text": "Save / Load Model: How to save/load a model for future use."
},
{
"code": null,
"e": 1865,
"s": 1698,
"text": "Installation is easy and will only take a few minutes. PyCaret’s default installation from pip only installs hard dependencies as listed in the requirements.txt file."
},
{
"code": null,
"e": 1885,
"s": 1865,
"text": "pip install pycaret"
},
{
"code": null,
"e": 1914,
"s": 1885,
"text": "To install the full version:"
},
{
"code": null,
"e": 1940,
"s": 1914,
"text": "pip install pycaret[full]"
},
{
"code": null,
"e": 2333,
"s": 1940,
"text": "Regression analysis is a set of statistical processes for estimating the relationships between a dependent variable (often called the ‘outcome variable’, or ‘target’) and one or more independent variables (often called ‘features’, ‘predictors’, or ‘covariates’). The objective of regression in machine learning is to predict continuous values such as sales amount, quantity, temperature, etc."
},
{
"code": null,
"e": 2361,
"s": 2333,
"text": "Learn More about Regression"
},
{
"code": null,
"e": 2675,
"s": 2361,
"text": "PyCaret’s Regression module (pycaret.regression) is a supervised machine learning module that is used for predicting continuous values/outcomes using various techniques and algorithms. Regression can be used for predicting values/outcomes such as sales, units sold, temperature, or any number which is continuous."
},
{
"code": null,
"e": 2901,
"s": 2675,
"text": "The PyCaret’s regression module has over 25 algorithms and 10 plots to analyze the performance of models. Be it hyper-parameter tuning, ensembling, or advanced techniques like stacking, PyCaret’s regression module has it all."
},
{
"code": null,
"e": 3073,
"s": 2901,
"text": "In this tutorial, we will use the dataset from PyCaret’s dataset repository. The data contains 6000 records for training. Short descriptions of each column are as follows:"
},
{
"code": null,
"e": 3124,
"s": 3073,
"text": "ID: Uniquely identifies each observation (diamond)"
},
{
"code": null,
"e": 3254,
"s": 3124,
"text": "Carat Weight: The weight of the diamond in metric carats. One carat is equal to 0.2 grams, roughly the same weight as a paperclip"
},
{
"code": null,
"e": 3399,
"s": 3254,
"text": "Cut: One of five values indicating the cut of the diamond in the following order of desirability (Signature-Ideal, Ideal, Very Good, Good, Fair)"
},
{
"code": null,
"e": 3542,
"s": 3399,
"text": "Color: One of six values indicating the diamond’s color in the following order of desirability (D, E, F — Colorless, G, H, I — Near-colorless)"
},
{
"code": null,
"e": 3794,
"s": 3542,
"text": "Clarity: One of seven values indicating the diamond’s clarity in the following order of desirability (F — Flawless, IF — Internally Flawless, VVS1 or VVS2 — Very, Very Slightly Included, or VS1 or VS2 — Very Slightly Included, SI1 — Slightly Included)"
},
{
"code": null,
"e": 3908,
"s": 3794,
"text": "Polish: One of four values indicating the diamond’s polish (ID — Ideal, EX — Excellent, VG — Very Good, G — Good)"
},
{
"code": null,
"e": 4026,
"s": 3908,
"text": "Symmetry: One of four values indicating the diamond’s symmetry (ID — Ideal, EX — Excellent, VG — Very Good, G — Good)"
},
{
"code": null,
"e": 4147,
"s": 4026,
"text": "Report: One of two values “AGSL” or “GIA” indicates which grading agency reported the qualities of the diamond qualities"
},
{
"code": null,
"e": 4213,
"s": 4147,
"text": "Price: The amount in USD that the diamond is valued Target Column"
},
{
"code": null,
"e": 4280,
"s": 4213,
"text": "from pycaret.datasets import get_datadataset = get_data('diamond')"
},
{
"code": null,
"e": 4327,
"s": 4280,
"text": "#check the shape of datadataset.shape(6000, 8)"
},
{
"code": null,
"e": 4766,
"s": 4327,
"text": "In order to demonstrate the use of the predict_model function on unseen data, a sample of 600 records has been withheld from the original dataset to be used for predictions. This should not be confused with a train/test split as this particular split is performed to simulate a real-life scenario. Another way to think about this is that these 600 records are not available at the time when this machine learning experiment was performed."
},
{
"code": null,
"e": 5125,
"s": 4766,
"text": "data = dataset.sample(frac=0.9, random_state=786)data_unseen = dataset.drop(data.index)data.reset_index(drop=True, inplace=True)data_unseen.reset_index(drop=True, inplace=True)print('Data for Modeling: ' + str(data.shape))print('Unseen Data For Predictions: ' + str(data_unseen.shape))>>> Data for Modeling: (5400, 8)>>> Unseen Data For Predictions: (600, 8)"
},
{
"code": null,
"e": 5557,
"s": 5125,
"text": "The setup function initializes the environment in pycaret and creates the transformation pipeline to prepare the data for modeling and deployment. setup must be called before executing any other function in pycaret. It takes two mandatory parameters: a pandas dataframe and the name of the target column. All other parameters are optional and are used to customize the pre-processing pipeline (we will see them in later tutorials)."
},
{
"code": null,
"e": 6034,
"s": 5557,
"text": "When setup is executed, PyCaret's inference algorithm will automatically infer the data types for all features based on certain properties. The data type should be inferred correctly but this is not always the case. To account for this, PyCaret displays a table containing the features and their inferred data types after setup function is executed. If all of the data types are correctly identified enter can be pressed to continue or quit can be typed to end the experiment."
},
{
"code": null,
"e": 6228,
"s": 6034,
"text": "Ensuring that the data types are correct is really important in PyCaret as it automatically performs multiple type-specific preprocessing tasks which are imperative for machine learning models."
},
{
"code": null,
"e": 6356,
"s": 6228,
"text": "Alternatively, you can also use numeric_features and categorical_features parameters in the setup to pre-define the data types."
},
{
"code": null,
"e": 6445,
"s": 6356,
"text": "from pycaret.regression import *s = setup(data = data, target = 'Price', session_id=123)"
},
{
"code": null,
"e": 6837,
"s": 6445,
"text": "Once the setup has been successfully executed it displays the information grid which contains several important pieces of information. Most of the information is related to the pre-processing pipeline which is constructed when setup is executed. The majority of these features are out of scope for the purposes of this tutorial. However, a few important things to note at this stage include:"
},
{
"code": null,
"e": 7123,
"s": 6837,
"text": "session_id: A pseudo-random number distributed as a seed in all functions for later reproducibility. If no session_id is passed, a random number is automatically generated that is distributed to all functions. In this experiment, the session_id is set as 123 for later reproducibility."
},
{
"code": null,
"e": 7276,
"s": 7123,
"text": "Original Data: Displays the original shape of the dataset. For this experiment, (5400, 8) means 5400 samples and 8 features including the target column."
},
{
"code": null,
"e": 7433,
"s": 7276,
"text": "Missing Values: When there are missing values in the original data, this will show as True. For this experiment, there are no missing values in the dataset."
},
{
"code": null,
"e": 7552,
"s": 7433,
"text": "Numeric Features: Number of features inferred as numeric. In this dataset, 1 out of 8 features is inferred as numeric."
},
{
"code": null,
"e": 7684,
"s": 7552,
"text": "Categorical Features: Number of features inferred as categorical. In this dataset, 6 out of 8 features are inferred as categorical."
},
{
"code": null,
"e": 7943,
"s": 7684,
"text": "Transformed Train Set: Displays the shape of the transformed training set. Notice that the original shape of (5400, 8) is transformed into (3779, 28) for the transformed train set. The number of features has increased from 8 to 28 due to categorical encoding"
},
{
"code": null,
"e": 8187,
"s": 7943,
"text": "Transformed Test Set: Displays the shape of the transformed test/hold-out set. There are 1621 samples in the test/hold-out set. This split is based on the default value of 70/30 that can be changed using the train_size parameter in the setup ."
},
{
"code": null,
"e": 8699,
"s": 8187,
"text": "Notice how a few tasks that are imperative to perform modeling are automatically handled, such as missing value imputation (in this case there are no missing values in training data, but we still need imputers for unseen data), categorical encoding, etc. Most of the parameters in the setup are optional and used for customizing the pre-processing pipeline. These parameters are out of scope for this tutorial but as you progress to the intermediate and expert levels, we will cover them in much greater detail."
},
{
"code": null,
"e": 9192,
"s": 8699,
"text": "Comparing all models to evaluate performance is the recommended starting point for modeling once the setup is completed (unless you exactly know what kind of model you need, which is often not the case). This function trains all models in the model library and scores them using k-fold cross-validation for metric evaluation. The output prints a scoring grid that shows average MAE, MSE, RMSE, R2, RMSLE, and MAPE across the folds (10 by default) along with the training time each model took."
},
{
"code": null,
"e": 9216,
"s": 9192,
"text": "best = compare_models()"
},
{
"code": null,
"e": 9628,
"s": 9216,
"text": "One line of code and we have trained and evaluated over 20 models using cross-validation. The scoring grid printed above highlights the highest performing metric for comparison purposes only. The grid by default is sorted using R2 (highest to lowest) which can be changed by passing sort parameter. For example, compare_models(sort = 'RMSLE') will sort the grid by RMSLE (lower to higher since lower is better)."
},
{
"code": null,
"e": 9903,
"s": 9628,
"text": "If you want to change the fold parameter from the default value 10 to a different value then you can use the fold parameter. For example compare_models(fold = 5) will compare all models on 5 fold cross-validation. Reducing the number of folds will improve the training time."
},
{
"code": null,
"e": 10073,
"s": 9903,
"text": "By default, the compare_models return the best performing model based on default sort order but can be used to return a list of top N models by using n_select parameter."
},
{
"code": null,
"e": 10416,
"s": 10073,
"text": "create_model is the most granular function in PyCaret and is often the foundation behind most of the PyCaret functionalities. As the name suggests this function trains and evaluates a model using cross-validation that can be set with the fold parameter. The output prints a scoring grid that shows MAE, MSE, RMSE, R2, RMSLE, and MAPE by fold."
},
{
"code": null,
"e": 10655,
"s": 10416,
"text": "For the remaining part of this tutorial, we will work with the below models as our candidate models. The selections are for illustration purposes only and do not necessarily mean they are the top-performing or ideal for this type of data."
},
{
"code": null,
"e": 10682,
"s": 10655,
"text": "AdaBoost Regressor (‘ada’)"
},
{
"code": null,
"e": 10727,
"s": 10682,
"text": "Light Gradient Boosting Machine (‘lightgbm’)"
},
{
"code": null,
"e": 10748,
"s": 10727,
"text": "Decision Tree (‘dt’)"
},
{
"code": null,
"e": 10926,
"s": 10748,
"text": "There are 25 regressors available in the model library of PyCaret. To see a complete list of all regressors either check the docstring or use models function to see the library."
},
{
"code": null,
"e": 10935,
"s": 10926,
"text": "models()"
},
{
"code": null,
"e": 10961,
"s": 10935,
"text": "ada = create_model('ada')"
},
{
"code": null,
"e": 11089,
"s": 10961,
"text": "print(ada)>>> OUTPUTAdaBoostRegressor(base_estimator=None, learning_rate=1.0, loss='linear', n_estimators=50, random_state=123)"
},
{
"code": null,
"e": 11125,
"s": 11089,
"text": "lightgbm = create_model('lightgbm')"
},
{
"code": null,
"e": 11149,
"s": 11125,
"text": "dt = create_model('dt')"
},
{
"code": null,
"e": 11640,
"s": 11149,
"text": "Notice that the Mean score of all models matches with the score printed in compare_models. This is because the metrics printed in the compare_models score grid are the average scores across all CV folds. Similar to the compare_models, if you want to change the fold parameter from the default value of 10 to a different value then you can use the fold parameter in the create_model function. For Example: create_model('dt', fold = 5) to create a Decision Tree using 5 fold cross-validation."
},
{
"code": null,
"e": 12121,
"s": 11640,
"text": "When a model is created using the create_model function it uses the default hyperparameters to train the model. In order to tune hyperparameters, the tune_model function is used. This function automatically tunes the hyperparameters of a model using RandomGridSearch on a pre-defined search space. The output prints a scoring grid that shows MAE, MSE, RMSE, R2, RMSLE, and MAPE by fold. To use the custom search grid, you can pass custom_grid parameter in the tune_model function."
},
{
"code": null,
"e": 12149,
"s": 12121,
"text": "tuned_ada = tune_model(ada)"
},
{
"code": null,
"e": 12283,
"s": 12149,
"text": "print(tuned_ada)>>> OUTPUTAdaBoostRegressor(base_estimator=None, learning_rate=0.05, loss='linear',n_estimators=90, random_state=123)"
},
{
"code": null,
"e": 12588,
"s": 12283,
"text": "import numpy as nplgbm_params = {'num_leaves': np.arange(10,200,10), 'max_depth': [int(x) for x in np.linspace(10, 110, num = 11)], 'learning_rate': np.arange(0.1,1,0.1) }tuned_lightgbm = tune_model(lightgbm, custom_grid = lgbm_params)"
},
{
"code": null,
"e": 13067,
"s": 12588,
"text": "print(tuned_lightgbm)>>> OUTPUTLGBMRegressor(boosting_type='gbdt', class_weight=None, colsample_bytree=1.0, importance_type='split', learning_rate=0.1, max_depth=60, min_child_samples=20, min_child_weight=0.001, min_split_gain=0.0, n_estimators=100, n_jobs=-1, num_leaves=120, objective=None, random_state=123, reg_alpha=0.0, reg_lambda=0.0, silent=True, subsample=1.0, subsample_for_bin=200000, subsample_freq=0)"
},
{
"code": null,
"e": 13093,
"s": 13067,
"text": "tuned_dt = tune_model(dt)"
},
{
"code": null,
"e": 13682,
"s": 13093,
"text": "By default, tune_model optimizes R2 but this can be changed using THE optimize parameter. For example, tune_model(dt, optimize = 'MAE')will search for the hyperparameters of a Decision Tree Regressor that results in the lowest MAE instead of highest R2. For the purposes of this example, we have used the default metric R2 for the sake of simplicity only. The methodology behind selecting the right metric to evaluate a regressor is beyond the scope of this tutorial but if you would like to learn more about it, you can click here to develop an understanding of regression error metrics."
},
{
"code": null,
"e": 14052,
"s": 13682,
"text": "Metrics alone are not the only criteria you should consider when finalizing the best model for production. Other factors to consider include training time, the standard deviation of k-folds, etc. For now, let’s move forward considering the Tuned Light Gradient Boosting Machine stored in the tuned_lightgbm variable as our best model for the remainder of this tutorial."
},
{
"code": null,
"e": 14330,
"s": 14052,
"text": "Before model finalization, the plot_model function can be used to analyze the performance across different aspects such as Residuals Plot, Prediction Error, Feature Importance, etc. This function takes a trained model object and returns a plot based on the test / hold-out set."
},
{
"code": null,
"e": 14438,
"s": 14330,
"text": "There are over 10 plots available, please see the plot_model documentation for the list of available plots."
},
{
"code": null,
"e": 14465,
"s": 14438,
"text": "plot_model(tuned_lightgbm)"
},
{
"code": null,
"e": 14508,
"s": 14465,
"text": "plot_model(tuned_lightgbm, plot = 'error')"
},
{
"code": null,
"e": 14551,
"s": 14508,
"text": "plot_model(tuned_lightgbm, plot='feature')"
},
{
"code": null,
"e": 14764,
"s": 14551,
"text": "Another way to analyze the performance of models is to use the evaluate_model function which displays a user interface for all of the available plots for a given model. It internally uses the plot_model function."
},
{
"code": null,
"e": 14795,
"s": 14764,
"text": "evaluate_model(tuned_lightgbm)"
},
{
"code": null,
"e": 15399,
"s": 14795,
"text": "Before finalizing the model, it is advisable to perform one final check by predicting the test/hold-out set and reviewing the evaluation metrics. If you look at the information grid in Section 6 above, you will see that 30% (1621 samples) of the data has been separated out as a test/hold-out sample. All of the evaluation metrics we have seen above are cross-validated results based on the training set (70%) only. Now, using our final trained model stored in the tuned_lightgbm , we will predict the hold-out sample and evaluate the metrics to see if they are materially different than the CV results."
},
{
"code": null,
"e": 15430,
"s": 15399,
"text": "predict_model(tuned_lightgbm);"
},
{
"code": null,
"e": 15969,
"s": 15430,
"text": "The R2 on the test/hold-out set is 0.9652 compared to 0.9708 achieved on tuned_lightgbm CV results (in section 10.2 above). This is not a significant difference. If there is a large variation between the test/hold-out and CV results, then this would normally indicate over-fitting but could also be due to several other factors and would require further investigation. In this case, we will move forward with finalizing the model and predicting on unseen data (the 10% that we had separated in the beginning and never exposed to PyCaret)."
},
{
"code": null,
"e": 16422,
"s": 15969,
"text": "Model finalization is the last step in the experiment. A machine learning workflow in PyCaret starts with the setup, followed by comparing all models using compare_models and shortlisting a few candidate models (based on the metric of interest) to perform several modeling techniques such as hyperparameter tuning, ensembling, stacking, etc. This workflow will eventually lead you to the best model for use in making predictions on new and unseen data."
},
{
"code": null,
"e": 16658,
"s": 16422,
"text": "The finalize_model function fits the model onto the complete dataset including the test/hold-out sample (30% in this case). The purpose of this function is to train the model on the complete dataset before it is deployed in production."
},
{
"code": null,
"e": 17184,
"s": 16658,
"text": "final_lightgbm = finalize_model(tuned_lightgbm)print(final_lightgbm)>>> OUTPUTLGBMRegressor(boosting_type='gbdt', class_weight=None, colsample_bytree=1.0, importance_type='split', learning_rate=0.1, max_depth=60, min_child_samples=20, min_child_weight=0.001, min_split_gain=0.0, n_estimators=100, n_jobs=-1, num_leaves=120, objective=None, random_state=123, reg_alpha=0.0, reg_lambda=0.0, silent=True, subsample=1.0, subsample_for_bin=200000, subsample_freq=0)"
},
{
"code": null,
"e": 17565,
"s": 17184,
"text": "Caution: One final word of caution. Once the model is finalized using the finalize_model, the entire dataset including the test/hold-out set is used for training. As such, if the model is used for predictions on the hold-out set after finalize_model is used, the information grid printed will be misleading as you are trying to predict on the same data that was used for modeling."
},
{
"code": null,
"e": 17719,
"s": 17565,
"text": "In order to demonstrate this point only, we will use final_lightgbm under predict_model to compare the information grid with the one above in section 12."
},
{
"code": null,
"e": 17750,
"s": 17719,
"text": "predict_model(final_lightgbm);"
},
{
"code": null,
"e": 17974,
"s": 17750,
"text": "Notice how the R2 in the final_lightgbm has increased to 0.9891 from 0.9652, even though the model is the same. This is because the final_lightgbm variable is trained on the complete dataset including the test/hold-out set."
},
{
"code": null,
"e": 18337,
"s": 17974,
"text": "The predict_model function is used to predict the unseen/new dataset. The only difference from the section above is that this time we will pass the data_unseen parameter. data_unseen is the variable created at the beginning of the tutorial and contains 10% (600 samples) of the original dataset which was never exposed to PyCaret. (see section 5 for explanation)"
},
{
"code": null,
"e": 18431,
"s": 18337,
"text": "unseen_predictions = predict_model(final_lightgbm, data=data_unseen)unseen_predictions.head()"
},
{
"code": null,
"e": 18789,
"s": 18431,
"text": "The Label column is added onto the data_unseen set. The label is the predicted value using the final_lightgbm model. If you want predictions to be rounded, you can use the round parameter inside the predict_model. You can also check the metrics on this since you have an actual target column Price available. To do that we will use the pycaret.utils module."
},
{
"code": null,
"e": 18914,
"s": 18789,
"text": "from pycaret.utils import check_metriccheck_metric(unseen_predictions.Price, unseen_predictions.Label, 'R2')>>> OUTPUT0.9779"
},
{
"code": null,
"e": 19452,
"s": 18914,
"text": "We have now finished the experiment by finalizing the tuned_lightgbm model which is now stored in final_lightgbm variable. We have also used the model stored in final_lightgbm to predict data_unseen. This brings us to the end of our experiment, but one question is still to be asked: What happens when you have more new data to predict? Do you have to go through the entire experiment again? The answer is no, PyCaret's inbuilt function save_model allows you to save the model along with the entire transformation pipeline for later use."
},
{
"code": null,
"e": 20963,
"s": 19452,
"text": "save_model(final_lightgbm,'Final LightGBM Model 25Nov2020')Transformation Pipeline and Model Successfully Saved>>> OUTPUT(Pipeline(memory=None, steps=[('dtypes', DataTypes_Auto_infer(categorical_features=[], display_types=True, features_todrop=[], id_columns=[], ml_usecase='regression', numerical_features=[], target='Price', time_features=[])), ('imputer', Simple_Imputer(categorical_strategy='not_available', fill_value_categorical=None, fill_value_numerical=None, numeric_strategy='... LGBMRegressor(boosting_type='gbdt', class_weight=None, colsample_bytree=1.0, importance_type='split', learning_rate=0.1, max_depth=60, min_child_samples=20, min_child_weight=0.001, min_split_gain=0.0, n_estimators=100, n_jobs=-1, num_leaves=120, objective=None, random_state=123, reg_alpha=0.0, reg_lambda=0.0, silent=True, subsample=1.0, subsample_for_bin=200000, subsample_freq=0)]], verbose=False), 'Final LightGBM Model 25Nov2020.pkl')"
},
{
"code": null,
"e": 21161,
"s": 20963,
"text": "To load a saved model at a future date in the same or an alternative environment, we would use PyCaret’s load_model function and then easily apply the saved model on new unseen data for prediction."
},
{
"code": null,
"e": 21282,
"s": 21161,
"text": "saved_final_lightgbm = load_model('Final LightGBM Model 25Nov2020')Transformation Pipeline and Model Successfully Loaded"
},
{
"code": null,
"e": 21517,
"s": 21282,
"text": "Once the model is loaded in the environment, you can simply use it to predict any new data using the same predict_model function. Below we have applied the loaded model to predict the same data_unseen that we used in section 13 above."
},
{
"code": null,
"e": 21609,
"s": 21517,
"text": "new_prediction = predict_model(saved_final_lightgbm, data=data_unseen)new_prediction.head()"
},
{
"code": null,
"e": 21689,
"s": 21609,
"text": "Notice that the results of unseen_predictions and new_prediction are identical."
},
{
"code": null,
"e": 21796,
"s": 21689,
"text": "from pycaret.utils import check_metriccheck_metric(new_prediction.Price, new_prediction.Label, 'R2')0.9779"
},
{
"code": null,
"e": 22282,
"s": 21796,
"text": "This tutorial has covered the entire machine learning pipeline from data ingestion, pre-processing, training the model, hyperparameter tuning, prediction, and saving the model for later use. We have completed all of these steps in less than 10 commands which are naturally constructed and very intuitive to remember such as create_model(), tune_model(), compare_models(). Re-creating the entire experiment without PyCaret would have taken well over 100 lines of code in most libraries."
},
{
"code": null,
"e": 22571,
"s": 22282,
"text": "We have only covered the basics of pycaret.regression. In the future tutorials we will go deeper into advanced pre-processing, ensembling, generalized stacking, and other techniques that allow you to fully customize your machine learning pipeline and are must know for any data scientist."
},
{
"code": null,
"e": 22595,
"s": 22571,
"text": "Thank you for reading 🙏"
},
{
"code": null,
"e": 23023,
"s": 22595,
"text": "⭐ Tutorials New to PyCaret? Check out our official notebooks!📋 Example Notebooks created by the community.📙 Blog Tutorials and articles by contributors.📚 Documentation The detailed API docs of PyCaret📺 Video Tutorials Our video tutorial from various events.📢 Discussions Have questions? Engage with community and contributors.🛠️ Changelog Changes and version history.🌳 Roadmap PyCaret’s software and community development plan."
}
] |
How to measure similarity between two correlation matrices | by Jin Hyun Cheong, PhD | Towards Data Science
|
Comparing the similarity between matrices can offer a way to assess the structural relationships among variables and is commonly used across disciplines such as neuroscience, epidemiology, and ecology.
Let’s assume you have data on how people react when watching a short Youtube video. This could be measured by facial expressions, heart rate, or breathing. A subject-by-subject similarity matrix of this data would represent how similar each person’s emotions were to every other subject. High similarity value in the matrix would mean that those individuals’ reactions were more similar than others.
You can compare this reaction similarity matrix with similarities in other factors such as demographics, interests, and/or preferences. This allows you to directly test if similarities in one domain (e.g. emotional reactions) can be explained by similarities in another (e.g. demographic/preference similarities).
This tutorial introduces the different metrics that can be used to measure similarity between similarity matrices and how to calculate the significance of those values.
Let’s simulate some data for analysis. We create a random data m1_u and m2_u that are related by the amount of noise added nr. Next, we create a correlation matrix for each underlying data using the default pandas correlation function. Let’s assume that the correlation matrix m1 represents how similar each subject’s reactions were to every other subject and m2 represents how similar each subject’s preferences were to one another.
We can simulate and visualize these matrices with the following code.
Now let’s see how we can test the similarity of these two matrices.
To measure the similarity between two correlation matrices you first need to extract either the top or the bottom triangle. They are symmetric but I recommend extracting the top triangle as it offers more consistency with other matrix functions when recasting the upper triangle back into a matrix.
The way to extract the upper triangle is simple. You can use the following function upper which leverages numpy functionality triu_indices. We can see from the figure below that the extracted upper triangle matches the original matrix.
Now that you have the matrices in simple vector forms, you can use the metric you need to measure similarity. The precise metric you use will depend on the properties of data you are working with but it is recommended to use a rank correlation such as a Spearman’s ρ or a Kendall’s τ. The benefit is that you don’t need to assume that similarity increases are linear and results will also be more robust to outliers.
In this example, let’s use the Spearman correlation to measure the similarity.
Which yields the following result of a Spearman rho of .15. The Spearman function also offers a p-value of .038, but using this would be inaccurate. Our data is non-independent meaning that each cell value from the upper matrix cannot be taken out independently without affecting other cells that arise from the same subject (learn more here). Alternatively, we can use the permutation testing approach outlined in Step 2.
Each cell value from our upper matrices are non-independent from one another. The independence is at the level of the subject which will be what we would be permuting.
In each iteration of the for loop in the function below, we shuffle the order of rows and columns from one of the correlation matrices, m1. We re-calculate the similarity between two matrices the amount of time we want to permute (e.g. 5000 times). After that, we can see how many values fall above our estimated value to obtain a p-value.
As shown in the figure above, our permuted p is more conservative at p=.042 than the one we obtained earlier at p=.038.
Comparing similarity matrices can help identify shared latent structures in the data across modalities. This tutorial offers a basic approach to assessing the similarity and calculating significance with a non-parametric permutation testing.
This approach can be extended in many ways. One extension would be to compare the average level of similarity between two correlation matrices. You can use the same approach of extracting the upper triangle and permuting the data to get significance for the difference. One thing to add however is that you’ll want to convert the Pearson’s R into a Z distribution using the Fisher transformation to make the distribution approximately normal.
Another extension would be to compare two distance matrices, such as geographical distance, Euclidean distance, or Mahalanobis distance. All you have to do is to create a distance matrix rather than correlation matrix. A real-world example with data comparing how distance between cities relates to average temperature differences is included in the full Colab notebook in the link below.
Author: Jin Hyun Cheong
import seaborn as sns
import numpy as np
import pandas as pd
import scipy.stats as stats
from scipy.spatial.distance import squareform
import matplotlib.pyplot as plt
# n is the number of subjects or items that will determine the size of the correlation matrix.
n = 20
data_length = 50
nr = .58
# Random data
np.random.seed(0)
m1_u = np.random.normal(loc=0, scale=1, size=(data_length, n))
m2_u = nr*np.random.normal(loc=0, scale=1, size=(data_length, n)) + (1-nr)*m1_u
m1 = pd.DataFrame(m1_u).corr()
m2 = pd.DataFrame(m2_u).corr()
f,axes = plt.subplots(1,2, figsize=(10,5))
sns.set_style("white")
for ix, m in enumerate([m1,m2]):
sns.heatmap(m, cmap="RdBu_r", center=0, vmin=-1, vmax=1, ax=axes[ix], square=True, cbar_kws={"shrink": .5}, xticklabels=True)
axes[ix].set(title=f"m{ix+1}")
def upper(df):
'''Returns the upper triangle of a correlation matrix.
You can use scipy.spatial.distance.squareform to recreate matrix from upper triangle.
Args:
df: pandas or numpy correlation matrix
Returns:
list of values from upper triangle
'''
try:
assert(type(df)==np.ndarray)
except:
if type(df)==pd.DataFrame:
df = df.values
else:
raise TypeError('Must be np.ndarray or pd.DataFrame')
mask = np.triu_indices(df.shape[0], k=1)
return df[mask]
# Compare that the upper triangle is properly extracted.
print("Extracted upper triangle from m1")
print(np.round(upper(m1)[:25],3))
print("Top 3 rows from m1")
display(m1.iloc[:3, :].round(3))
Extracted upper triangle from m1
[ 0.002 0.023 0.04 -0.024 -0.063 0.228 0.036 -0.035 0.056 0.034
0.003 0.181 0.367 0.022 0.079 -0.126 -0.222 0.075 0.011 0.235
-0.042 0.276 -0.065 0.069 -0.153]
Top 3 rows from m1
# You can go back to the original matrix using scipy's squareform.
# But note that the diagonal will be 0s.
recovered_m1 = pd.DataFrame(squareform(upper(m1))).round(2)
f,axes = plt.subplots(1,2, figsize=(10,5))
sns.set_style("white")
for ix, m in enumerate([m1,recovered_m1]):
sns.heatmap(m, cmap="RdBu_r", center=0, vmin=-1, vmax=1, ax=axes[ix], square=True, cbar_kws={"shrink": .5})
# Now lets measure the similarity
print(stats.spearmanr(upper(m1), upper(m2)))
SpearmanrResult(correlation=0.14991317735875465, pvalue=0.038974535666595055)
"""Nonparametric permutation testing Monte Carlo"""
np.random.seed(0)
rhos = []
n_iter = 5000
true_rho, _ = stats.spearmanr(upper(m1), upper(m2))
# matrix permutation, shuffle the groups
m_ids = list(m1.columns)
m2_v = upper(m2)
for iter in range(n_iter):
np.random.shuffle(m_ids) # shuffle list
r, _ = stats.spearmanr(upper(m1.loc[m_ids, m_ids]), m2_v)
rhos.append(r)
perm_p = ((np.sum(np.abs(true_rho) <= np.abs(rhos)))+1)/(n_iter+1) # two-tailed test
f,ax = plt.subplots()
plt.hist(rhos,bins=20)
ax.axvline(true_rho, color = 'r', linestyle='--')
ax.set(title=f"Permuted p: {perm_p:.3f}", ylabel="counts", xlabel="rho")
plt.show()
"""Real data of including latitude, longitude, average temperature, and city name.
References:
https://keisan.casio.com/exec/system/1224587128
https://en.wikipedia.org/wiki/List_of_cities_by_average_temperature
"""
seoul = (37.566535, 126.977969, 12.5, "Seoul")
tokyo = (35.676192, 139.650311, 15.4, "Tokyo")
sf = (37.77493, -122.419415, 14.6, "San Francisco")
la = (34.052234, -118.243685, 18.6, "Los Angeles")
chicago = (41.878114, -87.629798, 9.8, "Chicago")
beijing = (39.904211, 116.407395, 12.9, "Beijing")
cairo = (30.04442, 31.235712, 21.4, "Cairo")
moscow = (55.755826, 37.6173, 5.8, "Moscow")
sydney = (-33.86882, 151.209296, 17.7, "Sydney")
london =(51.507218, -0.127586, 11.3, "London")
paris = (48.856614, 2.352222, 12.3, "Paris")
berlin = (52.520007, 13.404954, 10.3, "Berlin")
rome = (41.902784, 12.496366, 15.2, "Rome")
lima = (-12.046373, -77.042754, 19.2, "Lima")
mexicocity = (19.432608, -99.133208, 17.5, "Mexico City")
capetown = (-33.924868, 18.424055, 16.2, "Cape Town")
newdelhi = (28.613939, 77.209021, 25, "New Delhi")
auckland = (-36.850883, 174.764488, 15.2, "Auckland")
saopaulo = (-23.555771, -46.639557, 19.2, "Sao Paulo")
madrid = (40.416775, -3.70379, 15, "Madrid")
bangkok = (13.756331, 100.501765, 28.6, "Bangkok")
phnompenh = (11.556374,104.92821, 28.3, "Phnom Penh")
mumbai = (19.075984, 72.877656, 27.1, "Mumbai")
singapore = (1.352083, 103.819836, 27, "Singapore")
vladivostok = (43.133248, 131.911297, 4.9, "Vladivostok")
city_list = [seoul, tokyo, sf, la, chicago, beijing, cairo, moscow, sydney, london, paris,
berlin, rome, lima, mexicocity, capetown, newdelhi, auckland, saopaulo, madrid,
bangkok, phnompenh, mumbai, singapore, vladivostok]
# Measure similarity
n = len(city_list)
city_names = [city[-1] for city in city_list]
m1 = pd.DataFrame(np.zeros((n,n)), index = city_names, columns = city_names)
m2 = pd.DataFrame(np.zeros((n,n)), index = city_names, columns = city_names)
for i, city1 in enumerate(city_list):
for j, city2 in enumerate(city_list):
# m1.iloc[i,j] = distance(city1[0], city1[1], city2[0], city2[1])
m1.iloc[i,j] = np.abs(city1[0]-city2[0])
m2.iloc[i,j] = np.abs(city1[2]-city2[2])
stats.spearmanr(upper(m1), upper(m2))
SpearmanrResult(correlation=0.21213613537496678, pvalue=0.00021460054002915316)
# Permute for significance
rhos = []
n_iter = 5000
true_rho, _ = stats.spearmanr(upper(m1), upper(m2))
# matrix permutation, shuffle the groups
m_ids = list(m1.columns)
m2_v = upper(m2)
for iter in range(n_iter):
np.random.shuffle(m_ids) # shuffle list
r, _ = stats.spearmanr(upper(m1.loc[m_ids, m_ids]), m2_v)
rhos.append(r)
perm_p = ((np.sum(np.abs(true_rho) <= np.abs(rhos)))+1)/(n_iter+1) # two-tailed test
f,ax = plt.subplots()
plt.hist(rhos,bins=20)
ax.axvline(true_rho, color = 'r', linestyle='--')
ax.set(title=f"Permuted p: {perm_p:.3f}", ylabel="counts", xlabel="rho")
plt.show()
Thank you for reading. If you liked this article, please consider subscribing and supporting writers like me by joining Medium through my referral link through which I will earn a small commission at no cost to you. Here are some other articles you might like:
|
[
{
"code": null,
"e": 374,
"s": 172,
"text": "Comparing the similarity between matrices can offer a way to assess the structural relationships among variables and is commonly used across disciplines such as neuroscience, epidemiology, and ecology."
},
{
"code": null,
"e": 774,
"s": 374,
"text": "Let’s assume you have data on how people react when watching a short Youtube video. This could be measured by facial expressions, heart rate, or breathing. A subject-by-subject similarity matrix of this data would represent how similar each person’s emotions were to every other subject. High similarity value in the matrix would mean that those individuals’ reactions were more similar than others."
},
{
"code": null,
"e": 1088,
"s": 774,
"text": "You can compare this reaction similarity matrix with similarities in other factors such as demographics, interests, and/or preferences. This allows you to directly test if similarities in one domain (e.g. emotional reactions) can be explained by similarities in another (e.g. demographic/preference similarities)."
},
{
"code": null,
"e": 1257,
"s": 1088,
"text": "This tutorial introduces the different metrics that can be used to measure similarity between similarity matrices and how to calculate the significance of those values."
},
{
"code": null,
"e": 1691,
"s": 1257,
"text": "Let’s simulate some data for analysis. We create a random data m1_u and m2_u that are related by the amount of noise added nr. Next, we create a correlation matrix for each underlying data using the default pandas correlation function. Let’s assume that the correlation matrix m1 represents how similar each subject’s reactions were to every other subject and m2 represents how similar each subject’s preferences were to one another."
},
{
"code": null,
"e": 1761,
"s": 1691,
"text": "We can simulate and visualize these matrices with the following code."
},
{
"code": null,
"e": 1829,
"s": 1761,
"text": "Now let’s see how we can test the similarity of these two matrices."
},
{
"code": null,
"e": 2128,
"s": 1829,
"text": "To measure the similarity between two correlation matrices you first need to extract either the top or the bottom triangle. They are symmetric but I recommend extracting the top triangle as it offers more consistency with other matrix functions when recasting the upper triangle back into a matrix."
},
{
"code": null,
"e": 2364,
"s": 2128,
"text": "The way to extract the upper triangle is simple. You can use the following function upper which leverages numpy functionality triu_indices. We can see from the figure below that the extracted upper triangle matches the original matrix."
},
{
"code": null,
"e": 2781,
"s": 2364,
"text": "Now that you have the matrices in simple vector forms, you can use the metric you need to measure similarity. The precise metric you use will depend on the properties of data you are working with but it is recommended to use a rank correlation such as a Spearman’s ρ or a Kendall’s τ. The benefit is that you don’t need to assume that similarity increases are linear and results will also be more robust to outliers."
},
{
"code": null,
"e": 2860,
"s": 2781,
"text": "In this example, let’s use the Spearman correlation to measure the similarity."
},
{
"code": null,
"e": 3283,
"s": 2860,
"text": "Which yields the following result of a Spearman rho of .15. The Spearman function also offers a p-value of .038, but using this would be inaccurate. Our data is non-independent meaning that each cell value from the upper matrix cannot be taken out independently without affecting other cells that arise from the same subject (learn more here). Alternatively, we can use the permutation testing approach outlined in Step 2."
},
{
"code": null,
"e": 3451,
"s": 3283,
"text": "Each cell value from our upper matrices are non-independent from one another. The independence is at the level of the subject which will be what we would be permuting."
},
{
"code": null,
"e": 3791,
"s": 3451,
"text": "In each iteration of the for loop in the function below, we shuffle the order of rows and columns from one of the correlation matrices, m1. We re-calculate the similarity between two matrices the amount of time we want to permute (e.g. 5000 times). After that, we can see how many values fall above our estimated value to obtain a p-value."
},
{
"code": null,
"e": 3911,
"s": 3791,
"text": "As shown in the figure above, our permuted p is more conservative at p=.042 than the one we obtained earlier at p=.038."
},
{
"code": null,
"e": 4153,
"s": 3911,
"text": "Comparing similarity matrices can help identify shared latent structures in the data across modalities. This tutorial offers a basic approach to assessing the similarity and calculating significance with a non-parametric permutation testing."
},
{
"code": null,
"e": 4596,
"s": 4153,
"text": "This approach can be extended in many ways. One extension would be to compare the average level of similarity between two correlation matrices. You can use the same approach of extracting the upper triangle and permuting the data to get significance for the difference. One thing to add however is that you’ll want to convert the Pearson’s R into a Z distribution using the Fisher transformation to make the distribution approximately normal."
},
{
"code": null,
"e": 4985,
"s": 4596,
"text": "Another extension would be to compare two distance matrices, such as geographical distance, Euclidean distance, or Mahalanobis distance. All you have to do is to create a distance matrix rather than correlation matrix. A real-world example with data comparing how distance between cities relates to average temperature differences is included in the full Colab notebook in the link below."
},
{
"code": null,
"e": 5009,
"s": 4985,
"text": "Author: Jin Hyun Cheong"
},
{
"code": null,
"e": 5808,
"s": 5009,
"text": "import seaborn as sns\nimport numpy as np\nimport pandas as pd\nimport scipy.stats as stats\nfrom scipy.spatial.distance import squareform\nimport matplotlib.pyplot as plt\n\n# n is the number of subjects or items that will determine the size of the correlation matrix. \nn = 20 \ndata_length = 50\nnr = .58\n\n# Random data\nnp.random.seed(0)\nm1_u = np.random.normal(loc=0, scale=1, size=(data_length, n))\nm2_u = nr*np.random.normal(loc=0, scale=1, size=(data_length, n)) + (1-nr)*m1_u\n\nm1 = pd.DataFrame(m1_u).corr()\nm2 = pd.DataFrame(m2_u).corr()\n\nf,axes = plt.subplots(1,2, figsize=(10,5))\nsns.set_style(\"white\")\nfor ix, m in enumerate([m1,m2]):\n sns.heatmap(m, cmap=\"RdBu_r\", center=0, vmin=-1, vmax=1, ax=axes[ix], square=True, cbar_kws={\"shrink\": .5}, xticklabels=True)\n axes[ix].set(title=f\"m{ix+1}\")\n"
},
{
"code": null,
"e": 6554,
"s": 5808,
"text": "def upper(df):\n '''Returns the upper triangle of a correlation matrix.\n\n You can use scipy.spatial.distance.squareform to recreate matrix from upper triangle.\n\n Args:\n df: pandas or numpy correlation matrix\n\n Returns:\n list of values from upper triangle\n '''\n try:\n assert(type(df)==np.ndarray)\n except:\n if type(df)==pd.DataFrame:\n df = df.values\n else:\n raise TypeError('Must be np.ndarray or pd.DataFrame')\n mask = np.triu_indices(df.shape[0], k=1)\n return df[mask]\n\n# Compare that the upper triangle is properly extracted. \nprint(\"Extracted upper triangle from m1\")\nprint(np.round(upper(m1)[:25],3))\nprint(\"Top 3 rows from m1\")\ndisplay(m1.iloc[:3, :].round(3))\n"
},
{
"code": null,
"e": 6786,
"s": 6554,
"text": "Extracted upper triangle from m1\n[ 0.002 0.023 0.04 -0.024 -0.063 0.228 0.036 -0.035 0.056 0.034\n 0.003 0.181 0.367 0.022 0.079 -0.126 -0.222 0.075 0.011 0.235\n -0.042 0.276 -0.065 0.069 -0.153]\nTop 3 rows from m1\n"
},
{
"code": null,
"e": 7177,
"s": 6786,
"text": "# You can go back to the original matrix using scipy's squareform. \n# But note that the diagonal will be 0s. \nrecovered_m1 = pd.DataFrame(squareform(upper(m1))).round(2)\n\nf,axes = plt.subplots(1,2, figsize=(10,5))\nsns.set_style(\"white\")\nfor ix, m in enumerate([m1,recovered_m1]):\n sns.heatmap(m, cmap=\"RdBu_r\", center=0, vmin=-1, vmax=1, ax=axes[ix], square=True, cbar_kws={\"shrink\": .5})\n"
},
{
"code": null,
"e": 7258,
"s": 7177,
"text": "# Now lets measure the similarity \nprint(stats.spearmanr(upper(m1), upper(m2)))\n"
},
{
"code": null,
"e": 7337,
"s": 7258,
"text": "SpearmanrResult(correlation=0.14991317735875465, pvalue=0.038974535666595055)\n"
},
{
"code": null,
"e": 7983,
"s": 7337,
"text": "\"\"\"Nonparametric permutation testing Monte Carlo\"\"\"\nnp.random.seed(0)\nrhos = []\nn_iter = 5000\ntrue_rho, _ = stats.spearmanr(upper(m1), upper(m2))\n# matrix permutation, shuffle the groups\nm_ids = list(m1.columns)\nm2_v = upper(m2)\nfor iter in range(n_iter):\n np.random.shuffle(m_ids) # shuffle list \n r, _ = stats.spearmanr(upper(m1.loc[m_ids, m_ids]), m2_v) \n rhos.append(r)\nperm_p = ((np.sum(np.abs(true_rho) <= np.abs(rhos)))+1)/(n_iter+1) # two-tailed test\n\n\nf,ax = plt.subplots()\nplt.hist(rhos,bins=20)\nax.axvline(true_rho, color = 'r', linestyle='--')\nax.set(title=f\"Permuted p: {perm_p:.3f}\", ylabel=\"counts\", xlabel=\"rho\")\nplt.show()\n"
},
{
"code": null,
"e": 9703,
"s": 7983,
"text": "\"\"\"Real data of including latitude, longitude, average temperature, and city name. \n\nReferences:\n https://keisan.casio.com/exec/system/1224587128\n https://en.wikipedia.org/wiki/List_of_cities_by_average_temperature\n\"\"\"\nseoul = (37.566535, 126.977969, 12.5, \"Seoul\")\ntokyo = (35.676192, 139.650311, 15.4, \"Tokyo\")\nsf = (37.77493, -122.419415, 14.6, \"San Francisco\")\nla = (34.052234, -118.243685, 18.6, \"Los Angeles\")\nchicago = (41.878114, -87.629798, 9.8, \"Chicago\")\nbeijing = (39.904211, 116.407395, 12.9, \"Beijing\")\ncairo = (30.04442, 31.235712, 21.4, \"Cairo\")\nmoscow = (55.755826, \t37.6173, 5.8, \"Moscow\")\nsydney = (-33.86882, 151.209296, 17.7, \"Sydney\")\nlondon =(51.507218, -0.127586, 11.3, \"London\")\nparis = (48.856614, 2.352222, 12.3, \"Paris\")\nberlin = (52.520007, 13.404954, 10.3, \"Berlin\")\nrome = (41.902784, 12.496366, 15.2, \"Rome\")\nlima = (-12.046373, -77.042754, 19.2, \"Lima\")\nmexicocity = (19.432608, -99.133208, 17.5, \"Mexico City\")\ncapetown = (-33.924868, 18.424055, 16.2, \"Cape Town\")\nnewdelhi = (28.613939, 77.209021, 25, \"New Delhi\")\nauckland = (-36.850883, 174.764488, 15.2, \"Auckland\")\nsaopaulo = (-23.555771, -46.639557, 19.2, \"Sao Paulo\")\nmadrid = (40.416775, -3.70379, 15, \"Madrid\")\nbangkok = (13.756331, 100.501765, 28.6, \"Bangkok\")\nphnompenh = (11.556374,104.92821, 28.3, \"Phnom Penh\")\nmumbai = (19.075984, 72.877656, 27.1, \"Mumbai\")\nsingapore = (1.352083, 103.819836, 27, \"Singapore\")\nvladivostok = (43.133248, 131.911297, 4.9, \"Vladivostok\")\ncity_list = [seoul, tokyo, sf, la, chicago, beijing, cairo, moscow, sydney, london, paris, \n berlin, rome, lima, mexicocity, capetown, newdelhi, auckland, saopaulo, madrid,\n bangkok, phnompenh, mumbai, singapore, vladivostok]\n"
},
{
"code": null,
"e": 10223,
"s": 9703,
"text": "# Measure similarity \nn = len(city_list)\ncity_names = [city[-1] for city in city_list]\nm1 = pd.DataFrame(np.zeros((n,n)), index = city_names, columns = city_names)\nm2 = pd.DataFrame(np.zeros((n,n)), index = city_names, columns = city_names)\nfor i, city1 in enumerate(city_list):\n for j, city2 in enumerate(city_list):\n # m1.iloc[i,j] = distance(city1[0], city1[1], city2[0], city2[1])\n m1.iloc[i,j] = np.abs(city1[0]-city2[0]) \n m2.iloc[i,j] = np.abs(city1[2]-city2[2])\n\nstats.spearmanr(upper(m1), upper(m2))\n"
},
{
"code": null,
"e": 10303,
"s": 10223,
"text": "SpearmanrResult(correlation=0.21213613537496678, pvalue=0.00021460054002915316)"
},
{
"code": null,
"e": 10905,
"s": 10303,
"text": "# Permute for significance\nrhos = []\nn_iter = 5000\ntrue_rho, _ = stats.spearmanr(upper(m1), upper(m2))\n# matrix permutation, shuffle the groups\nm_ids = list(m1.columns)\nm2_v = upper(m2)\nfor iter in range(n_iter):\n np.random.shuffle(m_ids) # shuffle list \n r, _ = stats.spearmanr(upper(m1.loc[m_ids, m_ids]), m2_v) \n rhos.append(r)\nperm_p = ((np.sum(np.abs(true_rho) <= np.abs(rhos)))+1)/(n_iter+1) # two-tailed test\n\nf,ax = plt.subplots()\nplt.hist(rhos,bins=20)\nax.axvline(true_rho, color = 'r', linestyle='--')\nax.set(title=f\"Permuted p: {perm_p:.3f}\", ylabel=\"counts\", xlabel=\"rho\")\nplt.show()\n"
}
] |
Java Math asin() method with Example - GeeksforGeeks
|
06 Apr, 2018
The java.lang.Math.asin() returns the arc sine of an angle in between -pi/2 and pi/2. Arc sine is also called as an inverse of a sine.
If the argument is NaN or its absolute value is greater than 1, then the result is NaN.
If the argument is zero, then the result is a zero with the same sign as the argument.
Syntax :
public static double asin(double angle)
Parameter :
angle : the value whose arc sine is to be returned.
Return :This method returns the arc sine of the argument.
Example 1 : To show working of java.lang.Math.asin() method.
// Java program to demonstrate working// of java.lang.Math.asin() methodimport java.lang.Math; class Gfg { // driver code public static void main(String args[]) { double a = Math.PI; // Output is NaN, because Math.PI gives 3.141 value // greater than 1 System.out.println(Math.asin(a)); // convert Math.PI to radians double b = Math.toRadians(a); System.out.println(Math.asin(b)); double c = 1.0; System.out.println(Math.asin(c)); double d = 0.0; System.out.println(Math.asin(d)); double e = -1.0; System.out.println(Math.asin(e)); double f = 1.5; // value of f does not lie in between -1 and 1 // so output is NaN System.out.println(Math.asin(f)); }}
Output:
NaN
0.054858647341251204
1.5707963267948966
0.0
-1.5707963267948966
NaN
Java-lang package
Java-Library
java-math
Java
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
HashMap in Java with Examples
Interfaces in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Singleton Class in Java
Multithreading in Java
Multidimensional Arrays in Java
Set in Java
|
[
{
"code": null,
"e": 25897,
"s": 25869,
"text": "\n06 Apr, 2018"
},
{
"code": null,
"e": 26032,
"s": 25897,
"text": "The java.lang.Math.asin() returns the arc sine of an angle in between -pi/2 and pi/2. Arc sine is also called as an inverse of a sine."
},
{
"code": null,
"e": 26120,
"s": 26032,
"text": "If the argument is NaN or its absolute value is greater than 1, then the result is NaN."
},
{
"code": null,
"e": 26207,
"s": 26120,
"text": "If the argument is zero, then the result is a zero with the same sign as the argument."
},
{
"code": null,
"e": 26216,
"s": 26207,
"text": "Syntax :"
},
{
"code": null,
"e": 26321,
"s": 26216,
"text": "public static double asin(double angle)\nParameter :\nangle : the value whose arc sine is to be returned.\n"
},
{
"code": null,
"e": 26379,
"s": 26321,
"text": "Return :This method returns the arc sine of the argument."
},
{
"code": null,
"e": 26440,
"s": 26379,
"text": "Example 1 : To show working of java.lang.Math.asin() method."
},
{
"code": "// Java program to demonstrate working// of java.lang.Math.asin() methodimport java.lang.Math; class Gfg { // driver code public static void main(String args[]) { double a = Math.PI; // Output is NaN, because Math.PI gives 3.141 value // greater than 1 System.out.println(Math.asin(a)); // convert Math.PI to radians double b = Math.toRadians(a); System.out.println(Math.asin(b)); double c = 1.0; System.out.println(Math.asin(c)); double d = 0.0; System.out.println(Math.asin(d)); double e = -1.0; System.out.println(Math.asin(e)); double f = 1.5; // value of f does not lie in between -1 and 1 // so output is NaN System.out.println(Math.asin(f)); }}",
"e": 27232,
"s": 26440,
"text": null
},
{
"code": null,
"e": 27240,
"s": 27232,
"text": "Output:"
},
{
"code": null,
"e": 27313,
"s": 27240,
"text": "NaN\n0.054858647341251204\n1.5707963267948966\n0.0\n-1.5707963267948966\nNaN\n"
},
{
"code": null,
"e": 27331,
"s": 27313,
"text": "Java-lang package"
},
{
"code": null,
"e": 27344,
"s": 27331,
"text": "Java-Library"
},
{
"code": null,
"e": 27354,
"s": 27344,
"text": "java-math"
},
{
"code": null,
"e": 27359,
"s": 27354,
"text": "Java"
},
{
"code": null,
"e": 27378,
"s": 27359,
"text": "Technical Scripter"
},
{
"code": null,
"e": 27383,
"s": 27378,
"text": "Java"
},
{
"code": null,
"e": 27481,
"s": 27383,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27496,
"s": 27481,
"text": "Stream In Java"
},
{
"code": null,
"e": 27526,
"s": 27496,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 27545,
"s": 27526,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 27563,
"s": 27545,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 27595,
"s": 27563,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 27615,
"s": 27595,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 27639,
"s": 27615,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 27662,
"s": 27639,
"text": "Multithreading in Java"
},
{
"code": null,
"e": 27694,
"s": 27662,
"text": "Multidimensional Arrays in Java"
}
] |
BigInteger Multiply | Practice | GeeksforGeeks
|
Given two BigIntegers X and Y. You have to multiply X and Y.
Example 1:
Input:
X = 3, Y = 4
Output:
12
Explanation:
Multiplication of X and Y is 12
Example 2:
Input:
X = 8, Y = 2
Output:
16
Explanation:
Multiplication of X and Y is 16.
Your Task:
Your task is to complete the function mul() which accepts x and y as input parameters and returns their multiplication.
Constraints:
1 <= X, Y, <= 1030
0
dell94593 weeks ago
Java:class MathematicalOperation{ static BigInteger mul(BigInteger x, BigInteger y){ // Your code here return x.multiply(y); } }
+1
badgujarsachin834 months ago
static BigInteger mul(BigInteger x, BigInteger y){
// Your code here
return x.multiply(y);
}
0
gautam2002pandeyjee6 months ago
Remember not use operator here because this is not an integer ..
This is a BigInteger..
So you can not use operator here ..
0
gaurav27919977 months ago
return x.multiply(y);
0
Achintya Veer Singh9 months ago
Achintya Veer Singh
Eeez:
static BigInteger mul(BigInteger x, BigInteger y){ return x.multiply(y); }
0
martial9 months ago
martial
https://uploads.disquscdn.c... https://uploads.disquscdn.c...
0
Sukanya Sinha1 year ago
Sukanya Sinha
return x.multiply(y);
-1
Tulsi Dey1 year ago
Tulsi Dey
Solution in Java:Execution time : 0.17
class MathematicalOperation{ static BigInteger mul(BigInteger x, BigInteger y){ return x.multiply(y); }}
0
Lakshya Khandelwal2 years ago
Lakshya Khandelwal
add cpp to pls
0
jyoti2 years ago
jyoti
https://github.com/jYOTIHAR...
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
|
[
{
"code": null,
"e": 287,
"s": 226,
"text": "Given two BigIntegers X and Y. You have to multiply X and Y."
},
{
"code": null,
"e": 300,
"s": 289,
"text": "Example 1:"
},
{
"code": null,
"e": 377,
"s": 300,
"text": "Input:\nX = 3, Y = 4\nOutput:\n12\nExplanation:\nMultiplication of X and Y is 12\n"
},
{
"code": null,
"e": 390,
"s": 379,
"text": "Example 2:"
},
{
"code": null,
"e": 468,
"s": 390,
"text": "Input:\nX = 8, Y = 2 \nOutput:\n16\nExplanation:\nMultiplication of X and Y is 16."
},
{
"code": null,
"e": 601,
"s": 470,
"text": "Your Task:\nYour task is to complete the function mul() which accepts x and y as input parameters and returns their multiplication."
},
{
"code": null,
"e": 635,
"s": 603,
"text": "Constraints:\n1 <= X, Y, <= 1030"
},
{
"code": null,
"e": 637,
"s": 635,
"text": "0"
},
{
"code": null,
"e": 657,
"s": 637,
"text": "dell94593 weeks ago"
},
{
"code": null,
"e": 810,
"s": 657,
"text": "Java:class MathematicalOperation{ static BigInteger mul(BigInteger x, BigInteger y){ // Your code here return x.multiply(y); } }"
},
{
"code": null,
"e": 813,
"s": 810,
"text": "+1"
},
{
"code": null,
"e": 842,
"s": 813,
"text": "badgujarsachin834 months ago"
},
{
"code": null,
"e": 980,
"s": 842,
"text": " static BigInteger mul(BigInteger x, BigInteger y){\n \n // Your code here\n return x.multiply(y);\n \n }\n "
},
{
"code": null,
"e": 982,
"s": 980,
"text": "0"
},
{
"code": null,
"e": 1014,
"s": 982,
"text": "gautam2002pandeyjee6 months ago"
},
{
"code": null,
"e": 1079,
"s": 1014,
"text": "Remember not use operator here because this is not an integer .."
},
{
"code": null,
"e": 1102,
"s": 1079,
"text": "This is a BigInteger.."
},
{
"code": null,
"e": 1138,
"s": 1102,
"text": "So you can not use operator here .."
},
{
"code": null,
"e": 1144,
"s": 1142,
"text": "0"
},
{
"code": null,
"e": 1170,
"s": 1144,
"text": "gaurav27919977 months ago"
},
{
"code": null,
"e": 1192,
"s": 1170,
"text": "return x.multiply(y);"
},
{
"code": null,
"e": 1194,
"s": 1192,
"text": "0"
},
{
"code": null,
"e": 1226,
"s": 1194,
"text": "Achintya Veer Singh9 months ago"
},
{
"code": null,
"e": 1246,
"s": 1226,
"text": "Achintya Veer Singh"
},
{
"code": null,
"e": 1252,
"s": 1246,
"text": "Eeez:"
},
{
"code": null,
"e": 1337,
"s": 1252,
"text": "static BigInteger mul(BigInteger x, BigInteger y){ return x.multiply(y); }"
},
{
"code": null,
"e": 1339,
"s": 1337,
"text": "0"
},
{
"code": null,
"e": 1359,
"s": 1339,
"text": "martial9 months ago"
},
{
"code": null,
"e": 1367,
"s": 1359,
"text": "martial"
},
{
"code": null,
"e": 1429,
"s": 1367,
"text": "https://uploads.disquscdn.c... https://uploads.disquscdn.c..."
},
{
"code": null,
"e": 1431,
"s": 1429,
"text": "0"
},
{
"code": null,
"e": 1455,
"s": 1431,
"text": "Sukanya Sinha1 year ago"
},
{
"code": null,
"e": 1469,
"s": 1455,
"text": "Sukanya Sinha"
},
{
"code": null,
"e": 1491,
"s": 1469,
"text": "return x.multiply(y);"
},
{
"code": null,
"e": 1494,
"s": 1491,
"text": "-1"
},
{
"code": null,
"e": 1514,
"s": 1494,
"text": "Tulsi Dey1 year ago"
},
{
"code": null,
"e": 1524,
"s": 1514,
"text": "Tulsi Dey"
},
{
"code": null,
"e": 1563,
"s": 1524,
"text": "Solution in Java:Execution time : 0.17"
},
{
"code": null,
"e": 1689,
"s": 1563,
"text": "class MathematicalOperation{ static BigInteger mul(BigInteger x, BigInteger y){ return x.multiply(y); }}"
},
{
"code": null,
"e": 1691,
"s": 1689,
"text": "0"
},
{
"code": null,
"e": 1721,
"s": 1691,
"text": "Lakshya Khandelwal2 years ago"
},
{
"code": null,
"e": 1740,
"s": 1721,
"text": "Lakshya Khandelwal"
},
{
"code": null,
"e": 1755,
"s": 1740,
"text": "add cpp to pls"
},
{
"code": null,
"e": 1757,
"s": 1755,
"text": "0"
},
{
"code": null,
"e": 1774,
"s": 1757,
"text": "jyoti2 years ago"
},
{
"code": null,
"e": 1780,
"s": 1774,
"text": "jyoti"
},
{
"code": null,
"e": 1811,
"s": 1780,
"text": "https://github.com/jYOTIHAR..."
},
{
"code": null,
"e": 1957,
"s": 1811,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 1993,
"s": 1957,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 2003,
"s": 1993,
"text": "\nProblem\n"
},
{
"code": null,
"e": 2013,
"s": 2003,
"text": "\nContest\n"
},
{
"code": null,
"e": 2076,
"s": 2013,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 2224,
"s": 2076,
"text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 2432,
"s": 2224,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints."
},
{
"code": null,
"e": 2538,
"s": 2432,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Count Inversions of size three in a given array - GeeksforGeeks
|
20 Jan, 2022
Given an array arr[] of size n. Three elements arr[i], arr[j] and arr[k] form an inversion of size 3 if a[i] > a[j] >a[k] and i < j < k. Find total number of inversions of size 3.Example :
Input: {8, 4, 2, 1}
Output: 4
The four inversions are (8,4,2), (8,4,1), (4,2,1) and (8,2,1).
Input: {9, 6, 4, 5, 8}
Output: 2
The two inversions are {9, 6, 4} and {9, 6, 5}
We have already discussed inversion count of size two by merge sort, Self Balancing BST and BIT.Simple approach :- Loop for all possible value of i, j and k and check for the condition a[i] > a[j] > a[k] and i < j < k.
C++
Java
Python3
C#
PHP
Javascript
// A Simple C++ O(n^3) program to count inversions of size 3#include<bits/stdc++.h>using namespace std; // Returns counts of inversions of size threeint getInvCount(int arr[],int n){ int invcount = 0; // Initialize result for (int i=0; i<n-2; i++) { for (int j=i+1; j<n-1; j++) { if (arr[i]>arr[j]) { for (int k=j+1; k<n; k++) { if (arr[j]>arr[k]) invcount++; } } } } return invcount;} // Driver program to test above functionint main(){ int arr[] = {8, 4, 2, 1}; int n = sizeof(arr)/sizeof(arr[0]); cout << "Inversion Count : " << getInvCount(arr, n); return 0;}
// A simple Java implementation to count inversion of size 3class Inversion{ // returns count of inversion of size 3 int getInvCount(int arr[], int n) { int invcount = 0; // initialize result for(int i=0 ; i< n-2; i++) { for(int j=i+1; j<n-1; j++) { if(arr[i] > arr[j]) { for(int k=j+1; k<n; k++) { if(arr[j] > arr[k]) invcount++; } } } } return invcount; } // driver program to test above function public static void main(String args[]) { Inversion inversion = new Inversion(); int arr[] = new int[] {8, 4, 2, 1}; int n = arr.length; System.out.print("Inversion count : " + inversion.getInvCount(arr, n)); }}// This code is contributed by Mayank Jaiswal
# A simple python O(n^3) program# to count inversions of size 3 # Returns counts of inversions# of size threeedef getInvCount(arr): n = len(arr) invcount = 0 #Initialize result for i in range(0,n-1): for j in range(i+1 , n): if arr[i] > arr[j]: for k in range(j+1 , n): if arr[j] > arr[k]: invcount += 1 return invcount # Driver program to test above functionarr = [8 , 4, 2 , 1]print ("Inversion Count : %d" %(getInvCount(arr))) # This code is contributed by Nikhil Kumar Singh(nickzuck_007)
// A simple C# implementation to// count inversion of size 3using System;class GFG { // returns count of inversion of size 3static int getInvCount(int []arr, int n) { // initialize result int invcount = 0; for(int i = 0 ; i < n - 2; i++) { for(int j = i + 1; j < n - 1; j++) { if(arr[i] > arr[j]) { for(int k = j + 1; k < n; k++) { if(arr[j] > arr[k]) invcount++; } } } } return invcount; } // Driver Code public static void Main() { int []arr = new int[] {8, 4, 2, 1}; int n = arr.Length; Console.WriteLine("Inversion count : " + getInvCount(arr, n)); }} // This code is contributed by anuj_67.
<?php// A O(n^2) PHP program to// count inversions of size 3 // Returns count of// inversions of size 3function getInvCount($arr, $n){ // Initialize result $invcount = 0; for ($i = 1; $i < $n - 1; $i++) { // Count all smaller elements // on right of arr[i] $small = 0; for($j = $i + 1; $j < $n; $j++) if ($arr[$i] > $arr[$j]) $small++; // Count all greater elements // on left of arr[i] $great = 0; for($j = $i - 1; $j >= 0; $j--) if ($arr[$i] < $arr[$j]) $great++; // Update inversion count by // adding all inversions // that have arr[i] as // middle of three elements $invcount += $great * $small; } return $invcount;} // Driver Code $arr = array(8, 4, 2, 1); $n = sizeof($arr); echo "Inversion Count : " , getInvCount($arr, $n); // This code is contributed m_kit?>
<script>// A simple Javascript implementation to count inversion of size 3 // returns count of inversion of size 3 function getInvCount(arr, n) { let invcount = 0; // initialize result for(let i = 0 ; i < n - 2; i++) { for(let j = i + 1; j < n - 1; j++) { if(arr[i] > arr[j]) { for(let k = j + 1; k < n; k++) { if(arr[j] > arr[k]) invcount++; } } } } return invcount; } // driver program to test above function let arr = [8, 4, 2, 1]; let n = arr.length; document.write("Inversion count : " + getInvCount(arr, n)); // This code is contributed by rag2127 </script>
Output:
Inversion Count : 4
Time complexity of this approach is : O(n^3)Better Approach : We can reduce the complexity if we consider every element arr[i] as middle element of inversion, find all the numbers greater than a[i] whose index is less than i, find all the numbers which are smaller than a[i] and index is more than i. We multiply the number of elements greater than a[i] to the number of elements smaller than a[i] and add it to the result. Below is the implementation of the idea.
C++
Java
Python3
C#
PHP
Javascript
// A O(n^2) C++ program to count inversions of size 3#include<bits/stdc++.h>using namespace std; // Returns count of inversions of size 3int getInvCount(int arr[], int n){ int invcount = 0; // Initialize result for (int i=1; i<n-1; i++) { // Count all smaller elements on right of arr[i] int small = 0; for (int j=i+1; j<n; j++) if (arr[i] > arr[j]) small++; // Count all greater elements on left of arr[i] int great = 0; for (int j=i-1; j>=0; j--) if (arr[i] < arr[j]) great++; // Update inversion count by adding all inversions // that have arr[i] as middle of three elements invcount += great*small; } return invcount;} // Driver program to test above functionint main(){ int arr[] = {8, 4, 2, 1}; int n = sizeof(arr)/sizeof(arr[0]); cout << "Inversion Count : " << getInvCount(arr, n); return 0;}
// A O(n^2) Java program to count inversions of size 3 class Inversion { // returns count of inversion of size 3 int getInvCount(int arr[], int n) { int invcount = 0; // initialize result for (int i=0 ; i< n-1; i++) { // count all smaller elements on right of arr[i] int small=0; for (int j=i+1; j<n; j++) if (arr[i] > arr[j]) small++; // count all greater elements on left of arr[i] int great = 0; for (int j=i-1; j>=0; j--) if (arr[i] < arr[j]) great++; // update inversion count by adding all inversions // that have arr[i] as middle of three elements invcount += great*small; } return invcount; } // driver program to test above function public static void main(String args[]) { Inversion inversion = new Inversion(); int arr[] = new int[] {8, 4, 2, 1}; int n = arr.length; System.out.print("Inversion count : " + inversion.getInvCount(arr, n)); }} // This code has been contributed by Mayank Jaiswal
# A O(n^2) Python3 program to# count inversions of size 3 # Returns count of inversions# of size 3def getInvCount(arr, n): # Initialize result invcount = 0 for i in range(1,n-1): # Count all smaller elements # on right of arr[i] small = 0 for j in range(i+1 ,n): if (arr[i] > arr[j]): small+=1 # Count all greater elements # on left of arr[i] great = 0; for j in range(i-1,-1,-1): if (arr[i] < arr[j]): great+=1 # Update inversion count by # adding all inversions that # have arr[i] as middle of # three elements invcount += great * small return invcount # Driver program to test above functionarr = [8, 4, 2, 1]n = len(arr)print("Inversion Count :",getInvCount(arr, n)) # This code is Contributed by Smitha Dinesh Semwal
// A O(n^2) Java program to count inversions// of size 3using System; public class Inversion { // returns count of inversion of size 3 static int getInvCount(int []arr, int n) { int invcount = 0; // initialize result for (int i = 0 ; i < n-1; i++) { // count all smaller elements on // right of arr[i] int small = 0; for (int j = i+1; j < n; j++) if (arr[i] > arr[j]) small++; // count all greater elements on // left of arr[i] int great = 0; for (int j = i-1; j >= 0; j--) if (arr[i] < arr[j]) great++; // update inversion count by // adding all inversions that // have arr[i] as middle of // three elements invcount += great * small; } return invcount; } // driver program to test above function public static void Main() { int []arr = new int[] {8, 4, 2, 1}; int n = arr.Length; Console.WriteLine("Inversion count : " + getInvCount(arr, n)); }} // This code has been contributed by anuj_67.
<?php// A O(n^2) PHP program to count// inversions of size 3 // Returns count of// inversions of size 3function getInvCount($arr, $n){ // Initialize result $invcount = 0; for ($i = 1; $i < $n - 1; $i++) { // Count all smaller elements // on right of arr[i] $small = 0; for ($j = $i + 1; $j < $n; $j++) if ($arr[$i] > $arr[$j]) $small++; // Count all greater elements // on left of arr[i] $great = 0; for ($j = $i - 1; $j >= 0; $j--) if ($arr[$i] < $arr[$j]) $great++; // Update inversion count by // adding all inversions that // have arr[i] as middle of // three elements $invcount += $great * $small; } return $invcount;} // Driver Code$arr = array (8, 4, 2, 1);$n = sizeof($arr);echo "Inversion Count : " , getInvCount($arr, $n); // This code is contributed by m_kit?>
<script>// A O(n^2) Javascript program to count inversions of size 3 // returns count of inversion of size 3 function getInvCount(arr, n) { let invcount = 0; // initialize result for (let i = 0 ; i < n - 1; i++) { // count all smaller elements on right of arr[i] let small = 0; for (let j = i + 1; j < n; j++) if (arr[i] > arr[j]) small++; // count all greater elements on left of arr[i] let great = 0; for (let j = i - 1; j >= 0; j--) if (arr[i] < arr[j]) great++; // update inversion count by adding all inversions // that have arr[i] as middle of three elements invcount += great*small; } return invcount; } // driver program to test above function let arr=[8, 4, 2, 1]; let n = arr.length; document.write("Inversion count : " +getInvCount(arr, n)); // This code is contributed by avanitrachhadiya2155</script>
Output :
Inversion Count : 4
Time Complexity of this approach : O(n^2)Binary Indexed Tree Approach : Like inversions of size 2, we can use Binary indexed tree to find inversions of size 3. It is strongly recommended to refer below article first.Count inversions of size two Using BITThe idea is similar to above method. We count the number of greater elements and smaller elements for all the elements and then multiply greater[] to smaller[] and add it to the result. Solution :
To find out the number of smaller elements for an index we iterate from n-1 to 0. For every element a[i] we calculate the getSum() function for (a[i]-1) which gives the number of elements till a[i]-1.To find out the number of greater elements for an index we iterate from 0 to n-1. For every element a[i] we calculate the sum of numbers till a[i] (sum smaller or equal to a[i]) by getSum() and subtract it from i (as i is the total number of element till that point) so that we can get number of elements greater than a[i].
To find out the number of smaller elements for an index we iterate from n-1 to 0. For every element a[i] we calculate the getSum() function for (a[i]-1) which gives the number of elements till a[i]-1.
To find out the number of greater elements for an index we iterate from 0 to n-1. For every element a[i] we calculate the sum of numbers till a[i] (sum smaller or equal to a[i]) by getSum() and subtract it from i (as i is the total number of element till that point) so that we can get number of elements greater than a[i].
jit_t
vt_m
ukasp
SHUBHAMSINGH10
rag2127
avanitrachhadiya2155
amartyaghoshgfg
Binary Indexed Tree
inversion
Advanced Data Structure
Arrays
Arrays
Binary Indexed Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Agents in Artificial Intelligence
Decision Tree Introduction with example
Disjoint Set Data Structures
Red-Black Tree | Set 2 (Insert)
AVL Tree | Set 2 (Deletion)
Arrays in Java
Arrays in C/C++
Program for array rotation
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews
|
[
{
"code": null,
"e": 24328,
"s": 24300,
"text": "\n20 Jan, 2022"
},
{
"code": null,
"e": 24519,
"s": 24328,
"text": "Given an array arr[] of size n. Three elements arr[i], arr[j] and arr[k] form an inversion of size 3 if a[i] > a[j] >a[k] and i < j < k. Find total number of inversions of size 3.Example : "
},
{
"code": null,
"e": 24696,
"s": 24519,
"text": "Input: {8, 4, 2, 1}\nOutput: 4\nThe four inversions are (8,4,2), (8,4,1), (4,2,1) and (8,2,1).\n\nInput: {9, 6, 4, 5, 8}\nOutput: 2\nThe two inversions are {9, 6, 4} and {9, 6, 5}"
},
{
"code": null,
"e": 24916,
"s": 24696,
"text": "We have already discussed inversion count of size two by merge sort, Self Balancing BST and BIT.Simple approach :- Loop for all possible value of i, j and k and check for the condition a[i] > a[j] > a[k] and i < j < k. "
},
{
"code": null,
"e": 24920,
"s": 24916,
"text": "C++"
},
{
"code": null,
"e": 24925,
"s": 24920,
"text": "Java"
},
{
"code": null,
"e": 24933,
"s": 24925,
"text": "Python3"
},
{
"code": null,
"e": 24936,
"s": 24933,
"text": "C#"
},
{
"code": null,
"e": 24940,
"s": 24936,
"text": "PHP"
},
{
"code": null,
"e": 24951,
"s": 24940,
"text": "Javascript"
},
{
"code": "// A Simple C++ O(n^3) program to count inversions of size 3#include<bits/stdc++.h>using namespace std; // Returns counts of inversions of size threeint getInvCount(int arr[],int n){ int invcount = 0; // Initialize result for (int i=0; i<n-2; i++) { for (int j=i+1; j<n-1; j++) { if (arr[i]>arr[j]) { for (int k=j+1; k<n; k++) { if (arr[j]>arr[k]) invcount++; } } } } return invcount;} // Driver program to test above functionint main(){ int arr[] = {8, 4, 2, 1}; int n = sizeof(arr)/sizeof(arr[0]); cout << \"Inversion Count : \" << getInvCount(arr, n); return 0;}",
"e": 25686,
"s": 24951,
"text": null
},
{
"code": "// A simple Java implementation to count inversion of size 3class Inversion{ // returns count of inversion of size 3 int getInvCount(int arr[], int n) { int invcount = 0; // initialize result for(int i=0 ; i< n-2; i++) { for(int j=i+1; j<n-1; j++) { if(arr[i] > arr[j]) { for(int k=j+1; k<n; k++) { if(arr[j] > arr[k]) invcount++; } } } } return invcount; } // driver program to test above function public static void main(String args[]) { Inversion inversion = new Inversion(); int arr[] = new int[] {8, 4, 2, 1}; int n = arr.length; System.out.print(\"Inversion count : \" + inversion.getInvCount(arr, n)); }}// This code is contributed by Mayank Jaiswal",
"e": 26648,
"s": 25686,
"text": null
},
{
"code": "# A simple python O(n^3) program# to count inversions of size 3 # Returns counts of inversions# of size threeedef getInvCount(arr): n = len(arr) invcount = 0 #Initialize result for i in range(0,n-1): for j in range(i+1 , n): if arr[i] > arr[j]: for k in range(j+1 , n): if arr[j] > arr[k]: invcount += 1 return invcount # Driver program to test above functionarr = [8 , 4, 2 , 1]print (\"Inversion Count : %d\" %(getInvCount(arr))) # This code is contributed by Nikhil Kumar Singh(nickzuck_007)",
"e": 27248,
"s": 26648,
"text": null
},
{
"code": "// A simple C# implementation to// count inversion of size 3using System;class GFG { // returns count of inversion of size 3static int getInvCount(int []arr, int n) { // initialize result int invcount = 0; for(int i = 0 ; i < n - 2; i++) { for(int j = i + 1; j < n - 1; j++) { if(arr[i] > arr[j]) { for(int k = j + 1; k < n; k++) { if(arr[j] > arr[k]) invcount++; } } } } return invcount; } // Driver Code public static void Main() { int []arr = new int[] {8, 4, 2, 1}; int n = arr.Length; Console.WriteLine(\"Inversion count : \" + getInvCount(arr, n)); }} // This code is contributed by anuj_67.",
"e": 28168,
"s": 27248,
"text": null
},
{
"code": "<?php// A O(n^2) PHP program to// count inversions of size 3 // Returns count of// inversions of size 3function getInvCount($arr, $n){ // Initialize result $invcount = 0; for ($i = 1; $i < $n - 1; $i++) { // Count all smaller elements // on right of arr[i] $small = 0; for($j = $i + 1; $j < $n; $j++) if ($arr[$i] > $arr[$j]) $small++; // Count all greater elements // on left of arr[i] $great = 0; for($j = $i - 1; $j >= 0; $j--) if ($arr[$i] < $arr[$j]) $great++; // Update inversion count by // adding all inversions // that have arr[i] as // middle of three elements $invcount += $great * $small; } return $invcount;} // Driver Code $arr = array(8, 4, 2, 1); $n = sizeof($arr); echo \"Inversion Count : \" , getInvCount($arr, $n); // This code is contributed m_kit?>",
"e": 29136,
"s": 28168,
"text": null
},
{
"code": "<script>// A simple Javascript implementation to count inversion of size 3 // returns count of inversion of size 3 function getInvCount(arr, n) { let invcount = 0; // initialize result for(let i = 0 ; i < n - 2; i++) { for(let j = i + 1; j < n - 1; j++) { if(arr[i] > arr[j]) { for(let k = j + 1; k < n; k++) { if(arr[j] > arr[k]) invcount++; } } } } return invcount; } // driver program to test above function let arr = [8, 4, 2, 1]; let n = arr.length; document.write(\"Inversion count : \" + getInvCount(arr, n)); // This code is contributed by rag2127 </script>",
"e": 29994,
"s": 29136,
"text": null
},
{
"code": null,
"e": 30002,
"s": 29994,
"text": "Output:"
},
{
"code": null,
"e": 30023,
"s": 30002,
"text": "Inversion Count : 4 "
},
{
"code": null,
"e": 30489,
"s": 30023,
"text": "Time complexity of this approach is : O(n^3)Better Approach : We can reduce the complexity if we consider every element arr[i] as middle element of inversion, find all the numbers greater than a[i] whose index is less than i, find all the numbers which are smaller than a[i] and index is more than i. We multiply the number of elements greater than a[i] to the number of elements smaller than a[i] and add it to the result. Below is the implementation of the idea. "
},
{
"code": null,
"e": 30493,
"s": 30489,
"text": "C++"
},
{
"code": null,
"e": 30498,
"s": 30493,
"text": "Java"
},
{
"code": null,
"e": 30506,
"s": 30498,
"text": "Python3"
},
{
"code": null,
"e": 30509,
"s": 30506,
"text": "C#"
},
{
"code": null,
"e": 30513,
"s": 30509,
"text": "PHP"
},
{
"code": null,
"e": 30524,
"s": 30513,
"text": "Javascript"
},
{
"code": "// A O(n^2) C++ program to count inversions of size 3#include<bits/stdc++.h>using namespace std; // Returns count of inversions of size 3int getInvCount(int arr[], int n){ int invcount = 0; // Initialize result for (int i=1; i<n-1; i++) { // Count all smaller elements on right of arr[i] int small = 0; for (int j=i+1; j<n; j++) if (arr[i] > arr[j]) small++; // Count all greater elements on left of arr[i] int great = 0; for (int j=i-1; j>=0; j--) if (arr[i] < arr[j]) great++; // Update inversion count by adding all inversions // that have arr[i] as middle of three elements invcount += great*small; } return invcount;} // Driver program to test above functionint main(){ int arr[] = {8, 4, 2, 1}; int n = sizeof(arr)/sizeof(arr[0]); cout << \"Inversion Count : \" << getInvCount(arr, n); return 0;}",
"e": 31473,
"s": 30524,
"text": null
},
{
"code": "// A O(n^2) Java program to count inversions of size 3 class Inversion { // returns count of inversion of size 3 int getInvCount(int arr[], int n) { int invcount = 0; // initialize result for (int i=0 ; i< n-1; i++) { // count all smaller elements on right of arr[i] int small=0; for (int j=i+1; j<n; j++) if (arr[i] > arr[j]) small++; // count all greater elements on left of arr[i] int great = 0; for (int j=i-1; j>=0; j--) if (arr[i] < arr[j]) great++; // update inversion count by adding all inversions // that have arr[i] as middle of three elements invcount += great*small; } return invcount; } // driver program to test above function public static void main(String args[]) { Inversion inversion = new Inversion(); int arr[] = new int[] {8, 4, 2, 1}; int n = arr.length; System.out.print(\"Inversion count : \" + inversion.getInvCount(arr, n)); }} // This code has been contributed by Mayank Jaiswal",
"e": 32727,
"s": 31473,
"text": null
},
{
"code": "# A O(n^2) Python3 program to# count inversions of size 3 # Returns count of inversions# of size 3def getInvCount(arr, n): # Initialize result invcount = 0 for i in range(1,n-1): # Count all smaller elements # on right of arr[i] small = 0 for j in range(i+1 ,n): if (arr[i] > arr[j]): small+=1 # Count all greater elements # on left of arr[i] great = 0; for j in range(i-1,-1,-1): if (arr[i] < arr[j]): great+=1 # Update inversion count by # adding all inversions that # have arr[i] as middle of # three elements invcount += great * small return invcount # Driver program to test above functionarr = [8, 4, 2, 1]n = len(arr)print(\"Inversion Count :\",getInvCount(arr, n)) # This code is Contributed by Smitha Dinesh Semwal",
"e": 33621,
"s": 32727,
"text": null
},
{
"code": "// A O(n^2) Java program to count inversions// of size 3using System; public class Inversion { // returns count of inversion of size 3 static int getInvCount(int []arr, int n) { int invcount = 0; // initialize result for (int i = 0 ; i < n-1; i++) { // count all smaller elements on // right of arr[i] int small = 0; for (int j = i+1; j < n; j++) if (arr[i] > arr[j]) small++; // count all greater elements on // left of arr[i] int great = 0; for (int j = i-1; j >= 0; j--) if (arr[i] < arr[j]) great++; // update inversion count by // adding all inversions that // have arr[i] as middle of // three elements invcount += great * small; } return invcount; } // driver program to test above function public static void Main() { int []arr = new int[] {8, 4, 2, 1}; int n = arr.Length; Console.WriteLine(\"Inversion count : \" + getInvCount(arr, n)); }} // This code has been contributed by anuj_67.",
"e": 34936,
"s": 33621,
"text": null
},
{
"code": "<?php// A O(n^2) PHP program to count// inversions of size 3 // Returns count of// inversions of size 3function getInvCount($arr, $n){ // Initialize result $invcount = 0; for ($i = 1; $i < $n - 1; $i++) { // Count all smaller elements // on right of arr[i] $small = 0; for ($j = $i + 1; $j < $n; $j++) if ($arr[$i] > $arr[$j]) $small++; // Count all greater elements // on left of arr[i] $great = 0; for ($j = $i - 1; $j >= 0; $j--) if ($arr[$i] < $arr[$j]) $great++; // Update inversion count by // adding all inversions that // have arr[i] as middle of // three elements $invcount += $great * $small; } return $invcount;} // Driver Code$arr = array (8, 4, 2, 1);$n = sizeof($arr);echo \"Inversion Count : \" , getInvCount($arr, $n); // This code is contributed by m_kit?>",
"e": 35882,
"s": 34936,
"text": null
},
{
"code": "<script>// A O(n^2) Javascript program to count inversions of size 3 // returns count of inversion of size 3 function getInvCount(arr, n) { let invcount = 0; // initialize result for (let i = 0 ; i < n - 1; i++) { // count all smaller elements on right of arr[i] let small = 0; for (let j = i + 1; j < n; j++) if (arr[i] > arr[j]) small++; // count all greater elements on left of arr[i] let great = 0; for (let j = i - 1; j >= 0; j--) if (arr[i] < arr[j]) great++; // update inversion count by adding all inversions // that have arr[i] as middle of three elements invcount += great*small; } return invcount; } // driver program to test above function let arr=[8, 4, 2, 1]; let n = arr.length; document.write(\"Inversion count : \" +getInvCount(arr, n)); // This code is contributed by avanitrachhadiya2155</script>",
"e": 37003,
"s": 35882,
"text": null
},
{
"code": null,
"e": 37012,
"s": 37003,
"text": "Output :"
},
{
"code": null,
"e": 37033,
"s": 37012,
"text": "Inversion Count : 4 "
},
{
"code": null,
"e": 37484,
"s": 37033,
"text": "Time Complexity of this approach : O(n^2)Binary Indexed Tree Approach : Like inversions of size 2, we can use Binary indexed tree to find inversions of size 3. It is strongly recommended to refer below article first.Count inversions of size two Using BITThe idea is similar to above method. We count the number of greater elements and smaller elements for all the elements and then multiply greater[] to smaller[] and add it to the result. Solution :"
},
{
"code": null,
"e": 38008,
"s": 37484,
"text": "To find out the number of smaller elements for an index we iterate from n-1 to 0. For every element a[i] we calculate the getSum() function for (a[i]-1) which gives the number of elements till a[i]-1.To find out the number of greater elements for an index we iterate from 0 to n-1. For every element a[i] we calculate the sum of numbers till a[i] (sum smaller or equal to a[i]) by getSum() and subtract it from i (as i is the total number of element till that point) so that we can get number of elements greater than a[i]."
},
{
"code": null,
"e": 38209,
"s": 38008,
"text": "To find out the number of smaller elements for an index we iterate from n-1 to 0. For every element a[i] we calculate the getSum() function for (a[i]-1) which gives the number of elements till a[i]-1."
},
{
"code": null,
"e": 38533,
"s": 38209,
"text": "To find out the number of greater elements for an index we iterate from 0 to n-1. For every element a[i] we calculate the sum of numbers till a[i] (sum smaller or equal to a[i]) by getSum() and subtract it from i (as i is the total number of element till that point) so that we can get number of elements greater than a[i]."
},
{
"code": null,
"e": 38539,
"s": 38533,
"text": "jit_t"
},
{
"code": null,
"e": 38544,
"s": 38539,
"text": "vt_m"
},
{
"code": null,
"e": 38550,
"s": 38544,
"text": "ukasp"
},
{
"code": null,
"e": 38565,
"s": 38550,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 38573,
"s": 38565,
"text": "rag2127"
},
{
"code": null,
"e": 38594,
"s": 38573,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 38610,
"s": 38594,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 38630,
"s": 38610,
"text": "Binary Indexed Tree"
},
{
"code": null,
"e": 38640,
"s": 38630,
"text": "inversion"
},
{
"code": null,
"e": 38664,
"s": 38640,
"text": "Advanced Data Structure"
},
{
"code": null,
"e": 38671,
"s": 38664,
"text": "Arrays"
},
{
"code": null,
"e": 38678,
"s": 38671,
"text": "Arrays"
},
{
"code": null,
"e": 38698,
"s": 38678,
"text": "Binary Indexed Tree"
},
{
"code": null,
"e": 38796,
"s": 38698,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 38830,
"s": 38796,
"text": "Agents in Artificial Intelligence"
},
{
"code": null,
"e": 38870,
"s": 38830,
"text": "Decision Tree Introduction with example"
},
{
"code": null,
"e": 38899,
"s": 38870,
"text": "Disjoint Set Data Structures"
},
{
"code": null,
"e": 38931,
"s": 38899,
"text": "Red-Black Tree | Set 2 (Insert)"
},
{
"code": null,
"e": 38959,
"s": 38931,
"text": "AVL Tree | Set 2 (Deletion)"
},
{
"code": null,
"e": 38974,
"s": 38959,
"text": "Arrays in Java"
},
{
"code": null,
"e": 38990,
"s": 38974,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 39017,
"s": 38990,
"text": "Program for array rotation"
},
{
"code": null,
"e": 39065,
"s": 39017,
"text": "Stack Data Structure (Introduction and Program)"
}
] |
ReactJS – componentWillUpdate() Method
|
In this article, we are going to see how to execute a function before the component is updated in the DOM tree.
This method is used during the updating phase of the React lifecycle. This function is generally called before the component is updated or when the state or props passed to the component changes. Don’t call setState() method in this function. This method will not be invoked if shouldComponentUpdate() methods return false.
Note: This method is now deprecated.
UNSAFE_componentWillUpdate(nextProps, nextState)
In this example, we will build a color changing React application which calls the componentWillUpdate method when the component is updated in the DOM tree.
Our first component in the following example is App. This component is the parent of the ChangeName component. We are creating ChangeName separately and just adding it inside the JSX tree in our App component. Hence, only the App component needs to be exported.
App.jsx
import React from 'react';
class App extends React.Component {
state = { color: 'green' };
render() {
setTimeout(() => {
this.setState({ color: 'wheat' });
}, 4000);
return (
<div>
<h1>Tutorialspoint</h1>
<ChangeName color={this.state.color} />
</div>
);
}
}
class ChangeName extends React.Component {
UNSAFE_componentWillUpdate(nextProps, nextState) {
console.log('Component will be updated soon');
}
render() {
console.log('ChangeName component is called');
return (
<div>
<h1 style={{ color: this.props.color }}>Simply Easy Learning</h1>
</div>
);
}
}
export default App;
This will produce the following result.
|
[
{
"code": null,
"e": 1174,
"s": 1062,
"text": "In this article, we are going to see how to execute a function before the component is updated in the DOM tree."
},
{
"code": null,
"e": 1498,
"s": 1174,
"text": "This method is used during the updating phase of the React lifecycle. This function is generally called before the component is updated or when the state or props passed to the component changes. Don’t call setState() method in this function. This method will not be invoked if shouldComponentUpdate() methods return false."
},
{
"code": null,
"e": 1535,
"s": 1498,
"text": "Note: This method is now deprecated."
},
{
"code": null,
"e": 1584,
"s": 1535,
"text": "UNSAFE_componentWillUpdate(nextProps, nextState)"
},
{
"code": null,
"e": 1740,
"s": 1584,
"text": "In this example, we will build a color changing React application which calls the componentWillUpdate method when the component is updated in the DOM tree."
},
{
"code": null,
"e": 2002,
"s": 1740,
"text": "Our first component in the following example is App. This component is the parent of the ChangeName component. We are creating ChangeName separately and just adding it inside the JSX tree in our App component. Hence, only the App component needs to be exported."
},
{
"code": null,
"e": 2010,
"s": 2002,
"text": "App.jsx"
},
{
"code": null,
"e": 2736,
"s": 2010,
"text": "import React from 'react';\n\nclass App extends React.Component {\n state = { color: 'green' };\n render() {\n setTimeout(() => {\n this.setState({ color: 'wheat' });\n }, 4000);\n return (\n <div>\n <h1>Tutorialspoint</h1>\n <ChangeName color={this.state.color} />\n </div>\n );\n }\n}\nclass ChangeName extends React.Component {\n UNSAFE_componentWillUpdate(nextProps, nextState) {\n console.log('Component will be updated soon');\n }\n render() {\n console.log('ChangeName component is called');\n return (\n <div>\n <h1 style={{ color: this.props.color }}>Simply Easy Learning</h1>\n </div>\n );\n }\n}\nexport default App;"
},
{
"code": null,
"e": 2776,
"s": 2736,
"text": "This will produce the following result."
}
] |
Find last unique URL from long list of URLs in single traversal - GeeksforGeeks
|
28 Jun, 2021
Given a very long list of URLs, find out last unique URL. Only one traversal of all URLs is allowed.
Examples:
Input:
https://www.geeksforgeeks.org
https://www.geeksforgeeks.org/quiz-corner-gq/
http://qa.geeksforgeeks.org
https://practice.geeksforgeeks.org
https://ide.geeksforgeeks.org
https://write.geeksforgeeks.org
https://www.geeksforgeeks.org/quiz-corner-gq/
https://practice.geeksforgeeks.org
https://ide.geeksforgeeks.org
https://www.geeksforgeeks.org/quiz-corner-gq/
http://qa.geeksforgeeks.org
https://practice.geeksforgeeks.org
Output:
https://write.geeksforgeeks.org
We can solve this problem in one traversal by using Trie with a Doubly Linked List (We can insert and delete in O(1) time). The idea is to insert all URLs into the Trie one by one and check if it is duplicate or not. To know if we have previously encountered the URL, we need to mark the last node of every URL as leaf node. If we encounter a URL for the first time, we insert it into the doubly Linked list and maintain a pointer to that node in linked list in leaf node of the trie. If we encounter a URL that is already in the trie and has pointer to the url in the linked list, we delete the node from the linked list and set its pointer in the trie to null. After all URLs are processed, linked list will only contain the URLs that are distinct and the node at the beginning of the linked list will be last unique URL.
// C++ program to print distinct URLs using Trie// and Doubly Linked List#include <bits/stdc++.h>using namespace std; // Alphabet size (# of symbols)const int ALPHABET_SIZE = 256; // A linked list nodestruct DLLNode{ string data; DLLNode* next, * prev;}; // trie nodestruct TrieNode{ TrieNode* children[ALPHABET_SIZE]; // isLeaf is true if the node represents // end of a word bool isLeaf; DLLNode* LLptr;}; /* Given a reference (pointer to pointer) to the head of a list and an int, inserts a new node on the front of the list. */void push(DLLNode*& head_ref, string new_data){ DLLNode* new_node = new DLLNode; // put in the data new_node->data = new_data; // Make next of new node as head and previous // as NULL new_node->next = (head_ref); new_node->prev = NULL; // change prev of head node to new node if(head_ref != NULL) head_ref->prev = new_node; // move the head to point to the new node head_ref = new_node;} /* Function to delete a node in a Doubly Linked List. head_ref --> pointer to head node pointer. del --> pointer to node to be deleted. */void deleteNode(DLLNode*& head_ref, DLLNode* del){ // base case if (head_ref == NULL || del == NULL) return; // If node to be deleted is head node if (head_ref == del) head_ref = del->next; // Change next only if node to be deleted is // NOT the last node if (del->next != NULL) del->next->prev = del->prev; // Change prev only if node to be deleted is // NOT the first node if (del->prev != NULL) del->prev->next = del->next; // Finally, free the memory occupied by del delete(del); return;} // Returns new trie node (initialized to NULLs)TrieNode* getNewTrieNode(void){ TrieNode* pNode = new TrieNode; if (pNode) { pNode->isLeaf = false; for (int i = 0; i < ALPHABET_SIZE; i++) pNode->children[i] = NULL; pNode->LLptr = NULL; } return pNode;} // If not present, inserts key into trie// If the key is prefix of trie node, just marks leaf nodevoid insert(TrieNode* root, string key, DLLNode*& head){ int index; TrieNode* pCrawl = root; for (int level = 0; level < key.length(); level++) { index = int(key[level]); if (!pCrawl->children[index]) pCrawl->children[index] = getNewTrieNode(); pCrawl = pCrawl->children[index]; } if (pCrawl->isLeaf) { // cout << "Duplicate Found " << key << endl; // delete from linked list if (pCrawl->LLptr) deleteNode(head, pCrawl->LLptr); pCrawl->LLptr = NULL; } else { // mark last node as leaf pCrawl->isLeaf = true; // insert to linked list push(head, key); pCrawl->LLptr = head; }} // Driver functionint main(){ string urls[] = { "https://www.geeksforgeeks.org", "https://write.geeksforgeeks.org", "http://quiz.geeksforgeeks.org", "http://qa.geeksforgeeks.org", "https://practice.geeksforgeeks.org", "https://ide.geeksforgeeks.org", "http://quiz.geeksforgeeks.org", "https://practice.geeksforgeeks.org", "https://ide.geeksforgeeks.org", "http://quiz.geeksforgeeks.org", "http://qa.geeksforgeeks.org", "https://practice.geeksforgeeks.org" }; TrieNode* root = getNewTrieNode(); // Start with the empty list DLLNode* head = NULL; int n = sizeof(urls)/sizeof(urls[0]); // Construct Trie from given URLs for (int i = 0; i < n; i++) insert(root, urls[i], head); // head of linked list will point to last // distinct URL cout << head->data << endl; return 0;}
Output:
https://write.geeksforgeeks.org
This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Trie
Advanced Data Structure
Trie
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Extendible Hashing (Dynamic approach to DBMS)
Ternary Search Tree
Proof that Dominant Set of a Graph is NP-Complete
2-3 Trees | (Search, Insert and Deletion)
Advantages of Trie Data Structure
Quad Tree
Interval Tree
Skip List | Set 2 (Insertion)
Ackermann Function
Dynamic Programming on Trees | Set-1
|
[
{
"code": null,
"e": 24095,
"s": 24067,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 24196,
"s": 24095,
"text": "Given a very long list of URLs, find out last unique URL. Only one traversal of all URLs is allowed."
},
{
"code": null,
"e": 24206,
"s": 24196,
"text": "Examples:"
},
{
"code": null,
"e": 24686,
"s": 24206,
"text": "Input:\nhttps://www.geeksforgeeks.org\nhttps://www.geeksforgeeks.org/quiz-corner-gq/ \nhttp://qa.geeksforgeeks.org \nhttps://practice.geeksforgeeks.org \nhttps://ide.geeksforgeeks.org\nhttps://write.geeksforgeeks.org \nhttps://www.geeksforgeeks.org/quiz-corner-gq/ \nhttps://practice.geeksforgeeks.org \nhttps://ide.geeksforgeeks.org \nhttps://www.geeksforgeeks.org/quiz-corner-gq/ \nhttp://qa.geeksforgeeks.org \nhttps://practice.geeksforgeeks.org\n\nOutput:\nhttps://write.geeksforgeeks.org\n"
},
{
"code": null,
"e": 25510,
"s": 24686,
"text": "We can solve this problem in one traversal by using Trie with a Doubly Linked List (We can insert and delete in O(1) time). The idea is to insert all URLs into the Trie one by one and check if it is duplicate or not. To know if we have previously encountered the URL, we need to mark the last node of every URL as leaf node. If we encounter a URL for the first time, we insert it into the doubly Linked list and maintain a pointer to that node in linked list in leaf node of the trie. If we encounter a URL that is already in the trie and has pointer to the url in the linked list, we delete the node from the linked list and set its pointer in the trie to null. After all URLs are processed, linked list will only contain the URLs that are distinct and the node at the beginning of the linked list will be last unique URL."
},
{
"code": "// C++ program to print distinct URLs using Trie// and Doubly Linked List#include <bits/stdc++.h>using namespace std; // Alphabet size (# of symbols)const int ALPHABET_SIZE = 256; // A linked list nodestruct DLLNode{ string data; DLLNode* next, * prev;}; // trie nodestruct TrieNode{ TrieNode* children[ALPHABET_SIZE]; // isLeaf is true if the node represents // end of a word bool isLeaf; DLLNode* LLptr;}; /* Given a reference (pointer to pointer) to the head of a list and an int, inserts a new node on the front of the list. */void push(DLLNode*& head_ref, string new_data){ DLLNode* new_node = new DLLNode; // put in the data new_node->data = new_data; // Make next of new node as head and previous // as NULL new_node->next = (head_ref); new_node->prev = NULL; // change prev of head node to new node if(head_ref != NULL) head_ref->prev = new_node; // move the head to point to the new node head_ref = new_node;} /* Function to delete a node in a Doubly Linked List. head_ref --> pointer to head node pointer. del --> pointer to node to be deleted. */void deleteNode(DLLNode*& head_ref, DLLNode* del){ // base case if (head_ref == NULL || del == NULL) return; // If node to be deleted is head node if (head_ref == del) head_ref = del->next; // Change next only if node to be deleted is // NOT the last node if (del->next != NULL) del->next->prev = del->prev; // Change prev only if node to be deleted is // NOT the first node if (del->prev != NULL) del->prev->next = del->next; // Finally, free the memory occupied by del delete(del); return;} // Returns new trie node (initialized to NULLs)TrieNode* getNewTrieNode(void){ TrieNode* pNode = new TrieNode; if (pNode) { pNode->isLeaf = false; for (int i = 0; i < ALPHABET_SIZE; i++) pNode->children[i] = NULL; pNode->LLptr = NULL; } return pNode;} // If not present, inserts key into trie// If the key is prefix of trie node, just marks leaf nodevoid insert(TrieNode* root, string key, DLLNode*& head){ int index; TrieNode* pCrawl = root; for (int level = 0; level < key.length(); level++) { index = int(key[level]); if (!pCrawl->children[index]) pCrawl->children[index] = getNewTrieNode(); pCrawl = pCrawl->children[index]; } if (pCrawl->isLeaf) { // cout << \"Duplicate Found \" << key << endl; // delete from linked list if (pCrawl->LLptr) deleteNode(head, pCrawl->LLptr); pCrawl->LLptr = NULL; } else { // mark last node as leaf pCrawl->isLeaf = true; // insert to linked list push(head, key); pCrawl->LLptr = head; }} // Driver functionint main(){ string urls[] = { \"https://www.geeksforgeeks.org\", \"https://write.geeksforgeeks.org\", \"http://quiz.geeksforgeeks.org\", \"http://qa.geeksforgeeks.org\", \"https://practice.geeksforgeeks.org\", \"https://ide.geeksforgeeks.org\", \"http://quiz.geeksforgeeks.org\", \"https://practice.geeksforgeeks.org\", \"https://ide.geeksforgeeks.org\", \"http://quiz.geeksforgeeks.org\", \"http://qa.geeksforgeeks.org\", \"https://practice.geeksforgeeks.org\" }; TrieNode* root = getNewTrieNode(); // Start with the empty list DLLNode* head = NULL; int n = sizeof(urls)/sizeof(urls[0]); // Construct Trie from given URLs for (int i = 0; i < n; i++) insert(root, urls[i], head); // head of linked list will point to last // distinct URL cout << head->data << endl; return 0;}",
"e": 29265,
"s": 25510,
"text": null
},
{
"code": null,
"e": 29273,
"s": 29265,
"text": "Output:"
},
{
"code": null,
"e": 29306,
"s": 29273,
"text": "https://write.geeksforgeeks.org\n"
},
{
"code": null,
"e": 29601,
"s": 29306,
"text": "This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 29726,
"s": 29601,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 29731,
"s": 29726,
"text": "Trie"
},
{
"code": null,
"e": 29755,
"s": 29731,
"text": "Advanced Data Structure"
},
{
"code": null,
"e": 29760,
"s": 29755,
"text": "Trie"
},
{
"code": null,
"e": 29858,
"s": 29760,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29867,
"s": 29858,
"text": "Comments"
},
{
"code": null,
"e": 29880,
"s": 29867,
"text": "Old Comments"
},
{
"code": null,
"e": 29926,
"s": 29880,
"text": "Extendible Hashing (Dynamic approach to DBMS)"
},
{
"code": null,
"e": 29946,
"s": 29926,
"text": "Ternary Search Tree"
},
{
"code": null,
"e": 29996,
"s": 29946,
"text": "Proof that Dominant Set of a Graph is NP-Complete"
},
{
"code": null,
"e": 30038,
"s": 29996,
"text": "2-3 Trees | (Search, Insert and Deletion)"
},
{
"code": null,
"e": 30072,
"s": 30038,
"text": "Advantages of Trie Data Structure"
},
{
"code": null,
"e": 30082,
"s": 30072,
"text": "Quad Tree"
},
{
"code": null,
"e": 30096,
"s": 30082,
"text": "Interval Tree"
},
{
"code": null,
"e": 30126,
"s": 30096,
"text": "Skip List | Set 2 (Insertion)"
},
{
"code": null,
"e": 30145,
"s": 30126,
"text": "Ackermann Function"
}
] |
Java Program to Find Sum of Fibonacci Series Numbers of First N Even Indexes - GeeksforGeeks
|
17 Mar, 2021
For a given positive integer N, the purpose is to find the value of F2 + F4 + F6 +.........+ F2n till N number. Where Fi indicates the i’th Fibonacci number.
The Fibonacci Series are the numbers in the below-given integer sequence.
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ......
Examples:
Input: n = 4
Output: 33
N = 4, So here the fibonacci series will be produced from 0th term till 8th term:
0, 1, 1, 2, 3, 5, 8, 13, 21
Sum of numbers at even indexes = 0 + 1 + 3 + 8 + 21 = 33.
Input: n = 7
Output: 609
0 + 1 + 3 + 8 + 21 + 55 + 144 + 377 = 609.
Approach 1:
Find all Fibonacci numbers till 2n and adding up only the even indices.
Java
// Java Program to find even sum of// fibonacci Series Till number Nimport java.io.*; class geeksforgeeks { // Computing the value of first fibonacci series // and storing the sum of even indexed numbers static int Fib_Even_Sum(int N) { if (N <= 0) return 0; int fib[] = new int[2 * N + 1]; fib[0] = 0; fib[1] = 1; // Initializing the sum int s = 0; // Adding remaining numbers for (int j = 2; j <= 2 * N; j++) { fib[j] = fib[j - 1] + fib[j - 2]; // Only considering even indexes if (j % 2 == 0) s += fib[j]; } return s; } // The Driver code public static void main(String[] args) { int N = 11; // Prints the sum of even-indexed numbers System.out.println( "Even sum of fibonacci series till number " + N + " is: " + +Fib_Even_Sum(N)); }}
Even sum of fibonacci series till number 11 is: 28656
Time Complexity: O(n)
Approach 2:
It can be clearly seen that the required sum can be obtained thus:2 ( F2 + F4 + F6 +.........+ F2n ) = (F1 + F2 + F3 + F4 +.........+ F2n) – (F1 – F2 + F3 – F4 +.........+ F2n)
Now the first term can be obtained if we put 2n instead of n in the formula given here.
Thus F1 + F2 + F3 + F4 +.........+ F2n = F2n+2 – 1.
The second term can also be found if we put 2n instead of n in the formula given here
Thus, F1 – F2 + F3 – F4 +.........- F2n = 1 + (-1)2n+1F2n-1 = 1 – F2n-1.
So, 2 ( F2 + F4 + F6 +.........+ F2n)= F2n+2 – 1 – 1 + F2n-1= F2n+2 + F2n-1 – 2= F2n + F2n+1 + F2n+1 – F2n – 2= 2 ( F2n+1 -1)Hence, ( F2 + F4 + F6 +.........+ F2n) = F2n+1 -1 .
The task is to find only F2n+1 -1.
Below is the implementation of the above approach:
Java
// Java Program to find even indexed// Fibonacci Sum in O(Log n) time. class GFG { static int MAX = 1000; // Create an array for memoization static int f[] = new int[MAX]; // Returns n'th Fibonacci number // using table f[] static int fib(int n) { // Base cases if (n == 0) { return 0; } if (n == 1 || n == 2) { return (f[n] = 1); } // If fib(n) is already computed if (f[n] == 1) { return f[n]; } int k = (n % 2 == 1) ? (n + 1) / 2 : n / 2; // Applying above formula [Note value n&1 is 1 // if n is odd, else 0]. f[n] = (n % 2 == 1) ? (fib(k) * fib(k) + fib(k - 1) * fib(k - 1)) : (2 * fib(k - 1) + fib(k)) * fib(k); return f[n]; } // Computes value of even-indexed Fibonacci Sum static int calculateEvenSum(int n) { return (fib(2 * n + 1) - 1); } // Driver program to test above function public static void main(String[] args) { // Get n int n = 11; // Find the alternating sum System.out.println( "Even indexed Fibonacci Sum upto " + n + " terms: " + calculateEvenSum(n)); }}
Even indexed Fibonacci Sum upto 8 terms: 1596
Time Complexity: O(log n)
java-basics
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Functional Interfaces in Java
Stream In Java
Constructors in Java
Different ways of Reading a text file in Java
Exceptions 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
Factory method design pattern in Java
|
[
{
"code": null,
"e": 23581,
"s": 23553,
"text": "\n17 Mar, 2021"
},
{
"code": null,
"e": 23739,
"s": 23581,
"text": "For a given positive integer N, the purpose is to find the value of F2 + F4 + F6 +.........+ F2n till N number. Where Fi indicates the i’th Fibonacci number."
},
{
"code": null,
"e": 23813,
"s": 23739,
"text": "The Fibonacci Series are the numbers in the below-given integer sequence."
},
{
"code": null,
"e": 23861,
"s": 23813,
"text": "0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ......"
},
{
"code": null,
"e": 23871,
"s": 23861,
"text": "Examples:"
},
{
"code": null,
"e": 24132,
"s": 23871,
"text": "Input: n = 4\nOutput: 33\nN = 4, So here the fibonacci series will be produced from 0th term till 8th term:\n0, 1, 1, 2, 3, 5, 8, 13, 21\nSum of numbers at even indexes = 0 + 1 + 3 + 8 + 21 = 33.\n\nInput: n = 7\nOutput: 609\n0 + 1 + 3 + 8 + 21 + 55 + 144 + 377 = 609."
},
{
"code": null,
"e": 24144,
"s": 24132,
"text": "Approach 1:"
},
{
"code": null,
"e": 24216,
"s": 24144,
"text": "Find all Fibonacci numbers till 2n and adding up only the even indices."
},
{
"code": null,
"e": 24221,
"s": 24216,
"text": "Java"
},
{
"code": "// Java Program to find even sum of// fibonacci Series Till number Nimport java.io.*; class geeksforgeeks { // Computing the value of first fibonacci series // and storing the sum of even indexed numbers static int Fib_Even_Sum(int N) { if (N <= 0) return 0; int fib[] = new int[2 * N + 1]; fib[0] = 0; fib[1] = 1; // Initializing the sum int s = 0; // Adding remaining numbers for (int j = 2; j <= 2 * N; j++) { fib[j] = fib[j - 1] + fib[j - 2]; // Only considering even indexes if (j % 2 == 0) s += fib[j]; } return s; } // The Driver code public static void main(String[] args) { int N = 11; // Prints the sum of even-indexed numbers System.out.println( \"Even sum of fibonacci series till number \" + N + \" is: \" + +Fib_Even_Sum(N)); }}",
"e": 25176,
"s": 24221,
"text": null
},
{
"code": null,
"e": 25231,
"s": 25176,
"text": "Even sum of fibonacci series till number 11 is: 28656\n"
},
{
"code": null,
"e": 25253,
"s": 25231,
"text": "Time Complexity: O(n)"
},
{
"code": null,
"e": 25265,
"s": 25253,
"text": "Approach 2:"
},
{
"code": null,
"e": 25442,
"s": 25265,
"text": "It can be clearly seen that the required sum can be obtained thus:2 ( F2 + F4 + F6 +.........+ F2n ) = (F1 + F2 + F3 + F4 +.........+ F2n) – (F1 – F2 + F3 – F4 +.........+ F2n)"
},
{
"code": null,
"e": 25530,
"s": 25442,
"text": "Now the first term can be obtained if we put 2n instead of n in the formula given here."
},
{
"code": null,
"e": 25582,
"s": 25530,
"text": "Thus F1 + F2 + F3 + F4 +.........+ F2n = F2n+2 – 1."
},
{
"code": null,
"e": 25668,
"s": 25582,
"text": "The second term can also be found if we put 2n instead of n in the formula given here"
},
{
"code": null,
"e": 25741,
"s": 25668,
"text": "Thus, F1 – F2 + F3 – F4 +.........- F2n = 1 + (-1)2n+1F2n-1 = 1 – F2n-1."
},
{
"code": null,
"e": 25918,
"s": 25741,
"text": "So, 2 ( F2 + F4 + F6 +.........+ F2n)= F2n+2 – 1 – 1 + F2n-1= F2n+2 + F2n-1 – 2= F2n + F2n+1 + F2n+1 – F2n – 2= 2 ( F2n+1 -1)Hence, ( F2 + F4 + F6 +.........+ F2n) = F2n+1 -1 ."
},
{
"code": null,
"e": 25953,
"s": 25918,
"text": "The task is to find only F2n+1 -1."
},
{
"code": null,
"e": 26004,
"s": 25953,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 26009,
"s": 26004,
"text": "Java"
},
{
"code": "// Java Program to find even indexed// Fibonacci Sum in O(Log n) time. class GFG { static int MAX = 1000; // Create an array for memoization static int f[] = new int[MAX]; // Returns n'th Fibonacci number // using table f[] static int fib(int n) { // Base cases if (n == 0) { return 0; } if (n == 1 || n == 2) { return (f[n] = 1); } // If fib(n) is already computed if (f[n] == 1) { return f[n]; } int k = (n % 2 == 1) ? (n + 1) / 2 : n / 2; // Applying above formula [Note value n&1 is 1 // if n is odd, else 0]. f[n] = (n % 2 == 1) ? (fib(k) * fib(k) + fib(k - 1) * fib(k - 1)) : (2 * fib(k - 1) + fib(k)) * fib(k); return f[n]; } // Computes value of even-indexed Fibonacci Sum static int calculateEvenSum(int n) { return (fib(2 * n + 1) - 1); } // Driver program to test above function public static void main(String[] args) { // Get n int n = 11; // Find the alternating sum System.out.println( \"Even indexed Fibonacci Sum upto \" + n + \" terms: \" + calculateEvenSum(n)); }}",
"e": 27295,
"s": 26009,
"text": null
},
{
"code": null,
"e": 27342,
"s": 27295,
"text": "Even indexed Fibonacci Sum upto 8 terms: 1596\n"
},
{
"code": null,
"e": 27368,
"s": 27342,
"text": "Time Complexity: O(log n)"
},
{
"code": null,
"e": 27380,
"s": 27368,
"text": "java-basics"
},
{
"code": null,
"e": 27385,
"s": 27380,
"text": "Java"
},
{
"code": null,
"e": 27399,
"s": 27385,
"text": "Java Programs"
},
{
"code": null,
"e": 27404,
"s": 27399,
"text": "Java"
},
{
"code": null,
"e": 27502,
"s": 27404,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27511,
"s": 27502,
"text": "Comments"
},
{
"code": null,
"e": 27524,
"s": 27511,
"text": "Old Comments"
},
{
"code": null,
"e": 27554,
"s": 27524,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 27569,
"s": 27554,
"text": "Stream In Java"
},
{
"code": null,
"e": 27590,
"s": 27569,
"text": "Constructors in Java"
},
{
"code": null,
"e": 27636,
"s": 27590,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 27655,
"s": 27636,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 27699,
"s": 27655,
"text": "Convert a String to Character array in Java"
},
{
"code": null,
"e": 27725,
"s": 27699,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 27759,
"s": 27725,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 27806,
"s": 27759,
"text": "Implementing a Linked List in Java using Class"
}
] |
Python Pandas - Basic Functionality
|
By now, we learnt about the three Pandas DataStructures and how to create them. We will majorly focus on the DataFrame objects because of its importance in the real time data processing and also discuss a few other DataStructures.
axes
Returns a list of the row axis labels
dtype
Returns the dtype of the object.
empty
Returns True if series is empty.
ndim
Returns the number of dimensions of the underlying data, by
definition 1.
size
Returns the number of elements in the underlying data.
values
Returns the Series as ndarray.
head()
Returns the first n rows.
tail()
Returns the last n rows.
Let us now create a Series and see all the above tabulated attributes operation.
import pandas as pd
import numpy as np
#Create a series with 100 random numbers
s = pd.Series(np.random.randn(4))
print s
Its output is as follows −
0 0.967853
1 -0.148368
2 -1.395906
3 -1.758394
dtype: float64
Returns the list of the labels of the series.
import pandas as pd
import numpy as np
#Create a series with 100 random numbers
s = pd.Series(np.random.randn(4))
print ("The axes are:")
print s.axes
Its output is as follows −
The axes are:
[RangeIndex(start=0, stop=4, step=1)]
The above result is a compact format of a list of values from 0 to 5, i.e., [0,1,2,3,4].
Returns the Boolean value saying whether the Object is empty or not. True indicates that the object is empty.
import pandas as pd
import numpy as np
#Create a series with 100 random numbers
s = pd.Series(np.random.randn(4))
print ("Is the Object empty?")
print s.empty
Its output is as follows −
Is the Object empty?
False
Returns the number of dimensions of the object. By definition, a Series is a 1D data structure, so it returns
import pandas as pd
import numpy as np
#Create a series with 4 random numbers
s = pd.Series(np.random.randn(4))
print s
print ("The dimensions of the object:")
print s.ndim
Its output is as follows −
0 0.175898
1 0.166197
2 -0.609712
3 -1.377000
dtype: float64
The dimensions of the object:
1
Returns the size(length) of the series.
import pandas as pd
import numpy as np
#Create a series with 4 random numbers
s = pd.Series(np.random.randn(2))
print s
print ("The size of the object:")
print s.size
Its output is as follows −
0 3.078058
1 -1.207803
dtype: float64
The size of the object:
2
Returns the actual data in the series as an array.
import pandas as pd
import numpy as np
#Create a series with 4 random numbers
s = pd.Series(np.random.randn(4))
print s
print ("The actual data series is:")
print s.values
Its output is as follows −
0 1.787373
1 -0.605159
2 0.180477
3 -0.140922
dtype: float64
The actual data series is:
[ 1.78737302 -0.60515881 0.18047664 -0.1409218 ]
To view a small sample of a Series or the DataFrame object, use the head() and the tail() methods.
head() returns the first n rows(observe the index values). The default number of elements to display is five, but you may pass a custom number.
import pandas as pd
import numpy as np
#Create a series with 4 random numbers
s = pd.Series(np.random.randn(4))
print ("The original series is:")
print s
print ("The first two rows of the data series:")
print s.head(2)
Its output is as follows −
The original series is:
0 0.720876
1 -0.765898
2 0.479221
3 -0.139547
dtype: float64
The first two rows of the data series:
0 0.720876
1 -0.765898
dtype: float64
tail() returns the last n rows(observe the index values). The default number of elements to display is five, but you may pass a custom number.
import pandas as pd
import numpy as np
#Create a series with 4 random numbers
s = pd.Series(np.random.randn(4))
print ("The original series is:")
print s
print ("The last two rows of the data series:")
print s.tail(2)
Its output is as follows −
The original series is:
0 -0.655091
1 -0.881407
2 -0.608592
3 -2.341413
dtype: float64
The last two rows of the data series:
2 -0.608592
3 -2.341413
dtype: float64
Let us now understand what DataFrame Basic Functionality is. The following tables lists down the important attributes or methods that help in DataFrame Basic Functionality.
T
Transposes rows and columns.
axes
Returns a list with the row axis labels and column axis labels as the only members.
dtypes
Returns the dtypes in this object.
empty
True if NDFrame is entirely empty [no items]; if any of the axes are of length 0.
ndim
Number of axes / array dimensions.
shape
Returns a tuple representing the dimensionality of the DataFrame.
size
Number of elements in the NDFrame.
values
Numpy representation of NDFrame.
head()
Returns the first n rows.
tail()
Returns last n rows.
Let us now create a DataFrame and see all how the above mentioned attributes operate.
import pandas as pd
import numpy as np
#Create a Dictionary of series
d = {'Name':pd.Series(['Tom','James','Ricky','Vin','Steve','Smith','Jack']),
'Age':pd.Series([25,26,25,23,30,29,23]),
'Rating':pd.Series([4.23,3.24,3.98,2.56,3.20,4.6,3.8])}
#Create a DataFrame
df = pd.DataFrame(d)
print ("Our data series is:")
print df
Its output is as follows −
Our data series is:
Age Name Rating
0 25 Tom 4.23
1 26 James 3.24
2 25 Ricky 3.98
3 23 Vin 2.56
4 30 Steve 3.20
5 29 Smith 4.60
6 23 Jack 3.80
Returns the transpose of the DataFrame. The rows and columns will interchange.
import pandas as pd
import numpy as np
# Create a Dictionary of series
d = {'Name':pd.Series(['Tom','James','Ricky','Vin','Steve','Smith','Jack']),
'Age':pd.Series([25,26,25,23,30,29,23]),
'Rating':pd.Series([4.23,3.24,3.98,2.56,3.20,4.6,3.8])}
# Create a DataFrame
df = pd.DataFrame(d)
print ("The transpose of the data series is:")
print df.T
Its output is as follows −
The transpose of the data series is:
0 1 2 3 4 5 6
Age 25 26 25 23 30 29 23
Name Tom James Ricky Vin Steve Smith Jack
Rating 4.23 3.24 3.98 2.56 3.2 4.6 3.8
Returns the list of row axis labels and column axis labels.
import pandas as pd
import numpy as np
#Create a Dictionary of series
d = {'Name':pd.Series(['Tom','James','Ricky','Vin','Steve','Smith','Jack']),
'Age':pd.Series([25,26,25,23,30,29,23]),
'Rating':pd.Series([4.23,3.24,3.98,2.56,3.20,4.6,3.8])}
#Create a DataFrame
df = pd.DataFrame(d)
print ("Row axis labels and column axis labels are:")
print df.axes
Its output is as follows −
Row axis labels and column axis labels are:
[RangeIndex(start=0, stop=7, step=1), Index([u'Age', u'Name', u'Rating'],
dtype='object')]
Returns the data type of each column.
import pandas as pd
import numpy as np
#Create a Dictionary of series
d = {'Name':pd.Series(['Tom','James','Ricky','Vin','Steve','Smith','Jack']),
'Age':pd.Series([25,26,25,23,30,29,23]),
'Rating':pd.Series([4.23,3.24,3.98,2.56,3.20,4.6,3.8])}
#Create a DataFrame
df = pd.DataFrame(d)
print ("The data types of each column are:")
print df.dtypes
Its output is as follows −
The data types of each column are:
Age int64
Name object
Rating float64
dtype: object
Returns the Boolean value saying whether the Object is empty or not; True indicates that the object is empty.
import pandas as pd
import numpy as np
#Create a Dictionary of series
d = {'Name':pd.Series(['Tom','James','Ricky','Vin','Steve','Smith','Jack']),
'Age':pd.Series([25,26,25,23,30,29,23]),
'Rating':pd.Series([4.23,3.24,3.98,2.56,3.20,4.6,3.8])}
#Create a DataFrame
df = pd.DataFrame(d)
print ("Is the object empty?")
print df.empty
Its output is as follows −
Is the object empty?
False
Returns the number of dimensions of the object. By definition, DataFrame is a 2D object.
import pandas as pd
import numpy as np
#Create a Dictionary of series
d = {'Name':pd.Series(['Tom','James','Ricky','Vin','Steve','Smith','Jack']),
'Age':pd.Series([25,26,25,23,30,29,23]),
'Rating':pd.Series([4.23,3.24,3.98,2.56,3.20,4.6,3.8])}
#Create a DataFrame
df = pd.DataFrame(d)
print ("Our object is:")
print df
print ("The dimension of the object is:")
print df.ndim
Its output is as follows −
Our object is:
Age Name Rating
0 25 Tom 4.23
1 26 James 3.24
2 25 Ricky 3.98
3 23 Vin 2.56
4 30 Steve 3.20
5 29 Smith 4.60
6 23 Jack 3.80
The dimension of the object is:
2
Returns a tuple representing the dimensionality of the DataFrame. Tuple (a,b), where a represents the number of rows and b represents the number of columns.
import pandas as pd
import numpy as np
#Create a Dictionary of series
d = {'Name':pd.Series(['Tom','James','Ricky','Vin','Steve','Smith','Jack']),
'Age':pd.Series([25,26,25,23,30,29,23]),
'Rating':pd.Series([4.23,3.24,3.98,2.56,3.20,4.6,3.8])}
#Create a DataFrame
df = pd.DataFrame(d)
print ("Our object is:")
print df
print ("The shape of the object is:")
print df.shape
Its output is as follows −
Our object is:
Age Name Rating
0 25 Tom 4.23
1 26 James 3.24
2 25 Ricky 3.98
3 23 Vin 2.56
4 30 Steve 3.20
5 29 Smith 4.60
6 23 Jack 3.80
The shape of the object is:
(7, 3)
Returns the number of elements in the DataFrame.
import pandas as pd
import numpy as np
#Create a Dictionary of series
d = {'Name':pd.Series(['Tom','James','Ricky','Vin','Steve','Smith','Jack']),
'Age':pd.Series([25,26,25,23,30,29,23]),
'Rating':pd.Series([4.23,3.24,3.98,2.56,3.20,4.6,3.8])}
#Create a DataFrame
df = pd.DataFrame(d)
print ("Our object is:")
print df
print ("The total number of elements in our object is:")
print df.size
Its output is as follows −
Our object is:
Age Name Rating
0 25 Tom 4.23
1 26 James 3.24
2 25 Ricky 3.98
3 23 Vin 2.56
4 30 Steve 3.20
5 29 Smith 4.60
6 23 Jack 3.80
The total number of elements in our object is:
21
Returns the actual data in the DataFrame as an NDarray.
import pandas as pd
import numpy as np
#Create a Dictionary of series
d = {'Name':pd.Series(['Tom','James','Ricky','Vin','Steve','Smith','Jack']),
'Age':pd.Series([25,26,25,23,30,29,23]),
'Rating':pd.Series([4.23,3.24,3.98,2.56,3.20,4.6,3.8])}
#Create a DataFrame
df = pd.DataFrame(d)
print ("Our object is:")
print df
print ("The actual data in our data frame is:")
print df.values
Its output is as follows −
Our object is:
Age Name Rating
0 25 Tom 4.23
1 26 James 3.24
2 25 Ricky 3.98
3 23 Vin 2.56
4 30 Steve 3.20
5 29 Smith 4.60
6 23 Jack 3.80
The actual data in our data frame is:
[[25 'Tom' 4.23]
[26 'James' 3.24]
[25 'Ricky' 3.98]
[23 'Vin' 2.56]
[30 'Steve' 3.2]
[29 'Smith' 4.6]
[23 'Jack' 3.8]]
To view a small sample of a DataFrame object, use the head() and tail() methods. head() returns the first n rows (observe the index values). The default number of elements to display is five, but you may pass a custom number.
import pandas as pd
import numpy as np
#Create a Dictionary of series
d = {'Name':pd.Series(['Tom','James','Ricky','Vin','Steve','Smith','Jack']),
'Age':pd.Series([25,26,25,23,30,29,23]),
'Rating':pd.Series([4.23,3.24,3.98,2.56,3.20,4.6,3.8])}
#Create a DataFrame
df = pd.DataFrame(d)
print ("Our data frame is:")
print df
print ("The first two rows of the data frame is:")
print df.head(2)
Its output is as follows −
Our data frame is:
Age Name Rating
0 25 Tom 4.23
1 26 James 3.24
2 25 Ricky 3.98
3 23 Vin 2.56
4 30 Steve 3.20
5 29 Smith 4.60
6 23 Jack 3.80
The first two rows of the data frame is:
Age Name Rating
0 25 Tom 4.23
1 26 James 3.24
tail() returns the last n rows (observe the index values). The default number of elements to display is five, but you may pass a custom number.
import pandas as pd
import numpy as np
#Create a Dictionary of series
d = {'Name':pd.Series(['Tom','James','Ricky','Vin','Steve','Smith','Jack']),
'Age':pd.Series([25,26,25,23,30,29,23]),
'Rating':pd.Series([4.23,3.24,3.98,2.56,3.20,4.6,3.8])}
#Create a DataFrame
df = pd.DataFrame(d)
print ("Our data frame is:")
print df
print ("The last two rows of the data frame is:")
print df.tail(2)
Its output is as follows −
Our data frame is:
Age Name Rating
0 25 Tom 4.23
1 26 James 3.24
2 25 Ricky 3.98
3 23 Vin 2.56
4 30 Steve 3.20
5 29 Smith 4.60
6 23 Jack 3.80
The last two rows of the data frame is:
Age Name Rating
5 29 Smith 4.6
6 23 Jack 3.8
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2674,
"s": 2443,
"text": "By now, we learnt about the three Pandas DataStructures and how to create them. We will majorly focus on the DataFrame objects because of its importance in the real time data processing and also discuss a few other DataStructures."
},
{
"code": null,
"e": 2679,
"s": 2674,
"text": "axes"
},
{
"code": null,
"e": 2717,
"s": 2679,
"text": "Returns a list of the row axis labels"
},
{
"code": null,
"e": 2723,
"s": 2717,
"text": "dtype"
},
{
"code": null,
"e": 2756,
"s": 2723,
"text": "Returns the dtype of the object."
},
{
"code": null,
"e": 2762,
"s": 2756,
"text": "empty"
},
{
"code": null,
"e": 2795,
"s": 2762,
"text": "Returns True if series is empty."
},
{
"code": null,
"e": 2800,
"s": 2795,
"text": "ndim"
},
{
"code": null,
"e": 2874,
"s": 2800,
"text": "Returns the number of dimensions of the underlying data, by\ndefinition 1."
},
{
"code": null,
"e": 2879,
"s": 2874,
"text": "size"
},
{
"code": null,
"e": 2934,
"s": 2879,
"text": "Returns the number of elements in the underlying data."
},
{
"code": null,
"e": 2941,
"s": 2934,
"text": "values"
},
{
"code": null,
"e": 2972,
"s": 2941,
"text": "Returns the Series as ndarray."
},
{
"code": null,
"e": 2979,
"s": 2972,
"text": "head()"
},
{
"code": null,
"e": 3005,
"s": 2979,
"text": "Returns the first n rows."
},
{
"code": null,
"e": 3012,
"s": 3005,
"text": "tail()"
},
{
"code": null,
"e": 3037,
"s": 3012,
"text": "Returns the last n rows."
},
{
"code": null,
"e": 3118,
"s": 3037,
"text": "Let us now create a Series and see all the above tabulated attributes operation."
},
{
"code": null,
"e": 3241,
"s": 3118,
"text": "import pandas as pd\nimport numpy as np\n\n#Create a series with 100 random numbers\ns = pd.Series(np.random.randn(4))\nprint s"
},
{
"code": null,
"e": 3268,
"s": 3241,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 3336,
"s": 3268,
"text": "0 0.967853\n1 -0.148368\n2 -1.395906\n3 -1.758394\ndtype: float64\n"
},
{
"code": null,
"e": 3382,
"s": 3336,
"text": "Returns the list of the labels of the series."
},
{
"code": null,
"e": 3534,
"s": 3382,
"text": "import pandas as pd\nimport numpy as np\n\n#Create a series with 100 random numbers\ns = pd.Series(np.random.randn(4))\nprint (\"The axes are:\")\nprint s.axes"
},
{
"code": null,
"e": 3561,
"s": 3534,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 3614,
"s": 3561,
"text": "The axes are:\n[RangeIndex(start=0, stop=4, step=1)]\n"
},
{
"code": null,
"e": 3703,
"s": 3614,
"text": "The above result is a compact format of a list of values from 0 to 5, i.e., [0,1,2,3,4]."
},
{
"code": null,
"e": 3813,
"s": 3703,
"text": "Returns the Boolean value saying whether the Object is empty or not. True indicates that the object is empty."
},
{
"code": null,
"e": 3973,
"s": 3813,
"text": "import pandas as pd\nimport numpy as np\n\n#Create a series with 100 random numbers\ns = pd.Series(np.random.randn(4))\nprint (\"Is the Object empty?\")\nprint s.empty"
},
{
"code": null,
"e": 4000,
"s": 3973,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 4028,
"s": 4000,
"text": "Is the Object empty?\nFalse\n"
},
{
"code": null,
"e": 4139,
"s": 4028,
"text": "Returns the number of dimensions of the object. By definition, a Series is a 1D data structure, so it returns "
},
{
"code": null,
"e": 4314,
"s": 4139,
"text": "import pandas as pd\nimport numpy as np\n\n#Create a series with 4 random numbers\ns = pd.Series(np.random.randn(4))\nprint s\n\nprint (\"The dimensions of the object:\")\nprint s.ndim"
},
{
"code": null,
"e": 4341,
"s": 4314,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 4442,
"s": 4341,
"text": "0 0.175898\n1 0.166197\n2 -0.609712\n3 -1.377000\ndtype: float64\n\nThe dimensions of the object:\n1\n"
},
{
"code": null,
"e": 4482,
"s": 4442,
"text": "Returns the size(length) of the series."
},
{
"code": null,
"e": 4650,
"s": 4482,
"text": "import pandas as pd\nimport numpy as np\n\n#Create a series with 4 random numbers\ns = pd.Series(np.random.randn(2))\nprint s\nprint (\"The size of the object:\")\nprint s.size"
},
{
"code": null,
"e": 4677,
"s": 4650,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 4746,
"s": 4677,
"text": "0 3.078058\n1 -1.207803\ndtype: float64\n\nThe size of the object:\n2\n"
},
{
"code": null,
"e": 4797,
"s": 4746,
"text": "Returns the actual data in the series as an array."
},
{
"code": null,
"e": 4971,
"s": 4797,
"text": "import pandas as pd\nimport numpy as np\n\n#Create a series with 4 random numbers\ns = pd.Series(np.random.randn(4))\nprint s\n\nprint (\"The actual data series is:\")\nprint s.values"
},
{
"code": null,
"e": 4998,
"s": 4971,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 5143,
"s": 4998,
"text": "0 1.787373\n1 -0.605159\n2 0.180477\n3 -0.140922\ndtype: float64\n\nThe actual data series is:\n[ 1.78737302 -0.60515881 0.18047664 -0.1409218 ]\n"
},
{
"code": null,
"e": 5242,
"s": 5143,
"text": "To view a small sample of a Series or the DataFrame object, use the head() and the tail() methods."
},
{
"code": null,
"e": 5386,
"s": 5242,
"text": "head() returns the first n rows(observe the index values). The default number of elements to display is five, but you may pass a custom number."
},
{
"code": null,
"e": 5607,
"s": 5386,
"text": "import pandas as pd\nimport numpy as np\n\n#Create a series with 4 random numbers\ns = pd.Series(np.random.randn(4))\nprint (\"The original series is:\")\nprint s\n\nprint (\"The first two rows of the data series:\")\nprint s.head(2)"
},
{
"code": null,
"e": 5634,
"s": 5607,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 5807,
"s": 5634,
"text": "The original series is:\n0 0.720876\n1 -0.765898\n2 0.479221\n3 -0.139547\ndtype: float64\n\nThe first two rows of the data series:\n0 0.720876\n1 -0.765898\ndtype: float64\n"
},
{
"code": null,
"e": 5950,
"s": 5807,
"text": "tail() returns the last n rows(observe the index values). The default number of elements to display is five, but you may pass a custom number."
},
{
"code": null,
"e": 6170,
"s": 5950,
"text": "import pandas as pd\nimport numpy as np\n\n#Create a series with 4 random numbers\ns = pd.Series(np.random.randn(4))\nprint (\"The original series is:\")\nprint s\n\nprint (\"The last two rows of the data series:\")\nprint s.tail(2)"
},
{
"code": null,
"e": 6197,
"s": 6170,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 6363,
"s": 6197,
"text": "The original series is:\n0 -0.655091\n1 -0.881407\n2 -0.608592\n3 -2.341413\ndtype: float64\n\nThe last two rows of the data series:\n2 -0.608592\n3 -2.341413\ndtype: float64\n"
},
{
"code": null,
"e": 6536,
"s": 6363,
"text": "Let us now understand what DataFrame Basic Functionality is. The following tables lists down the important attributes or methods that help in DataFrame Basic Functionality."
},
{
"code": null,
"e": 6538,
"s": 6536,
"text": "T"
},
{
"code": null,
"e": 6567,
"s": 6538,
"text": "Transposes rows and columns."
},
{
"code": null,
"e": 6572,
"s": 6567,
"text": "axes"
},
{
"code": null,
"e": 6656,
"s": 6572,
"text": "Returns a list with the row axis labels and column axis labels as the only members."
},
{
"code": null,
"e": 6663,
"s": 6656,
"text": "dtypes"
},
{
"code": null,
"e": 6698,
"s": 6663,
"text": "Returns the dtypes in this object."
},
{
"code": null,
"e": 6704,
"s": 6698,
"text": "empty"
},
{
"code": null,
"e": 6786,
"s": 6704,
"text": "True if NDFrame is entirely empty [no items]; if any of the axes are of length 0."
},
{
"code": null,
"e": 6791,
"s": 6786,
"text": "ndim"
},
{
"code": null,
"e": 6826,
"s": 6791,
"text": "Number of axes / array dimensions."
},
{
"code": null,
"e": 6832,
"s": 6826,
"text": "shape"
},
{
"code": null,
"e": 6898,
"s": 6832,
"text": "Returns a tuple representing the dimensionality of the DataFrame."
},
{
"code": null,
"e": 6903,
"s": 6898,
"text": "size"
},
{
"code": null,
"e": 6938,
"s": 6903,
"text": "Number of elements in the NDFrame."
},
{
"code": null,
"e": 6945,
"s": 6938,
"text": "values"
},
{
"code": null,
"e": 6978,
"s": 6945,
"text": "Numpy representation of NDFrame."
},
{
"code": null,
"e": 6985,
"s": 6978,
"text": "head()"
},
{
"code": null,
"e": 7011,
"s": 6985,
"text": "Returns the first n rows."
},
{
"code": null,
"e": 7018,
"s": 7011,
"text": "tail()"
},
{
"code": null,
"e": 7039,
"s": 7018,
"text": "Returns last n rows."
},
{
"code": null,
"e": 7125,
"s": 7039,
"text": "Let us now create a DataFrame and see all how the above mentioned attributes operate."
},
{
"code": null,
"e": 7457,
"s": 7125,
"text": "import pandas as pd\nimport numpy as np\n\n#Create a Dictionary of series\nd = {'Name':pd.Series(['Tom','James','Ricky','Vin','Steve','Smith','Jack']),\n 'Age':pd.Series([25,26,25,23,30,29,23]),\n 'Rating':pd.Series([4.23,3.24,3.98,2.56,3.20,4.6,3.8])}\n\n#Create a DataFrame\ndf = pd.DataFrame(d)\nprint (\"Our data series is:\")\nprint df"
},
{
"code": null,
"e": 7484,
"s": 7457,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 7691,
"s": 7484,
"text": "Our data series is:\n Age Name Rating\n0 25 Tom 4.23\n1 26 James 3.24\n2 25 Ricky 3.98\n3 23 Vin 2.56\n4 30 Steve 3.20\n5 29 Smith 4.60\n6 23 Jack 3.80\n"
},
{
"code": null,
"e": 7770,
"s": 7691,
"text": "Returns the transpose of the DataFrame. The rows and columns will interchange."
},
{
"code": null,
"e": 8124,
"s": 7770,
"text": "import pandas as pd\nimport numpy as np\n \n# Create a Dictionary of series\nd = {'Name':pd.Series(['Tom','James','Ricky','Vin','Steve','Smith','Jack']),\n 'Age':pd.Series([25,26,25,23,30,29,23]),\n 'Rating':pd.Series([4.23,3.24,3.98,2.56,3.20,4.6,3.8])}\n\n# Create a DataFrame\ndf = pd.DataFrame(d)\nprint (\"The transpose of the data series is:\")\nprint df.T"
},
{
"code": null,
"e": 8151,
"s": 8124,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 8411,
"s": 8151,
"text": "The transpose of the data series is:\n 0 1 2 3 4 5 6\nAge 25 26 25 23 30 29 23\nName Tom James Ricky Vin Steve Smith Jack\nRating 4.23 3.24 3.98 2.56 3.2 4.6 3.8\n"
},
{
"code": null,
"e": 8471,
"s": 8411,
"text": "Returns the list of row axis labels and column axis labels."
},
{
"code": null,
"e": 8832,
"s": 8471,
"text": "import pandas as pd\nimport numpy as np\n\n#Create a Dictionary of series\nd = {'Name':pd.Series(['Tom','James','Ricky','Vin','Steve','Smith','Jack']),\n 'Age':pd.Series([25,26,25,23,30,29,23]),\n 'Rating':pd.Series([4.23,3.24,3.98,2.56,3.20,4.6,3.8])}\n\n#Create a DataFrame\ndf = pd.DataFrame(d)\nprint (\"Row axis labels and column axis labels are:\")\nprint df.axes"
},
{
"code": null,
"e": 8859,
"s": 8832,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 8996,
"s": 8859,
"text": "Row axis labels and column axis labels are:\n\n[RangeIndex(start=0, stop=7, step=1), Index([u'Age', u'Name', u'Rating'],\ndtype='object')]\n"
},
{
"code": null,
"e": 9034,
"s": 8996,
"text": "Returns the data type of each column."
},
{
"code": null,
"e": 9388,
"s": 9034,
"text": "import pandas as pd\nimport numpy as np\n\n#Create a Dictionary of series\nd = {'Name':pd.Series(['Tom','James','Ricky','Vin','Steve','Smith','Jack']),\n 'Age':pd.Series([25,26,25,23,30,29,23]),\n 'Rating':pd.Series([4.23,3.24,3.98,2.56,3.20,4.6,3.8])}\n\n#Create a DataFrame\ndf = pd.DataFrame(d)\nprint (\"The data types of each column are:\")\nprint df.dtypes"
},
{
"code": null,
"e": 9415,
"s": 9388,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 9510,
"s": 9415,
"text": "The data types of each column are:\nAge int64\nName object\nRating float64\ndtype: object\n"
},
{
"code": null,
"e": 9620,
"s": 9510,
"text": "Returns the Boolean value saying whether the Object is empty or not; True indicates that the object is empty."
},
{
"code": null,
"e": 9961,
"s": 9620,
"text": "import pandas as pd\nimport numpy as np\n \n#Create a Dictionary of series\nd = {'Name':pd.Series(['Tom','James','Ricky','Vin','Steve','Smith','Jack']),\n 'Age':pd.Series([25,26,25,23,30,29,23]),\n 'Rating':pd.Series([4.23,3.24,3.98,2.56,3.20,4.6,3.8])}\n \n#Create a DataFrame\ndf = pd.DataFrame(d)\nprint (\"Is the object empty?\")\nprint df.empty"
},
{
"code": null,
"e": 9988,
"s": 9961,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 10016,
"s": 9988,
"text": "Is the object empty?\nFalse\n"
},
{
"code": null,
"e": 10105,
"s": 10016,
"text": "Returns the number of dimensions of the object. By definition, DataFrame is a 2D object."
},
{
"code": null,
"e": 10488,
"s": 10105,
"text": "import pandas as pd\nimport numpy as np\n\n#Create a Dictionary of series\nd = {'Name':pd.Series(['Tom','James','Ricky','Vin','Steve','Smith','Jack']),\n 'Age':pd.Series([25,26,25,23,30,29,23]),\n 'Rating':pd.Series([4.23,3.24,3.98,2.56,3.20,4.6,3.8])}\n\n#Create a DataFrame\ndf = pd.DataFrame(d)\nprint (\"Our object is:\")\nprint df\nprint (\"The dimension of the object is:\")\nprint df.ndim"
},
{
"code": null,
"e": 10515,
"s": 10488,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 10784,
"s": 10515,
"text": "Our object is:\n Age Name Rating\n0 25 Tom 4.23\n1 26 James 3.24\n2 25 Ricky 3.98\n3 23 Vin 2.56\n4 30 Steve 3.20\n5 29 Smith 4.60\n6 23 Jack 3.80\n\nThe dimension of the object is:\n2\n"
},
{
"code": null,
"e": 10941,
"s": 10784,
"text": "Returns a tuple representing the dimensionality of the DataFrame. Tuple (a,b), where a represents the number of rows and b represents the number of columns."
},
{
"code": null,
"e": 11323,
"s": 10941,
"text": "import pandas as pd\nimport numpy as np\n \n#Create a Dictionary of series\nd = {'Name':pd.Series(['Tom','James','Ricky','Vin','Steve','Smith','Jack']),\n 'Age':pd.Series([25,26,25,23,30,29,23]),\n 'Rating':pd.Series([4.23,3.24,3.98,2.56,3.20,4.6,3.8])}\n \n#Create a DataFrame\ndf = pd.DataFrame(d)\nprint (\"Our object is:\")\nprint df\nprint (\"The shape of the object is:\")\nprint df.shape"
},
{
"code": null,
"e": 11350,
"s": 11323,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 11580,
"s": 11350,
"text": "Our object is:\n Age Name Rating\n0 25 Tom 4.23\n1 26 James 3.24\n2 25 Ricky 3.98\n3 23 Vin 2.56\n4 30 Steve 3.20\n5 29 Smith 4.60\n6 23 Jack 3.80\n\nThe shape of the object is:\n(7, 3)\n"
},
{
"code": null,
"e": 11629,
"s": 11580,
"text": "Returns the number of elements in the DataFrame."
},
{
"code": null,
"e": 12029,
"s": 11629,
"text": "import pandas as pd\nimport numpy as np\n \n#Create a Dictionary of series\nd = {'Name':pd.Series(['Tom','James','Ricky','Vin','Steve','Smith','Jack']),\n 'Age':pd.Series([25,26,25,23,30,29,23]),\n 'Rating':pd.Series([4.23,3.24,3.98,2.56,3.20,4.6,3.8])}\n \n#Create a DataFrame\ndf = pd.DataFrame(d)\nprint (\"Our object is:\")\nprint df\nprint (\"The total number of elements in our object is:\")\nprint df.size"
},
{
"code": null,
"e": 12056,
"s": 12029,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 12309,
"s": 12056,
"text": "Our object is:\n Age Name Rating\n0 25 Tom 4.23\n1 26 James 3.24\n2 25 Ricky 3.98\n3 23 Vin 2.56\n4 30 Steve 3.20\n5 29 Smith 4.60\n6 23 Jack 3.80\n\nThe total number of elements in our object is:\n21\n"
},
{
"code": null,
"e": 12365,
"s": 12309,
"text": "Returns the actual data in the DataFrame as an NDarray."
},
{
"code": null,
"e": 12758,
"s": 12365,
"text": "import pandas as pd\nimport numpy as np\n \n#Create a Dictionary of series\nd = {'Name':pd.Series(['Tom','James','Ricky','Vin','Steve','Smith','Jack']),\n 'Age':pd.Series([25,26,25,23,30,29,23]),\n 'Rating':pd.Series([4.23,3.24,3.98,2.56,3.20,4.6,3.8])}\n \n#Create a DataFrame\ndf = pd.DataFrame(d)\nprint (\"Our object is:\")\nprint df\nprint (\"The actual data in our data frame is:\")\nprint df.values"
},
{
"code": null,
"e": 12785,
"s": 12758,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 13145,
"s": 12785,
"text": "Our object is:\n Age Name Rating\n0 25 Tom 4.23\n1 26 James 3.24\n2 25 Ricky 3.98\n3 23 Vin 2.56\n4 30 Steve 3.20\n5 29 Smith 4.60\n6 23 Jack 3.80\nThe actual data in our data frame is:\n[[25 'Tom' 4.23]\n[26 'James' 3.24]\n[25 'Ricky' 3.98]\n[23 'Vin' 2.56]\n[30 'Steve' 3.2]\n[29 'Smith' 4.6]\n[23 'Jack' 3.8]]\n"
},
{
"code": null,
"e": 13371,
"s": 13145,
"text": "To view a small sample of a DataFrame object, use the head() and tail() methods. head() returns the first n rows (observe the index values). The default number of elements to display is five, but you may pass a custom number."
},
{
"code": null,
"e": 13771,
"s": 13371,
"text": "import pandas as pd\nimport numpy as np\n \n#Create a Dictionary of series\nd = {'Name':pd.Series(['Tom','James','Ricky','Vin','Steve','Smith','Jack']),\n 'Age':pd.Series([25,26,25,23,30,29,23]),\n 'Rating':pd.Series([4.23,3.24,3.98,2.56,3.20,4.6,3.8])}\n\n#Create a DataFrame\ndf = pd.DataFrame(d)\nprint (\"Our data frame is:\")\nprint df\nprint (\"The first two rows of the data frame is:\")\nprint df.head(2)"
},
{
"code": null,
"e": 13798,
"s": 13771,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 14111,
"s": 13798,
"text": "Our data frame is:\n Age Name Rating\n0 25 Tom 4.23\n1 26 James 3.24\n2 25 Ricky 3.98\n3 23 Vin 2.56\n4 30 Steve 3.20\n5 29 Smith 4.60\n6 23 Jack 3.80\n\nThe first two rows of the data frame is:\n Age Name Rating\n0 25 Tom 4.23\n1 26 James 3.24\n"
},
{
"code": null,
"e": 14255,
"s": 14111,
"text": "tail() returns the last n rows (observe the index values). The default number of elements to display is five, but you may pass a custom number."
},
{
"code": null,
"e": 14655,
"s": 14255,
"text": "import pandas as pd\nimport numpy as np\n\n#Create a Dictionary of series\nd = {'Name':pd.Series(['Tom','James','Ricky','Vin','Steve','Smith','Jack']),\n 'Age':pd.Series([25,26,25,23,30,29,23]), \n 'Rating':pd.Series([4.23,3.24,3.98,2.56,3.20,4.6,3.8])}\n \n#Create a DataFrame\ndf = pd.DataFrame(d)\nprint (\"Our data frame is:\")\nprint df\nprint (\"The last two rows of the data frame is:\")\nprint df.tail(2)"
},
{
"code": null,
"e": 14682,
"s": 14655,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 15000,
"s": 14682,
"text": "Our data frame is:\n Age Name Rating\n0 25 Tom 4.23\n1 26 James 3.24\n2 25 Ricky 3.98\n3 23 Vin 2.56\n4 30 Steve 3.20\n5 29 Smith 4.60\n6 23 Jack 3.80\n\nThe last two rows of the data frame is:\n Age Name Rating\n5 29 Smith 4.6\n6 23 Jack 3.8\n"
},
{
"code": null,
"e": 15037,
"s": 15000,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 15053,
"s": 15037,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 15086,
"s": 15053,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 15105,
"s": 15086,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 15140,
"s": 15105,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 15162,
"s": 15140,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 15196,
"s": 15162,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 15224,
"s": 15196,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 15259,
"s": 15224,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 15273,
"s": 15259,
"text": " Lets Kode It"
},
{
"code": null,
"e": 15306,
"s": 15273,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 15323,
"s": 15306,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 15330,
"s": 15323,
"text": " Print"
},
{
"code": null,
"e": 15341,
"s": 15330,
"text": " Add Notes"
}
] |
Machine Translation Evaluation with sacreBLEU and BERTScore | by Ng Wai Foong | Towards Data Science
|
By reading this piece, you will learn to evaluate your machine translation models using the following packages:
sacreBLEU
BERTScore
For your information, BLEU (bilingual evaluation understudy) is one of the most popular metric for evaluating machine-translated text. It can be used to evaluate translations of any language provided that there exists some form of word boundary in the text.
BLEU’s output is usually a score between 0 and 100, indicating the similarity value between the reference text and hypothesis text. The higher the value, the better the translations.
Having said that, one of the major downside for BLEU is the need to tokenize the text properly. For example, you can easily tokenize any English sentences using whitespace as the delimiter. However, tokenization can be challenging for languages such as Burmese, Chinese and Thai.
In addition, there are criticism that an increase in the BLEU score does not guarantee better translations. This is fairly noticeable when the translated text contains similar words or synonyms that convey the same message. For example, the following sentences are in fact identical from human perspective but will not score 100 when evaluating them with BLEU.
# Reference textHi, how are you?# Hypothesis textHello, how are you?
Nevertheless, let’s explore how you can evaluate the BLEU score easily using sacreBLEU which:
... provides hassle-free computation of shareable, comparable, and reproducible BLEU scores.
It is highly recommended to create a new virtual environment before you continue. Activate it and run the following command to install sacrebleu:
pip install sacrebleu
Create a new file called bleu_scorer.py and append the following import statement at the top of the file:
from sacrebleu.metrics import BLEU
Define the hypothesis text and reference text as follows:
refs = [['The dog bit the guy.', 'It was not unexpected.', 'The man bit him first.']]hyps = ['The dog bit the man.', "It wasn't surprising.", 'The man had just bitten him.']
hyps consists of a list of text while refs must be a list of list of text. In actual use cases, you should read it from a file as follows (strip to remove the ending newline):
with open('hyps.txt', 'r', encoding='utf8') as f: lines = [x.strip() for x in f]
For multi-references, you should define it as follows:
refs = [['The dog bit the guy.', 'It was not unexpected.', 'The man bit him first.'], ['The dog had bit the man.', 'No one was surprised.', 'The man had bitten the dog.']]hyps = ['The dog bit the man.', "It wasn't surprising.", 'The man had just bitten him.']
The following code highlights the base structure for multi-references:
refs = [[ref1_for_sent1, ref1_for_sent2 ...,], [ref2_for_sent1, ref2_for_sent2, ...], ...]
Then, create a new instance using the metrics.BLEU object-oriented API:
bleu = BLEU()
It accepts the following input parameters:
lowercase — If True, lowercased BLEU is computed.
tokenize — The tokenizer to use. If None, defaults to language-specific tokenizers with ‘13a’ as the fallback default.
smooth_method — The smoothing method to use (‘floor’, ‘add-k’, ‘exp’ or ‘none’).
smooth_value — The smoothing value for `floor` and `add-k` methods. `None` falls back to default value.
max_ngram_order — If given, it overrides the maximum n-gram order (default: 4) when computing precisions.
The max ngram is default to 4 as the it was found to be the highest correlation with monolingual human judgements based on the following research paper.
Call the corpus_score function to calculate the BLUE score of the entire corpus:
result = bleu.corpus_score(hyps, refs)
You can find the complete code at the following gist:
The output is as follows:
29.44 82.4/42.9/27.3/12.5 (BP = 0.889 ratio = 0.895 hyp_len = 17 ref_len = 19)
29.44 refers to the final BLEU score
82.4/42.9/27.3/12.5 represents the precision value for 1–4 ngram order
BP is the brevity penalty
ratio indicates the ratio between hypothesis length and reference length
hyp_len refers to the total number of characters for hypothesis text
ref_len is the total number of characters for reference text
You can find more information on each individual metrics at the following repository.
On the other hand, BERTScore has a few outstanding points that differs from BLEU. It
... leverages the pre-trained contextual embeddings from BERT and matches words in candidate and reference sentences by cosine similarity.
It has been shown to correlate with human judgment on sentence-level and system-level evaluation. Moreover, BERTScore computes precision, recall, and F1 measure, which can be useful for evaluating different language generation tasks.
This provides better evaluation for sentences that use synonyms or similar words. For example:
# reference textThe weather is cold today.# hypothesis textIt is freezing today.
Run the following command to install BERTScore via pip install:
pip install bert-score
Create a new file called bert_scorer.py and add the following code inside it:
from bert_score import BERTScorer
Next, you need to define the reference and hypothesis text. BERTScore accepts both a list of text (single reference) or list of list of text (multiple references):
refs = [['The dog bit the guy.', 'The dog had bit the man.'], ['It was not unexpected.', 'No one was surprised.'], ['The man bit him first.', 'The man had bitten the dog.']]hyps = ['The dog bit the man.', "It wasn't surprising.", 'The man had just bitten him.']
The structure for multi-references is slightly different compared to sacreBLEU. It is based on the following syntax:
refs = [[ref1_for_sent1, ref2_for_sent1 ...,], [ref1_for_sent2, ref2_for_sent2, ...], ...]
Instantiate a new instance of the BERTScorer object-oriented API as follows:
scorer = BERTScorer(lang="en", rescale_with_baseline=True)
It accepts:
model_type — contexual embedding model specification, default using the suggested model for the target language; has to specify at least one of model_type or lang
verbose — turn on intermediate status update
device — if None, the model lives on cuda:0 if cuda is available
batch_size — processing batch size
nthreads — number of threads
lang — language of the sentences. It needs to be specified when rescale_with_baseline is True
rescale_with_baseline — rescale bertscore with pre-computed baseline
baseline_path — customized baseline file
use_fast_tokenizer — to use HuggingFace’s fast tokenizer
By default, it uses the following model based on the lang specified:
en — roberta-large
en-sci — allenai/scibert_scivocab_uncased
zh — bert-base-chinese
tr — dbmdz/bert-base-turkish-cased
The rest of the language will be based on bert-base-multilingual-cased. If you intend to customize the model, kindly check the following Google sheet to find out more.
Rescale baselines helps to adjust the output score to be more readable. This is simply because some contextual embedding models tend produce scores in a very narrow range. You can find more information on this at the following blog post.
The repository also contains a few pre-computed baseline file for you. Simply head to the following repository and download the desired file based on the mode that you intend to use.
It will download the model and dependencies from HuggingFace during the initial run. Subsequently, it will reuse the same downloaded model. On Linux operating system, the model is located at the following directory:
~/.cache/huggingface/transformers/
Call the score function as follows:
P, R, F1 = scorer.score(hyps, refs)
It will returns the tensors for:
P — precision
R — recall
F1 — F1-score
Here is an example output for F1-score:
tensor([0.9014, 0.8710, 0.5036, 0.7563, 0.8073, 0.8103, 0.7644, 0.8002, 0.6673, 0.7086])
Please be noted that the underlying values range from -1 to 1.
You can easily compute the corpus score by calling the mean function as follows:
print(F1.mean())# 0.6798698902130217
The complete code is located at the following gist:
Please be noted that running BERTScore is a lot slower compared to sacreBLEU. Make sure that you have sufficient GPU memory during evaluation.
For more information on BERTScore, kindly check the example notebook from the official repository.
let’s recap what you have learned today.
This article started off with a brief introduction on BLEU, the advantages and disadvantages of using it to evaluate translated text.
Next, it covered on using sacreBLEU to compute the corpus-level BLEU score. The output also includes the precision value for 1–4 ngrams.
Subsequently, it explored on BERTScore which evaluate the translated text by cosine similarity. The score function returns the tensors for precision, recall and F1-score respectively.
Thanks for reading this piece. Have a great day ahead!
Github — sacreBLEUGithub — BERTScore
Github — sacreBLEU
Github — BERTScore
|
[
{
"code": null,
"e": 283,
"s": 171,
"text": "By reading this piece, you will learn to evaluate your machine translation models using the following packages:"
},
{
"code": null,
"e": 293,
"s": 283,
"text": "sacreBLEU"
},
{
"code": null,
"e": 303,
"s": 293,
"text": "BERTScore"
},
{
"code": null,
"e": 561,
"s": 303,
"text": "For your information, BLEU (bilingual evaluation understudy) is one of the most popular metric for evaluating machine-translated text. It can be used to evaluate translations of any language provided that there exists some form of word boundary in the text."
},
{
"code": null,
"e": 744,
"s": 561,
"text": "BLEU’s output is usually a score between 0 and 100, indicating the similarity value between the reference text and hypothesis text. The higher the value, the better the translations."
},
{
"code": null,
"e": 1024,
"s": 744,
"text": "Having said that, one of the major downside for BLEU is the need to tokenize the text properly. For example, you can easily tokenize any English sentences using whitespace as the delimiter. However, tokenization can be challenging for languages such as Burmese, Chinese and Thai."
},
{
"code": null,
"e": 1385,
"s": 1024,
"text": "In addition, there are criticism that an increase in the BLEU score does not guarantee better translations. This is fairly noticeable when the translated text contains similar words or synonyms that convey the same message. For example, the following sentences are in fact identical from human perspective but will not score 100 when evaluating them with BLEU."
},
{
"code": null,
"e": 1454,
"s": 1385,
"text": "# Reference textHi, how are you?# Hypothesis textHello, how are you?"
},
{
"code": null,
"e": 1548,
"s": 1454,
"text": "Nevertheless, let’s explore how you can evaluate the BLEU score easily using sacreBLEU which:"
},
{
"code": null,
"e": 1641,
"s": 1548,
"text": "... provides hassle-free computation of shareable, comparable, and reproducible BLEU scores."
},
{
"code": null,
"e": 1787,
"s": 1641,
"text": "It is highly recommended to create a new virtual environment before you continue. Activate it and run the following command to install sacrebleu:"
},
{
"code": null,
"e": 1809,
"s": 1787,
"text": "pip install sacrebleu"
},
{
"code": null,
"e": 1915,
"s": 1809,
"text": "Create a new file called bleu_scorer.py and append the following import statement at the top of the file:"
},
{
"code": null,
"e": 1950,
"s": 1915,
"text": "from sacrebleu.metrics import BLEU"
},
{
"code": null,
"e": 2008,
"s": 1950,
"text": "Define the hypothesis text and reference text as follows:"
},
{
"code": null,
"e": 2182,
"s": 2008,
"text": "refs = [['The dog bit the guy.', 'It was not unexpected.', 'The man bit him first.']]hyps = ['The dog bit the man.', \"It wasn't surprising.\", 'The man had just bitten him.']"
},
{
"code": null,
"e": 2358,
"s": 2182,
"text": "hyps consists of a list of text while refs must be a list of list of text. In actual use cases, you should read it from a file as follows (strip to remove the ending newline):"
},
{
"code": null,
"e": 2442,
"s": 2358,
"text": "with open('hyps.txt', 'r', encoding='utf8') as f: lines = [x.strip() for x in f]"
},
{
"code": null,
"e": 2497,
"s": 2442,
"text": "For multi-references, you should define it as follows:"
},
{
"code": null,
"e": 2764,
"s": 2497,
"text": "refs = [['The dog bit the guy.', 'It was not unexpected.', 'The man bit him first.'], ['The dog had bit the man.', 'No one was surprised.', 'The man had bitten the dog.']]hyps = ['The dog bit the man.', \"It wasn't surprising.\", 'The man had just bitten him.']"
},
{
"code": null,
"e": 2835,
"s": 2764,
"text": "The following code highlights the base structure for multi-references:"
},
{
"code": null,
"e": 2926,
"s": 2835,
"text": "refs = [[ref1_for_sent1, ref1_for_sent2 ...,], [ref2_for_sent1, ref2_for_sent2, ...], ...]"
},
{
"code": null,
"e": 2998,
"s": 2926,
"text": "Then, create a new instance using the metrics.BLEU object-oriented API:"
},
{
"code": null,
"e": 3012,
"s": 2998,
"text": "bleu = BLEU()"
},
{
"code": null,
"e": 3055,
"s": 3012,
"text": "It accepts the following input parameters:"
},
{
"code": null,
"e": 3105,
"s": 3055,
"text": "lowercase — If True, lowercased BLEU is computed."
},
{
"code": null,
"e": 3224,
"s": 3105,
"text": "tokenize — The tokenizer to use. If None, defaults to language-specific tokenizers with ‘13a’ as the fallback default."
},
{
"code": null,
"e": 3305,
"s": 3224,
"text": "smooth_method — The smoothing method to use (‘floor’, ‘add-k’, ‘exp’ or ‘none’)."
},
{
"code": null,
"e": 3409,
"s": 3305,
"text": "smooth_value — The smoothing value for `floor` and `add-k` methods. `None` falls back to default value."
},
{
"code": null,
"e": 3515,
"s": 3409,
"text": "max_ngram_order — If given, it overrides the maximum n-gram order (default: 4) when computing precisions."
},
{
"code": null,
"e": 3668,
"s": 3515,
"text": "The max ngram is default to 4 as the it was found to be the highest correlation with monolingual human judgements based on the following research paper."
},
{
"code": null,
"e": 3749,
"s": 3668,
"text": "Call the corpus_score function to calculate the BLUE score of the entire corpus:"
},
{
"code": null,
"e": 3788,
"s": 3749,
"text": "result = bleu.corpus_score(hyps, refs)"
},
{
"code": null,
"e": 3842,
"s": 3788,
"text": "You can find the complete code at the following gist:"
},
{
"code": null,
"e": 3868,
"s": 3842,
"text": "The output is as follows:"
},
{
"code": null,
"e": 3947,
"s": 3868,
"text": "29.44 82.4/42.9/27.3/12.5 (BP = 0.889 ratio = 0.895 hyp_len = 17 ref_len = 19)"
},
{
"code": null,
"e": 3984,
"s": 3947,
"text": "29.44 refers to the final BLEU score"
},
{
"code": null,
"e": 4055,
"s": 3984,
"text": "82.4/42.9/27.3/12.5 represents the precision value for 1–4 ngram order"
},
{
"code": null,
"e": 4081,
"s": 4055,
"text": "BP is the brevity penalty"
},
{
"code": null,
"e": 4154,
"s": 4081,
"text": "ratio indicates the ratio between hypothesis length and reference length"
},
{
"code": null,
"e": 4223,
"s": 4154,
"text": "hyp_len refers to the total number of characters for hypothesis text"
},
{
"code": null,
"e": 4284,
"s": 4223,
"text": "ref_len is the total number of characters for reference text"
},
{
"code": null,
"e": 4370,
"s": 4284,
"text": "You can find more information on each individual metrics at the following repository."
},
{
"code": null,
"e": 4455,
"s": 4370,
"text": "On the other hand, BERTScore has a few outstanding points that differs from BLEU. It"
},
{
"code": null,
"e": 4594,
"s": 4455,
"text": "... leverages the pre-trained contextual embeddings from BERT and matches words in candidate and reference sentences by cosine similarity."
},
{
"code": null,
"e": 4828,
"s": 4594,
"text": "It has been shown to correlate with human judgment on sentence-level and system-level evaluation. Moreover, BERTScore computes precision, recall, and F1 measure, which can be useful for evaluating different language generation tasks."
},
{
"code": null,
"e": 4923,
"s": 4828,
"text": "This provides better evaluation for sentences that use synonyms or similar words. For example:"
},
{
"code": null,
"e": 5004,
"s": 4923,
"text": "# reference textThe weather is cold today.# hypothesis textIt is freezing today."
},
{
"code": null,
"e": 5068,
"s": 5004,
"text": "Run the following command to install BERTScore via pip install:"
},
{
"code": null,
"e": 5091,
"s": 5068,
"text": "pip install bert-score"
},
{
"code": null,
"e": 5169,
"s": 5091,
"text": "Create a new file called bert_scorer.py and add the following code inside it:"
},
{
"code": null,
"e": 5203,
"s": 5169,
"text": "from bert_score import BERTScorer"
},
{
"code": null,
"e": 5367,
"s": 5203,
"text": "Next, you need to define the reference and hypothesis text. BERTScore accepts both a list of text (single reference) or list of list of text (multiple references):"
},
{
"code": null,
"e": 5689,
"s": 5367,
"text": "refs = [['The dog bit the guy.', 'The dog had bit the man.'], ['It was not unexpected.', 'No one was surprised.'], ['The man bit him first.', 'The man had bitten the dog.']]hyps = ['The dog bit the man.', \"It wasn't surprising.\", 'The man had just bitten him.']"
},
{
"code": null,
"e": 5806,
"s": 5689,
"text": "The structure for multi-references is slightly different compared to sacreBLEU. It is based on the following syntax:"
},
{
"code": null,
"e": 5897,
"s": 5806,
"text": "refs = [[ref1_for_sent1, ref2_for_sent1 ...,], [ref1_for_sent2, ref2_for_sent2, ...], ...]"
},
{
"code": null,
"e": 5974,
"s": 5897,
"text": "Instantiate a new instance of the BERTScorer object-oriented API as follows:"
},
{
"code": null,
"e": 6033,
"s": 5974,
"text": "scorer = BERTScorer(lang=\"en\", rescale_with_baseline=True)"
},
{
"code": null,
"e": 6045,
"s": 6033,
"text": "It accepts:"
},
{
"code": null,
"e": 6208,
"s": 6045,
"text": "model_type — contexual embedding model specification, default using the suggested model for the target language; has to specify at least one of model_type or lang"
},
{
"code": null,
"e": 6253,
"s": 6208,
"text": "verbose — turn on intermediate status update"
},
{
"code": null,
"e": 6318,
"s": 6253,
"text": "device — if None, the model lives on cuda:0 if cuda is available"
},
{
"code": null,
"e": 6353,
"s": 6318,
"text": "batch_size — processing batch size"
},
{
"code": null,
"e": 6382,
"s": 6353,
"text": "nthreads — number of threads"
},
{
"code": null,
"e": 6476,
"s": 6382,
"text": "lang — language of the sentences. It needs to be specified when rescale_with_baseline is True"
},
{
"code": null,
"e": 6545,
"s": 6476,
"text": "rescale_with_baseline — rescale bertscore with pre-computed baseline"
},
{
"code": null,
"e": 6586,
"s": 6545,
"text": "baseline_path — customized baseline file"
},
{
"code": null,
"e": 6643,
"s": 6586,
"text": "use_fast_tokenizer — to use HuggingFace’s fast tokenizer"
},
{
"code": null,
"e": 6712,
"s": 6643,
"text": "By default, it uses the following model based on the lang specified:"
},
{
"code": null,
"e": 6731,
"s": 6712,
"text": "en — roberta-large"
},
{
"code": null,
"e": 6773,
"s": 6731,
"text": "en-sci — allenai/scibert_scivocab_uncased"
},
{
"code": null,
"e": 6796,
"s": 6773,
"text": "zh — bert-base-chinese"
},
{
"code": null,
"e": 6831,
"s": 6796,
"text": "tr — dbmdz/bert-base-turkish-cased"
},
{
"code": null,
"e": 6999,
"s": 6831,
"text": "The rest of the language will be based on bert-base-multilingual-cased. If you intend to customize the model, kindly check the following Google sheet to find out more."
},
{
"code": null,
"e": 7237,
"s": 6999,
"text": "Rescale baselines helps to adjust the output score to be more readable. This is simply because some contextual embedding models tend produce scores in a very narrow range. You can find more information on this at the following blog post."
},
{
"code": null,
"e": 7420,
"s": 7237,
"text": "The repository also contains a few pre-computed baseline file for you. Simply head to the following repository and download the desired file based on the mode that you intend to use."
},
{
"code": null,
"e": 7636,
"s": 7420,
"text": "It will download the model and dependencies from HuggingFace during the initial run. Subsequently, it will reuse the same downloaded model. On Linux operating system, the model is located at the following directory:"
},
{
"code": null,
"e": 7671,
"s": 7636,
"text": "~/.cache/huggingface/transformers/"
},
{
"code": null,
"e": 7707,
"s": 7671,
"text": "Call the score function as follows:"
},
{
"code": null,
"e": 7743,
"s": 7707,
"text": "P, R, F1 = scorer.score(hyps, refs)"
},
{
"code": null,
"e": 7776,
"s": 7743,
"text": "It will returns the tensors for:"
},
{
"code": null,
"e": 7790,
"s": 7776,
"text": "P — precision"
},
{
"code": null,
"e": 7801,
"s": 7790,
"text": "R — recall"
},
{
"code": null,
"e": 7815,
"s": 7801,
"text": "F1 — F1-score"
},
{
"code": null,
"e": 7855,
"s": 7815,
"text": "Here is an example output for F1-score:"
},
{
"code": null,
"e": 7944,
"s": 7855,
"text": "tensor([0.9014, 0.8710, 0.5036, 0.7563, 0.8073, 0.8103, 0.7644, 0.8002, 0.6673, 0.7086])"
},
{
"code": null,
"e": 8007,
"s": 7944,
"text": "Please be noted that the underlying values range from -1 to 1."
},
{
"code": null,
"e": 8088,
"s": 8007,
"text": "You can easily compute the corpus score by calling the mean function as follows:"
},
{
"code": null,
"e": 8125,
"s": 8088,
"text": "print(F1.mean())# 0.6798698902130217"
},
{
"code": null,
"e": 8177,
"s": 8125,
"text": "The complete code is located at the following gist:"
},
{
"code": null,
"e": 8320,
"s": 8177,
"text": "Please be noted that running BERTScore is a lot slower compared to sacreBLEU. Make sure that you have sufficient GPU memory during evaluation."
},
{
"code": null,
"e": 8419,
"s": 8320,
"text": "For more information on BERTScore, kindly check the example notebook from the official repository."
},
{
"code": null,
"e": 8460,
"s": 8419,
"text": "let’s recap what you have learned today."
},
{
"code": null,
"e": 8594,
"s": 8460,
"text": "This article started off with a brief introduction on BLEU, the advantages and disadvantages of using it to evaluate translated text."
},
{
"code": null,
"e": 8731,
"s": 8594,
"text": "Next, it covered on using sacreBLEU to compute the corpus-level BLEU score. The output also includes the precision value for 1–4 ngrams."
},
{
"code": null,
"e": 8915,
"s": 8731,
"text": "Subsequently, it explored on BERTScore which evaluate the translated text by cosine similarity. The score function returns the tensors for precision, recall and F1-score respectively."
},
{
"code": null,
"e": 8970,
"s": 8915,
"text": "Thanks for reading this piece. Have a great day ahead!"
},
{
"code": null,
"e": 9007,
"s": 8970,
"text": "Github — sacreBLEUGithub — BERTScore"
},
{
"code": null,
"e": 9026,
"s": 9007,
"text": "Github — sacreBLEU"
}
] |
Matplotlib.figure.Figure.set_figheight() in Python - GeeksforGeeks
|
03 May, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The figure module provides the top-level Artist, the Figure, which contains all the plot elements. This module is used to control the default spacing of the subplots and top level container for all plot elements.
The set_figheight() method figure module of matplotlib library is used to set the height of the figure in inches.
Syntax: set_figheight(self, val, forward=True)
Parameters: This method accept the following parameters that are discussed below:
val : This parameter is the float value.
forward : This parameter contains the boolean value.
Returns: This method does not returns any value.
Below examples illustrate the matplotlib.figure.Figure.set_figheight() function in matplotlib.figure:
Example 1:
# Implementation of matplotlib function import matplotlib.pyplot as plt from matplotlib.figure import Figurefrom mpl_toolkits.axisartist.axislines import Subplot import numpy as np fig = plt.figure() ax = Subplot(fig, 111) fig.add_subplot(ax) fig.set_figheight(7.6) fig.suptitle("""matplotlib.figure.Figure.set_figheight()function Example\n\n""", fontweight ="bold") plt.show()
Output:
Example 2:
# Implementation of matplotlib function import matplotlib.pyplot as plt from matplotlib.figure import Figureimport numpy as np fig = plt.figure(figsize =(7, 6)) ax = fig.add_axes([0.1, 0.1, 0.8, 0.8]) xx = np.arange(0, 2 * np.pi, 0.01) ax.plot(xx, np.sin(xx)) fig.set_figheight(4.8) fig.suptitle("""matplotlib.figure.Figure.set_figheight()function Example\n\n""", fontweight ="bold") plt.show()
Output:
Matplotlib figure-class
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Pandas dataframe.groupby()
Create a directory in Python
Defaultdict in Python
Python | Get unique values from a list
|
[
{
"code": null,
"e": 25647,
"s": 25619,
"text": "\n03 May, 2020"
},
{
"code": null,
"e": 25958,
"s": 25647,
"text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The figure module provides the top-level Artist, the Figure, which contains all the plot elements. This module is used to control the default spacing of the subplots and top level container for all plot elements."
},
{
"code": null,
"e": 26072,
"s": 25958,
"text": "The set_figheight() method figure module of matplotlib library is used to set the height of the figure in inches."
},
{
"code": null,
"e": 26119,
"s": 26072,
"text": "Syntax: set_figheight(self, val, forward=True)"
},
{
"code": null,
"e": 26201,
"s": 26119,
"text": "Parameters: This method accept the following parameters that are discussed below:"
},
{
"code": null,
"e": 26242,
"s": 26201,
"text": "val : This parameter is the float value."
},
{
"code": null,
"e": 26295,
"s": 26242,
"text": "forward : This parameter contains the boolean value."
},
{
"code": null,
"e": 26344,
"s": 26295,
"text": "Returns: This method does not returns any value."
},
{
"code": null,
"e": 26446,
"s": 26344,
"text": "Below examples illustrate the matplotlib.figure.Figure.set_figheight() function in matplotlib.figure:"
},
{
"code": null,
"e": 26457,
"s": 26446,
"text": "Example 1:"
},
{
"code": "# Implementation of matplotlib function import matplotlib.pyplot as plt from matplotlib.figure import Figurefrom mpl_toolkits.axisartist.axislines import Subplot import numpy as np fig = plt.figure() ax = Subplot(fig, 111) fig.add_subplot(ax) fig.set_figheight(7.6) fig.suptitle(\"\"\"matplotlib.figure.Figure.set_figheight()function Example\\n\\n\"\"\", fontweight =\"bold\") plt.show()",
"e": 26859,
"s": 26457,
"text": null
},
{
"code": null,
"e": 26867,
"s": 26859,
"text": "Output:"
},
{
"code": null,
"e": 26878,
"s": 26867,
"text": "Example 2:"
},
{
"code": "# Implementation of matplotlib function import matplotlib.pyplot as plt from matplotlib.figure import Figureimport numpy as np fig = plt.figure(figsize =(7, 6)) ax = fig.add_axes([0.1, 0.1, 0.8, 0.8]) xx = np.arange(0, 2 * np.pi, 0.01) ax.plot(xx, np.sin(xx)) fig.set_figheight(4.8) fig.suptitle(\"\"\"matplotlib.figure.Figure.set_figheight()function Example\\n\\n\"\"\", fontweight =\"bold\") plt.show() ",
"e": 27307,
"s": 26878,
"text": null
},
{
"code": null,
"e": 27315,
"s": 27307,
"text": "Output:"
},
{
"code": null,
"e": 27339,
"s": 27315,
"text": "Matplotlib figure-class"
},
{
"code": null,
"e": 27357,
"s": 27339,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 27364,
"s": 27357,
"text": "Python"
},
{
"code": null,
"e": 27462,
"s": 27364,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27494,
"s": 27462,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27536,
"s": 27494,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27578,
"s": 27536,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27634,
"s": 27578,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27661,
"s": 27634,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27692,
"s": 27661,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27728,
"s": 27692,
"text": "Python | Pandas dataframe.groupby()"
},
{
"code": null,
"e": 27757,
"s": 27728,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 27779,
"s": 27757,
"text": "Defaultdict in Python"
}
] |
BCD to binary conversion in 8051
|
In this problem, we will see how to convert 8-bit BCD number to its Binary (Hexadecimal)equivalent. The BCD number is stored at location 20H. After converting, the results will be stored at 30H.
So let us assume the data is D5H. The program converts the binary value ofD5H to BCD value 213D.
MOVR0,#20H; Initialize the address of the data
MOVA,@R0;Get the data from an address, which is stored in R0
MOVR2,A; Store the content of A into R2
CLRA;Clear the content of A to 00H
MOVR3,#00H
LOOP: ADDA,#01H;increment A by 01H
DAA; Decimal Adjust of the accumulator content
INCR3; Increase R3 to keep track of the hex value
CJNEA,02H,LOOP ;Run the loop until A = R2
MOVR0,#30H; Point the destination location
MOVA,R3; Move R3 to A
MOV@R0,A; Store A content to the memory location pointed by R0
HALT: SJMPHALT
Here the logic is very simple. We are just taking the number from the memory. And storing that value into R2. By this value, we can compare while executing the loop.
The accumulator (A) and register R3 is set to 00H at first. So we are just increasing the value of A by 01H. We can use the INC A instruction to increment the value, but in this case, the value is incremented by using ADDA, #01H. The reason behind it is the INCinstruction does not affect the CY and AC flags. But these flags are needed to use DA A instruction for decimal adjusting. After increasing the value of A, DA A instruction is executed to convert the value to decimal. By using this decimal value, we can compare with the number stored inR2. In each iteration the value of R3 is incremented by 1, this is acting like a counter. So at the end, we are getting the output from register R3.
We can do the same thing using some other logic also. Here no additional loops are needed to do the task. We are just multiplying the digit of 10th place of the BCD number with 0AH. Then adding the second digit with the result to get the number.
If the number is 94, then it is multiplying 0AH with 9.
(9 * 0AH) = 5AH, thenadding 4 with 5AH. (5AH + 4) = 5EH.
MOVR0,#20H; Initialize the address of the data
MOVA,@R0; Get the data from an address, which is stored in R0
MOVR2,A;Store the content of A into R2
SWAPA; Swap the nibbles of A register
ANLA,#0FH;Mask the Higher Nibble of A
MOVB,0AH;Take 0AH = 10D into B
MULAB ;Multiply A with B, and get result into A
MOVA,R2;Copy R2 content to A
ANLA,#0FH;Mask the higher nibble of A
ADDA,R2
MOVR0,#30H;Point the destination location
MOVA,R3;Move R3 to A
MOV@R0,A;Store A content to memory location pointed by R0
HALT: SJMPHALT
|
[
{
"code": null,
"e": 1257,
"s": 1062,
"text": "In this problem, we will see how to convert 8-bit BCD number to its Binary (Hexadecimal)equivalent. The BCD number is stored at location 20H. After converting, the results will be stored at 30H."
},
{
"code": null,
"e": 1354,
"s": 1257,
"text": "So let us assume the data is D5H. The program converts the binary value ofD5H to BCD value 213D."
},
{
"code": null,
"e": 1898,
"s": 1354,
"text": " MOVR0,#20H; Initialize the address of the data\n MOVA,@R0;Get the data from an address, which is stored in R0\n MOVR2,A; Store the content of A into R2\n \n CLRA;Clear the content of A to 00H\n MOVR3,#00H\nLOOP: ADDA,#01H;increment A by 01H\n DAA; Decimal Adjust of the accumulator content\n INCR3; Increase R3 to keep track of the hex value\n CJNEA,02H,LOOP ;Run the loop until A = R2\n\nMOVR0,#30H; Point the destination location\nMOVA,R3; Move R3 to A\nMOV@R0,A; Store A content to the memory location pointed by R0\nHALT: SJMPHALT"
},
{
"code": null,
"e": 2064,
"s": 1898,
"text": "Here the logic is very simple. We are just taking the number from the memory. And storing that value into R2. By this value, we can compare while executing the loop."
},
{
"code": null,
"e": 2761,
"s": 2064,
"text": "The accumulator (A) and register R3 is set to 00H at first. So we are just increasing the value of A by 01H. We can use the INC A instruction to increment the value, but in this case, the value is incremented by using ADDA, #01H. The reason behind it is the INCinstruction does not affect the CY and AC flags. But these flags are needed to use DA A instruction for decimal adjusting. After increasing the value of A, DA A instruction is executed to convert the value to decimal. By using this decimal value, we can compare with the number stored inR2. In each iteration the value of R3 is incremented by 1, this is acting like a counter. So at the end, we are getting the output from register R3."
},
{
"code": null,
"e": 3008,
"s": 2761,
"text": "We can do the same thing using some other logic also. Here no additional loops are needed to do the task. We are just multiplying the digit of 10th place of the BCD number with 0AH. Then adding the second digit with the result to get the number. "
},
{
"code": null,
"e": 3064,
"s": 3008,
"text": "If the number is 94, then it is multiplying 0AH with 9."
},
{
"code": null,
"e": 3121,
"s": 3064,
"text": "(9 * 0AH) = 5AH, thenadding 4 with 5AH. (5AH + 4) = 5EH."
},
{
"code": null,
"e": 3637,
"s": 3121,
"text": "MOVR0,#20H; Initialize the address of the data\nMOVA,@R0; Get the data from an address, which is stored in R0\nMOVR2,A;Store the content of A into R2\nSWAPA; Swap the nibbles of A register\nANLA,#0FH;Mask the Higher Nibble of A\nMOVB,0AH;Take 0AH = 10D into B\nMULAB ;Multiply A with B, and get result into A\nMOVA,R2;Copy R2 content to A\nANLA,#0FH;Mask the higher nibble of A\nADDA,R2\nMOVR0,#30H;Point the destination location\nMOVA,R3;Move R3 to A\nMOV@R0,A;Store A content to memory location pointed by R0\nHALT: SJMPHALT"
}
] |
std::bad_array_new_length class in C++ with Examples
|
28 May, 2020
Standard C++ contains several built-in exception classes, std::bad_array_new_length is one of them.It is an exception on bad array length and thrown if the size of array is less than zero and if the array size is greater than the limit. Below is the syntax for the same:
Header File:
<new>
Syntax:
class bad_array_new_length;
Return: The std::bad_array_new returns a null terminated character that is used to identify the exception.
Note: To make use of std::bad_array_new, one should set up the appropriate try and catch blocks.
Below are the Programs to understand the implementation of std::bad_array_new in a better way:
Program 1:
// C++ code for std::bad_array_new_length#include <bits/stdc++.h> using namespace std; // main methodint main(){ int a = -1; int b = 1; int c = INT_MAX; // try block try { new int[a]; new int[b]{ 1, 2, 3, 4 }; new int[50000000]; } // catch block to handle the errors catch (const bad_array_new_length& gfg) { cout << gfg.what() << endl; } return 0;}
std::bad_array_new_length
Program 2:
// C++ code for std::bad_array_new_length#include <bits/stdc++.h> using namespace std; // main methodint main(){ int a = -1; int b = 1; int c = INT_MAX; // try block try { new int[a]; new int[b]{ 11, 25, 56, 27 }; new int[1000000]; } // catch block to handle the errors catch (const bad_array_new_length& gfg) { cout << gfg.what() << endl; } return 0;}
std::bad_array_new_length
Reference: http://www.cplusplus.com/reference/new/bad_array_new_length/
CPP-Functions
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 May, 2020"
},
{
"code": null,
"e": 299,
"s": 28,
"text": "Standard C++ contains several built-in exception classes, std::bad_array_new_length is one of them.It is an exception on bad array length and thrown if the size of array is less than zero and if the array size is greater than the limit. Below is the syntax for the same:"
},
{
"code": null,
"e": 312,
"s": 299,
"text": "Header File:"
},
{
"code": null,
"e": 319,
"s": 312,
"text": "<new>\n"
},
{
"code": null,
"e": 327,
"s": 319,
"text": "Syntax:"
},
{
"code": null,
"e": 356,
"s": 327,
"text": "class bad_array_new_length;\n"
},
{
"code": null,
"e": 463,
"s": 356,
"text": "Return: The std::bad_array_new returns a null terminated character that is used to identify the exception."
},
{
"code": null,
"e": 560,
"s": 463,
"text": "Note: To make use of std::bad_array_new, one should set up the appropriate try and catch blocks."
},
{
"code": null,
"e": 655,
"s": 560,
"text": "Below are the Programs to understand the implementation of std::bad_array_new in a better way:"
},
{
"code": null,
"e": 666,
"s": 655,
"text": "Program 1:"
},
{
"code": "// C++ code for std::bad_array_new_length#include <bits/stdc++.h> using namespace std; // main methodint main(){ int a = -1; int b = 1; int c = INT_MAX; // try block try { new int[a]; new int[b]{ 1, 2, 3, 4 }; new int[50000000]; } // catch block to handle the errors catch (const bad_array_new_length& gfg) { cout << gfg.what() << endl; } return 0;}",
"e": 1133,
"s": 666,
"text": null
},
{
"code": null,
"e": 1160,
"s": 1133,
"text": "std::bad_array_new_length\n"
},
{
"code": null,
"e": 1171,
"s": 1160,
"text": "Program 2:"
},
{
"code": "// C++ code for std::bad_array_new_length#include <bits/stdc++.h> using namespace std; // main methodint main(){ int a = -1; int b = 1; int c = INT_MAX; // try block try { new int[a]; new int[b]{ 11, 25, 56, 27 }; new int[1000000]; } // catch block to handle the errors catch (const bad_array_new_length& gfg) { cout << gfg.what() << endl; } return 0;}",
"e": 1639,
"s": 1171,
"text": null
},
{
"code": null,
"e": 1666,
"s": 1639,
"text": "std::bad_array_new_length\n"
},
{
"code": null,
"e": 1738,
"s": 1666,
"text": "Reference: http://www.cplusplus.com/reference/new/bad_array_new_length/"
},
{
"code": null,
"e": 1752,
"s": 1738,
"text": "CPP-Functions"
},
{
"code": null,
"e": 1756,
"s": 1752,
"text": "C++"
},
{
"code": null,
"e": 1760,
"s": 1756,
"text": "CPP"
}
] |
starts_with() and ends_with() in C++20 with Examples
|
28 Jan, 2021
In this article, we will be discussing starts_with() and ends_with() with examples in C++20.
This function efficiently checks if a string begins with the given prefix or not. This function written in both std::basic_string and in std::basic_string_view.
Syntax:
template <typename PrefixType> bool starts_with(PrefixType prefix)
In the above syntax the prefix can be:
string
string view
single character or C-style string with null-terminated character
starts_with() with different types of Prefix:
bool starts_with(std::basic_string_view<Char T, Traits> x) const noexcept;bool starts_with(CharT x) const noexcept;bool starts_with(const CharT *x) const;
All the three overloaded forms of the function effectively return std::basic_string_view<Char T, Traits>(data(), size()).starts_with(x);
Parameters: It requires a single character sequence or a single character to compare to the start of the string.
Return Value: It returns the boolean true or false indication the following:
True: If string starts with the prefix.
False: If string does not start with the prefix.
Program 1:
Below program to demonstrates the concept of starts_with() in C++:
C++
// C++ program to illustrate the use// of starts_with()#include <iostream>#include <string>#include <string_view>using namespace std; // Function template to check if the// given string starts with the given// prefix or nottemplate <typename PrefixType>void if_prefix(const std::string& str, PrefixType prefix){ cout << "'" << str << "' starts with '" << prefix << "': " << str.starts_with(prefix) << endl;} // Driver Codeint main(){ string str = { "geeksforgeeks" }; if_prefix(str, string("geek")); // prefix is string if_prefix(str, string_view("geek")); // prefix is string view if_prefix(str, 'g'); // prefix is single character if_prefix(str, "geek\0"); // prefix is C-style string if_prefix(str, string("for")); if_prefix(str, string("Geek")); if_prefix(str, 'x'); return 0;}
Output:
This function efficiently checks if a string ends with the given suffix or not. This function written in both std::basic_string and in std::basic_string_view.
Syntax:
template <typename SuffixType> bool starts_with(SuffixType suffix)
In the above syntax the suffix can be:
string
string view
single character or C-style string with null-terminated character.
ends with() different types of Suffix:
constexpr bool ends_with(std::basic_string_view<Char T, Traits> sv) const noexcept;|constexpr boll ends_with(CharT c) const noexcept;constexpr bool ends_with(const CharT* s) const;
All the three overloaded forms of the function effectively return std::basic_string_view<Char T, Traits>(data(), size()).ends_with(x);
Parameters: It requires a single character sequence or a single character to compare to the end of the string.
Return Value: It returns the boolean true or false indicating the following:
True: If string ends with the suffix.
False: If string does not end with the suffix.
Program 2:
Below program to demonstrates the concept of ends_with() in C++:
C++
// C++ program to illustrate the use// of ends_with()#include <iostream>#include <string>#include <string_view>using namespace std; // Function template to check if the// given string ends_with given stringtemplate <typename SuffixType>void if_suffix(const std::string& str, SuffixType suffix){ cout << "'" << str << "' ends with '" << suffix << "': " << str.ends_with(suffix) << std::endl;} // Driver Codeint main(){ string str = { "geeksforgeeks" }; if_suffix(str, string("geeks")); // suffix is string if_suffix(str, string_view("geeks")); // suffix is string view if_suffix(str, 's'); // suffix is single character if_suffix(str, "geeks\0"); // suffix is C-style string if_suffix(str, string("for")); if_suffix(str, string("Geeks")); if_suffix(str, 'x'); if_suffix(str, '\0');}
Output:
C++
C++ Programs
Strings
Strings
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n28 Jan, 2021"
},
{
"code": null,
"e": 146,
"s": 53,
"text": "In this article, we will be discussing starts_with() and ends_with() with examples in C++20."
},
{
"code": null,
"e": 308,
"s": 146,
"text": "This function efficiently checks if a string begins with the given prefix or not. This function written in both std::basic_string and in std::basic_string_view. "
},
{
"code": null,
"e": 316,
"s": 308,
"text": "Syntax:"
},
{
"code": null,
"e": 383,
"s": 316,
"text": "template <typename PrefixType> bool starts_with(PrefixType prefix)"
},
{
"code": null,
"e": 422,
"s": 383,
"text": "In the above syntax the prefix can be:"
},
{
"code": null,
"e": 429,
"s": 422,
"text": "string"
},
{
"code": null,
"e": 441,
"s": 429,
"text": "string view"
},
{
"code": null,
"e": 507,
"s": 441,
"text": "single character or C-style string with null-terminated character"
},
{
"code": null,
"e": 553,
"s": 507,
"text": "starts_with() with different types of Prefix:"
},
{
"code": null,
"e": 708,
"s": 553,
"text": "bool starts_with(std::basic_string_view<Char T, Traits> x) const noexcept;bool starts_with(CharT x) const noexcept;bool starts_with(const CharT *x) const;"
},
{
"code": null,
"e": 846,
"s": 708,
"text": "All the three overloaded forms of the function effectively return std::basic_string_view<Char T, Traits>(data(), size()).starts_with(x);"
},
{
"code": null,
"e": 959,
"s": 846,
"text": "Parameters: It requires a single character sequence or a single character to compare to the start of the string."
},
{
"code": null,
"e": 1036,
"s": 959,
"text": "Return Value: It returns the boolean true or false indication the following:"
},
{
"code": null,
"e": 1076,
"s": 1036,
"text": "True: If string starts with the prefix."
},
{
"code": null,
"e": 1125,
"s": 1076,
"text": "False: If string does not start with the prefix."
},
{
"code": null,
"e": 1136,
"s": 1125,
"text": "Program 1:"
},
{
"code": null,
"e": 1203,
"s": 1136,
"text": "Below program to demonstrates the concept of starts_with() in C++:"
},
{
"code": null,
"e": 1207,
"s": 1203,
"text": "C++"
},
{
"code": "// C++ program to illustrate the use// of starts_with()#include <iostream>#include <string>#include <string_view>using namespace std; // Function template to check if the// given string starts with the given// prefix or nottemplate <typename PrefixType>void if_prefix(const std::string& str, PrefixType prefix){ cout << \"'\" << str << \"' starts with '\" << prefix << \"': \" << str.starts_with(prefix) << endl;} // Driver Codeint main(){ string str = { \"geeksforgeeks\" }; if_prefix(str, string(\"geek\")); // prefix is string if_prefix(str, string_view(\"geek\")); // prefix is string view if_prefix(str, 'g'); // prefix is single character if_prefix(str, \"geek\\0\"); // prefix is C-style string if_prefix(str, string(\"for\")); if_prefix(str, string(\"Geek\")); if_prefix(str, 'x'); return 0;}",
"e": 2087,
"s": 1207,
"text": null
},
{
"code": null,
"e": 2095,
"s": 2087,
"text": "Output:"
},
{
"code": null,
"e": 2254,
"s": 2095,
"text": "This function efficiently checks if a string ends with the given suffix or not. This function written in both std::basic_string and in std::basic_string_view."
},
{
"code": null,
"e": 2262,
"s": 2254,
"text": "Syntax:"
},
{
"code": null,
"e": 2329,
"s": 2262,
"text": "template <typename SuffixType> bool starts_with(SuffixType suffix)"
},
{
"code": null,
"e": 2368,
"s": 2329,
"text": "In the above syntax the suffix can be:"
},
{
"code": null,
"e": 2375,
"s": 2368,
"text": "string"
},
{
"code": null,
"e": 2387,
"s": 2375,
"text": "string view"
},
{
"code": null,
"e": 2454,
"s": 2387,
"text": "single character or C-style string with null-terminated character."
},
{
"code": null,
"e": 2493,
"s": 2454,
"text": "ends with() different types of Suffix:"
},
{
"code": null,
"e": 2674,
"s": 2493,
"text": "constexpr bool ends_with(std::basic_string_view<Char T, Traits> sv) const noexcept;|constexpr boll ends_with(CharT c) const noexcept;constexpr bool ends_with(const CharT* s) const;"
},
{
"code": null,
"e": 2810,
"s": 2674,
"text": "All the three overloaded forms of the function effectively return std::basic_string_view<Char T, Traits>(data(), size()).ends_with(x);"
},
{
"code": null,
"e": 2921,
"s": 2810,
"text": "Parameters: It requires a single character sequence or a single character to compare to the end of the string."
},
{
"code": null,
"e": 2998,
"s": 2921,
"text": "Return Value: It returns the boolean true or false indicating the following:"
},
{
"code": null,
"e": 3036,
"s": 2998,
"text": "True: If string ends with the suffix."
},
{
"code": null,
"e": 3083,
"s": 3036,
"text": "False: If string does not end with the suffix."
},
{
"code": null,
"e": 3094,
"s": 3083,
"text": "Program 2:"
},
{
"code": null,
"e": 3159,
"s": 3094,
"text": "Below program to demonstrates the concept of ends_with() in C++:"
},
{
"code": null,
"e": 3163,
"s": 3159,
"text": "C++"
},
{
"code": "// C++ program to illustrate the use// of ends_with()#include <iostream>#include <string>#include <string_view>using namespace std; // Function template to check if the// given string ends_with given stringtemplate <typename SuffixType>void if_suffix(const std::string& str, SuffixType suffix){ cout << \"'\" << str << \"' ends with '\" << suffix << \"': \" << str.ends_with(suffix) << std::endl;} // Driver Codeint main(){ string str = { \"geeksforgeeks\" }; if_suffix(str, string(\"geeks\")); // suffix is string if_suffix(str, string_view(\"geeks\")); // suffix is string view if_suffix(str, 's'); // suffix is single character if_suffix(str, \"geeks\\0\"); // suffix is C-style string if_suffix(str, string(\"for\")); if_suffix(str, string(\"Geeks\")); if_suffix(str, 'x'); if_suffix(str, '\\0');}",
"e": 4032,
"s": 3163,
"text": null
},
{
"code": null,
"e": 4040,
"s": 4032,
"text": "Output:"
},
{
"code": null,
"e": 4044,
"s": 4040,
"text": "C++"
},
{
"code": null,
"e": 4057,
"s": 4044,
"text": "C++ Programs"
},
{
"code": null,
"e": 4065,
"s": 4057,
"text": "Strings"
},
{
"code": null,
"e": 4073,
"s": 4065,
"text": "Strings"
},
{
"code": null,
"e": 4077,
"s": 4073,
"text": "CPP"
}
] |
Python program to find tuples which have all elements divisible by K from a list of tuples
|
05 Sep, 2020
Given a list of tuples. The task is to extract all tuples which have all elements divisible by K.
Input : test_list = [(6, 24, 12), (60, 12, 6), (12, 18, 21)], K = 6 Output : [(6, 24, 12), (60, 12, 6)] Explanation : Both tuples have all elements multiple of 6.
Input : test_list = [(6, 24, 12), (60, 10, 5), (12, 18, 21)], K = 5 Output : [(60, 10, 5)] Explanation : Multiple of 5 tuples extracted.
Method #1 : Using list comprehension + all()
In this, we test for all elements to be K multiple using all() for filtering purpose, and list comprehension is used for iteration of all tuples.
Python3
# Python3 code to demonstrate working of# K Multiple Elements Tuples# Using list comprehension + all() # initializing listtest_list = [(6, 24, 12), (7, 9, 6), (12, 18, 21)] # printing original listprint("The original list is : " + str(test_list)) # initializing KK = 6 # all() used to filter elementsres = [sub for sub in test_list if all(ele % K == 0 for ele in sub)] # printing resultprint("K Multiple elements tuples : " + str(res))
The original list is : [(6, 24, 12), (7, 9, 6), (12, 18, 21)]
K Multiple elements tuples : [(6, 24, 12)]
Method #2 : Using filter() + lambda + all()
In this, we perform task of filtering using filter() + lambda, and logic provided by all(), as in above method.
Python3
# Python3 code to demonstrate working of# K Multiple Elements Tuples# Using filter() + lambda + all() # initializing listtest_list = [(6, 24, 12), (7, 9, 6), (12, 18, 21)] # printing original listprint("The original list is : " + str(test_list)) # initializing KK = 6 # filter() + lambda for filter operationres = list(filter(lambda sub: all(ele % K == 0 for ele in sub), test_list)) # printing resultprint("K Multiple elements tuples : " + str(res))
The original list is : [(6, 24, 12), (7, 9, 6), (12, 18, 21)]
K Multiple elements tuples : [(6, 24, 12)]
Python List-of-Tuples
Python tuple-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Enumerate() in Python
Different ways to create Pandas Dataframe
Read a file line by line in Python
How to Install PIP on Windows ?
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n05 Sep, 2020"
},
{
"code": null,
"e": 126,
"s": 28,
"text": "Given a list of tuples. The task is to extract all tuples which have all elements divisible by K."
},
{
"code": null,
"e": 289,
"s": 126,
"text": "Input : test_list = [(6, 24, 12), (60, 12, 6), (12, 18, 21)], K = 6 Output : [(6, 24, 12), (60, 12, 6)] Explanation : Both tuples have all elements multiple of 6."
},
{
"code": null,
"e": 427,
"s": 289,
"text": "Input : test_list = [(6, 24, 12), (60, 10, 5), (12, 18, 21)], K = 5 Output : [(60, 10, 5)] Explanation : Multiple of 5 tuples extracted. "
},
{
"code": null,
"e": 472,
"s": 427,
"text": "Method #1 : Using list comprehension + all()"
},
{
"code": null,
"e": 618,
"s": 472,
"text": "In this, we test for all elements to be K multiple using all() for filtering purpose, and list comprehension is used for iteration of all tuples."
},
{
"code": null,
"e": 626,
"s": 618,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# K Multiple Elements Tuples# Using list comprehension + all() # initializing listtest_list = [(6, 24, 12), (7, 9, 6), (12, 18, 21)] # printing original listprint(\"The original list is : \" + str(test_list)) # initializing KK = 6 # all() used to filter elementsres = [sub for sub in test_list if all(ele % K == 0 for ele in sub)] # printing resultprint(\"K Multiple elements tuples : \" + str(res))",
"e": 1067,
"s": 626,
"text": null
},
{
"code": null,
"e": 1173,
"s": 1067,
"text": "The original list is : [(6, 24, 12), (7, 9, 6), (12, 18, 21)]\nK Multiple elements tuples : [(6, 24, 12)]\n"
},
{
"code": null,
"e": 1218,
"s": 1173,
"text": " Method #2 : Using filter() + lambda + all()"
},
{
"code": null,
"e": 1330,
"s": 1218,
"text": "In this, we perform task of filtering using filter() + lambda, and logic provided by all(), as in above method."
},
{
"code": null,
"e": 1338,
"s": 1330,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# K Multiple Elements Tuples# Using filter() + lambda + all() # initializing listtest_list = [(6, 24, 12), (7, 9, 6), (12, 18, 21)] # printing original listprint(\"The original list is : \" + str(test_list)) # initializing KK = 6 # filter() + lambda for filter operationres = list(filter(lambda sub: all(ele % K == 0 for ele in sub), test_list)) # printing resultprint(\"K Multiple elements tuples : \" + str(res))",
"e": 1794,
"s": 1338,
"text": null
},
{
"code": null,
"e": 1900,
"s": 1794,
"text": "The original list is : [(6, 24, 12), (7, 9, 6), (12, 18, 21)]\nK Multiple elements tuples : [(6, 24, 12)]\n"
},
{
"code": null,
"e": 1922,
"s": 1900,
"text": "Python List-of-Tuples"
},
{
"code": null,
"e": 1944,
"s": 1922,
"text": "Python tuple-programs"
},
{
"code": null,
"e": 1951,
"s": 1944,
"text": "Python"
},
{
"code": null,
"e": 1967,
"s": 1951,
"text": "Python Programs"
},
{
"code": null,
"e": 2065,
"s": 1967,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2083,
"s": 2065,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2105,
"s": 2083,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2147,
"s": 2105,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2182,
"s": 2147,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2214,
"s": 2182,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2257,
"s": 2214,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 2279,
"s": 2257,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2318,
"s": 2279,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2356,
"s": 2318,
"text": "Python | Convert a list to dictionary"
}
] |
std::uniform_real_ distribution class in C++ with Examples
|
15 Jul, 2021
In Probability, Uniform Distribution Function refers to the distribution in which the probabilities are defined on a continuous random variable, one which can take any value between two numbers, then the distribution is said to be a continuous probability distribution. For example, the temperature throughout a given day can be represented by a continuous random variable and the corresponding probability distribution is said to be continuous.
C++ have introduced uniform_real_distribution class in the random library whose member function give random real numbers or continuous values from a given input range with uniform probability.Public member functions in uniform_real_distribution class:
operator(): This function returns a random value from the range given. The datatype of the return value is specified during initialization of the template class. The probability for any value is same. The time complexity for this operation is O(1).Example: CPPCPP// C++ code to demonstrate the working of// operator() function #include <iostream> // for uniform_real_distribution function#include <random> using namespace std; int main(){ // Here default_random_engine object // is used as source of randomness // We can give seed also to default_random_engine // if psuedorandom numbers are required default_random_engine generator; double a = 0.0, b = 1.0; // Initializing of uniform_real_distribution class uniform_real_distribution<double> distribution(a, b); // number of experiments const int num_of_exp = 10000000; // number of ranges int n = 100; int p[n] = {}; for (int i = 0; i < num_of_exp; ++i) { // using operator() function // to give random values double number = distribution(generator); ++p[int(number * n)]; } cout << "Probability of some ranges" << endl; // Displaying the probability of some ranges // after generating values 10000 times. cout << "0.50-0.51" << " " << (float)p[50] / (float)num_of_exp << endl; cout << "0.60-0.61" << " " << (float)p[60] / (float)num_of_exp << endl; cout << "0.45-0.46" << " " << (float)p[45] / (float)num_of_exp << endl; return 0;}Output:Probability of some ranges
0.50-0.51 0.0099808
0.60-0.61 0.0099719
0.45-0.46 0.009999
operator(): This function returns a random value from the range given. The datatype of the return value is specified during initialization of the template class. The probability for any value is same. The time complexity for this operation is O(1).Example: CPPCPP// C++ code to demonstrate the working of// operator() function #include <iostream> // for uniform_real_distribution function#include <random> using namespace std; int main(){ // Here default_random_engine object // is used as source of randomness // We can give seed also to default_random_engine // if psuedorandom numbers are required default_random_engine generator; double a = 0.0, b = 1.0; // Initializing of uniform_real_distribution class uniform_real_distribution<double> distribution(a, b); // number of experiments const int num_of_exp = 10000000; // number of ranges int n = 100; int p[n] = {}; for (int i = 0; i < num_of_exp; ++i) { // using operator() function // to give random values double number = distribution(generator); ++p[int(number * n)]; } cout << "Probability of some ranges" << endl; // Displaying the probability of some ranges // after generating values 10000 times. cout << "0.50-0.51" << " " << (float)p[50] / (float)num_of_exp << endl; cout << "0.60-0.61" << " " << (float)p[60] / (float)num_of_exp << endl; cout << "0.45-0.46" << " " << (float)p[45] / (float)num_of_exp << endl; return 0;}Output:Probability of some ranges
0.50-0.51 0.0099808
0.60-0.61 0.0099719
0.45-0.46 0.009999
CPP
// C++ code to demonstrate the working of// operator() function #include <iostream> // for uniform_real_distribution function#include <random> using namespace std; int main(){ // Here default_random_engine object // is used as source of randomness // We can give seed also to default_random_engine // if psuedorandom numbers are required default_random_engine generator; double a = 0.0, b = 1.0; // Initializing of uniform_real_distribution class uniform_real_distribution<double> distribution(a, b); // number of experiments const int num_of_exp = 10000000; // number of ranges int n = 100; int p[n] = {}; for (int i = 0; i < num_of_exp; ++i) { // using operator() function // to give random values double number = distribution(generator); ++p[int(number * n)]; } cout << "Probability of some ranges" << endl; // Displaying the probability of some ranges // after generating values 10000 times. cout << "0.50-0.51" << " " << (float)p[50] / (float)num_of_exp << endl; cout << "0.60-0.61" << " " << (float)p[60] / (float)num_of_exp << endl; cout << "0.45-0.46" << " " << (float)p[45] / (float)num_of_exp << endl; return 0;}
Probability of some ranges
0.50-0.51 0.0099808
0.60-0.61 0.0099719
0.45-0.46 0.009999
The probability of all ranges are almost equal.
a(): Returns lower bound of range.
b(): Returns upper bound of range.
min(): Returns minimum value the function can return. For uniform distribution min() and a() return same value.
max(): Returns minimum value the function can return. For uniform distribution min() and a() return same value.
reset(): This function resets the distribution such that the next random values generated are not based on the previous values.
Example:
CPP
// C++ code to demonstrate the working of// a(), b(), min(), max(), reset() function #include <iostream> // for uniform_real_distribution function#include <random> using namespace std; int main(){ double a = 0, b = 1.5; // Initializing of uniform_real_distribution class uniform_real_distribution<double> distribution(a, b); // Using a() and b() cout << "Lower Bound" << " " << distribution.a() << endl; cout << "Upper Bound" << " " << distribution.b() << endl; // Using min() and max() cout << "Minimum possible output" << " " << distribution.min() << endl; cout << "Maximum possible output" << " " << distribution.max() << endl; // Using reset function distribution.reset(); return 0;}
Lower Bound 0
Upper Bound 1.5
Minimum possible output 0
Maximum possible output 1.5
Reference: http://www.cplusplus.com/reference/random/uniform_real_distribution/
nidhi_biet
abhishek0719kadiyan
cpp-class
cpp-random
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n15 Jul, 2021"
},
{
"code": null,
"e": 474,
"s": 28,
"text": "In Probability, Uniform Distribution Function refers to the distribution in which the probabilities are defined on a continuous random variable, one which can take any value between two numbers, then the distribution is said to be a continuous probability distribution. For example, the temperature throughout a given day can be represented by a continuous random variable and the corresponding probability distribution is said to be continuous."
},
{
"code": null,
"e": 733,
"s": 479,
"text": "C++ have introduced uniform_real_distribution class in the random library whose member function give random real numbers or continuous values from a given input range with uniform probability.Public member functions in uniform_real_distribution class: "
},
{
"code": null,
"e": 2343,
"s": 733,
"text": "operator(): This function returns a random value from the range given. The datatype of the return value is specified during initialization of the template class. The probability for any value is same. The time complexity for this operation is O(1).Example: CPPCPP// C++ code to demonstrate the working of// operator() function #include <iostream> // for uniform_real_distribution function#include <random> using namespace std; int main(){ // Here default_random_engine object // is used as source of randomness // We can give seed also to default_random_engine // if psuedorandom numbers are required default_random_engine generator; double a = 0.0, b = 1.0; // Initializing of uniform_real_distribution class uniform_real_distribution<double> distribution(a, b); // number of experiments const int num_of_exp = 10000000; // number of ranges int n = 100; int p[n] = {}; for (int i = 0; i < num_of_exp; ++i) { // using operator() function // to give random values double number = distribution(generator); ++p[int(number * n)]; } cout << \"Probability of some ranges\" << endl; // Displaying the probability of some ranges // after generating values 10000 times. cout << \"0.50-0.51\" << \" \" << (float)p[50] / (float)num_of_exp << endl; cout << \"0.60-0.61\" << \" \" << (float)p[60] / (float)num_of_exp << endl; cout << \"0.45-0.46\" << \" \" << (float)p[45] / (float)num_of_exp << endl; return 0;}Output:Probability of some ranges\n0.50-0.51 0.0099808\n0.60-0.61 0.0099719\n0.45-0.46 0.009999"
},
{
"code": null,
"e": 3953,
"s": 2343,
"text": "operator(): This function returns a random value from the range given. The datatype of the return value is specified during initialization of the template class. The probability for any value is same. The time complexity for this operation is O(1).Example: CPPCPP// C++ code to demonstrate the working of// operator() function #include <iostream> // for uniform_real_distribution function#include <random> using namespace std; int main(){ // Here default_random_engine object // is used as source of randomness // We can give seed also to default_random_engine // if psuedorandom numbers are required default_random_engine generator; double a = 0.0, b = 1.0; // Initializing of uniform_real_distribution class uniform_real_distribution<double> distribution(a, b); // number of experiments const int num_of_exp = 10000000; // number of ranges int n = 100; int p[n] = {}; for (int i = 0; i < num_of_exp; ++i) { // using operator() function // to give random values double number = distribution(generator); ++p[int(number * n)]; } cout << \"Probability of some ranges\" << endl; // Displaying the probability of some ranges // after generating values 10000 times. cout << \"0.50-0.51\" << \" \" << (float)p[50] / (float)num_of_exp << endl; cout << \"0.60-0.61\" << \" \" << (float)p[60] / (float)num_of_exp << endl; cout << \"0.45-0.46\" << \" \" << (float)p[45] / (float)num_of_exp << endl; return 0;}Output:Probability of some ranges\n0.50-0.51 0.0099808\n0.60-0.61 0.0099719\n0.45-0.46 0.009999"
},
{
"code": null,
"e": 3957,
"s": 3953,
"text": "CPP"
},
{
"code": "// C++ code to demonstrate the working of// operator() function #include <iostream> // for uniform_real_distribution function#include <random> using namespace std; int main(){ // Here default_random_engine object // is used as source of randomness // We can give seed also to default_random_engine // if psuedorandom numbers are required default_random_engine generator; double a = 0.0, b = 1.0; // Initializing of uniform_real_distribution class uniform_real_distribution<double> distribution(a, b); // number of experiments const int num_of_exp = 10000000; // number of ranges int n = 100; int p[n] = {}; for (int i = 0; i < num_of_exp; ++i) { // using operator() function // to give random values double number = distribution(generator); ++p[int(number * n)]; } cout << \"Probability of some ranges\" << endl; // Displaying the probability of some ranges // after generating values 10000 times. cout << \"0.50-0.51\" << \" \" << (float)p[50] / (float)num_of_exp << endl; cout << \"0.60-0.61\" << \" \" << (float)p[60] / (float)num_of_exp << endl; cout << \"0.45-0.46\" << \" \" << (float)p[45] / (float)num_of_exp << endl; return 0;}",
"e": 5212,
"s": 3957,
"text": null
},
{
"code": null,
"e": 5298,
"s": 5212,
"text": "Probability of some ranges\n0.50-0.51 0.0099808\n0.60-0.61 0.0099719\n0.45-0.46 0.009999"
},
{
"code": null,
"e": 5346,
"s": 5298,
"text": "The probability of all ranges are almost equal."
},
{
"code": null,
"e": 5383,
"s": 5346,
"text": "a(): Returns lower bound of range. "
},
{
"code": null,
"e": 5420,
"s": 5383,
"text": "b(): Returns upper bound of range. "
},
{
"code": null,
"e": 5534,
"s": 5420,
"text": "min(): Returns minimum value the function can return. For uniform distribution min() and a() return same value. "
},
{
"code": null,
"e": 5648,
"s": 5534,
"text": "max(): Returns minimum value the function can return. For uniform distribution min() and a() return same value. "
},
{
"code": null,
"e": 5778,
"s": 5648,
"text": "reset(): This function resets the distribution such that the next random values generated are not based on the previous values. "
},
{
"code": null,
"e": 5789,
"s": 5778,
"text": "Example: "
},
{
"code": null,
"e": 5793,
"s": 5789,
"text": "CPP"
},
{
"code": "// C++ code to demonstrate the working of// a(), b(), min(), max(), reset() function #include <iostream> // for uniform_real_distribution function#include <random> using namespace std; int main(){ double a = 0, b = 1.5; // Initializing of uniform_real_distribution class uniform_real_distribution<double> distribution(a, b); // Using a() and b() cout << \"Lower Bound\" << \" \" << distribution.a() << endl; cout << \"Upper Bound\" << \" \" << distribution.b() << endl; // Using min() and max() cout << \"Minimum possible output\" << \" \" << distribution.min() << endl; cout << \"Maximum possible output\" << \" \" << distribution.max() << endl; // Using reset function distribution.reset(); return 0;}",
"e": 6563,
"s": 5793,
"text": null
},
{
"code": null,
"e": 6647,
"s": 6563,
"text": "Lower Bound 0\nUpper Bound 1.5\nMinimum possible output 0\nMaximum possible output 1.5"
},
{
"code": null,
"e": 6730,
"s": 6649,
"text": "Reference: http://www.cplusplus.com/reference/random/uniform_real_distribution/ "
},
{
"code": null,
"e": 6741,
"s": 6730,
"text": "nidhi_biet"
},
{
"code": null,
"e": 6761,
"s": 6741,
"text": "abhishek0719kadiyan"
},
{
"code": null,
"e": 6771,
"s": 6761,
"text": "cpp-class"
},
{
"code": null,
"e": 6782,
"s": 6771,
"text": "cpp-random"
},
{
"code": null,
"e": 6786,
"s": 6782,
"text": "C++"
},
{
"code": null,
"e": 6790,
"s": 6786,
"text": "CPP"
}
] |
TreeMap ceilingKey() in Java with Examples - GeeksforGeeks
|
18 Sep, 2018
The ceilingKey() function of TreeMap Class returns the least key greater than or equal to the given key or null if the such a key is absent.
Syntax:
public K ceilingKey(K key)
Parameters: This method accepts a mandatory parameter key which is the key to be searched for.
Return Value: This method returns the least key which is greater than or equal to the given key value.If such a key is absent, null is returned.
Exceptions: This method throws following exceptions:
ClassCastException – Thrown if the specified key can’t be compared with the given key values.
NullPointerException – Thrown if the given key is null and the map uses natural ordering or the comparator does not permit null values.
Below are the examples to illustrate ceilingKey() method:
Program 1: To demonstrate use of ceilingKey() method for a TreeMap with comparator
import java.util.*; public class Main { public static void main(String[] args) { // creating tree map NavigableMap<Integer, String> treemap = new TreeMap<Integer, String>((a, b) -> ((a > b) ? 1 : ((a == b) ? 0 : -1))); // populating tree map treemap.put(1, " A "); treemap.put(2, " B "); treemap.put(3, " C "); treemap.put(4, " D "); treemap.put(6, " E "); try { System.out.println("Ceiling key entry for 5: " + treemap.ceilingKey(5)); } catch (Exception e) { System.out.println("Exception: " + e); } }}
Ceiling key entry for 5: 6
Program 2: To demonstrate use of ceilingKey() method for a TreeMap without any comparator
import java.util.*; public class Main { public static void main(String[] args) { // creating tree map NavigableMap<Integer, String> treemap = new TreeMap<Integer, String>(); // populating tree map treemap.put(1, " A "); treemap.put(2, " B "); treemap.put(3, " C "); treemap.put(4, " D "); treemap.put(6, " E "); treemap.put(7, " F "); // Since 6 is the least value greater than 5, // it is returned as the key. System.out.println("Ceiling key entry for 5: " + treemap.ceilingKey(5)); }}
Ceiling key entry for 5: 6
Program 3: To demonstrate use of ceilingKey() method when it will return null
import java.util.*; public class Main { public static void main(String[] args) { // creating tree map NavigableMap<Integer, String> treemap = new TreeMap<Integer, String>(); // populating tree map treemap.put(1, " A "); treemap.put(2, " B "); treemap.put(3, " C "); treemap.put(4, " E "); treemap.put(5, " D "); // Since 10 is not present in the Map // and neither any Key is present greater than 10 // Hence this will return null System.out.println("Ceiling key entry for 10: " + treemap.ceilingKey(10)); }}
Ceiling key entry for 10: null
Program 4: To show NullPointerException
import java.util.*; public class Main { public static void main(String[] args) { // creating tree map TreeMap<Integer, String> treemap = new TreeMap<Integer, String>(); // populating tree map treemap.put(2, " two "); treemap.put(1, " one "); treemap.put(3, " three "); treemap.put(6, " six "); treemap.put(5, " five "); try { // returns a NullPointerException // as key value can't be null // because of natural ordering System.out.println("Ceiling key entry for null value : " + treemap.ceilingKey(null)); } catch (Exception e) { System.out.println("Exception: " + e); } }}
Exception: java.lang.NullPointerException
Program 5: To demonstrate ClassCastException
import java.util.*; public class Main { public static void main(String[] args) { // creating tree map NavigableMap<Object, String> treemap = new TreeMap<Object, String>(); // populating tree map treemap.put(1, " A "); treemap.put(2, " B "); treemap.put(3, " C "); treemap.put(4, " E "); treemap.put(5, " D "); try { // returns ClassCastException // as we cannot compare a String object with an Integer object System.out.println("Ceiling key entry for \"asd\": " + treemap.ceilingKey(new String("asd"))); } catch (Exception e) { System.out.println("Exception: " + e); } }}
Exception: java.lang.ClassCastException:
java.lang.Integer cannot be cast to java.lang.String
Java - util package
Java-Functions
Picked
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
HashMap in Java with Examples
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
Collections in Java
Set in Java
|
[
{
"code": null,
"e": 24442,
"s": 24414,
"text": "\n18 Sep, 2018"
},
{
"code": null,
"e": 24583,
"s": 24442,
"text": "The ceilingKey() function of TreeMap Class returns the least key greater than or equal to the given key or null if the such a key is absent."
},
{
"code": null,
"e": 24591,
"s": 24583,
"text": "Syntax:"
},
{
"code": null,
"e": 24618,
"s": 24591,
"text": "public K ceilingKey(K key)"
},
{
"code": null,
"e": 24713,
"s": 24618,
"text": "Parameters: This method accepts a mandatory parameter key which is the key to be searched for."
},
{
"code": null,
"e": 24858,
"s": 24713,
"text": "Return Value: This method returns the least key which is greater than or equal to the given key value.If such a key is absent, null is returned."
},
{
"code": null,
"e": 24911,
"s": 24858,
"text": "Exceptions: This method throws following exceptions:"
},
{
"code": null,
"e": 25005,
"s": 24911,
"text": "ClassCastException – Thrown if the specified key can’t be compared with the given key values."
},
{
"code": null,
"e": 25141,
"s": 25005,
"text": "NullPointerException – Thrown if the given key is null and the map uses natural ordering or the comparator does not permit null values."
},
{
"code": null,
"e": 25199,
"s": 25141,
"text": "Below are the examples to illustrate ceilingKey() method:"
},
{
"code": null,
"e": 25282,
"s": 25199,
"text": "Program 1: To demonstrate use of ceilingKey() method for a TreeMap with comparator"
},
{
"code": "import java.util.*; public class Main { public static void main(String[] args) { // creating tree map NavigableMap<Integer, String> treemap = new TreeMap<Integer, String>((a, b) -> ((a > b) ? 1 : ((a == b) ? 0 : -1))); // populating tree map treemap.put(1, \" A \"); treemap.put(2, \" B \"); treemap.put(3, \" C \"); treemap.put(4, \" D \"); treemap.put(6, \" E \"); try { System.out.println(\"Ceiling key entry for 5: \" + treemap.ceilingKey(5)); } catch (Exception e) { System.out.println(\"Exception: \" + e); } }}",
"e": 26251,
"s": 25282,
"text": null
},
{
"code": null,
"e": 26279,
"s": 26251,
"text": "Ceiling key entry for 5: 6\n"
},
{
"code": null,
"e": 26369,
"s": 26279,
"text": "Program 2: To demonstrate use of ceilingKey() method for a TreeMap without any comparator"
},
{
"code": "import java.util.*; public class Main { public static void main(String[] args) { // creating tree map NavigableMap<Integer, String> treemap = new TreeMap<Integer, String>(); // populating tree map treemap.put(1, \" A \"); treemap.put(2, \" B \"); treemap.put(3, \" C \"); treemap.put(4, \" D \"); treemap.put(6, \" E \"); treemap.put(7, \" F \"); // Since 6 is the least value greater than 5, // it is returned as the key. System.out.println(\"Ceiling key entry for 5: \" + treemap.ceilingKey(5)); }}",
"e": 26993,
"s": 26369,
"text": null
},
{
"code": null,
"e": 27021,
"s": 26993,
"text": "Ceiling key entry for 5: 6\n"
},
{
"code": null,
"e": 27099,
"s": 27021,
"text": "Program 3: To demonstrate use of ceilingKey() method when it will return null"
},
{
"code": "import java.util.*; public class Main { public static void main(String[] args) { // creating tree map NavigableMap<Integer, String> treemap = new TreeMap<Integer, String>(); // populating tree map treemap.put(1, \" A \"); treemap.put(2, \" B \"); treemap.put(3, \" C \"); treemap.put(4, \" E \"); treemap.put(5, \" D \"); // Since 10 is not present in the Map // and neither any Key is present greater than 10 // Hence this will return null System.out.println(\"Ceiling key entry for 10: \" + treemap.ceilingKey(10)); }}",
"e": 27745,
"s": 27099,
"text": null
},
{
"code": null,
"e": 27777,
"s": 27745,
"text": "Ceiling key entry for 10: null\n"
},
{
"code": null,
"e": 27817,
"s": 27777,
"text": "Program 4: To show NullPointerException"
},
{
"code": "import java.util.*; public class Main { public static void main(String[] args) { // creating tree map TreeMap<Integer, String> treemap = new TreeMap<Integer, String>(); // populating tree map treemap.put(2, \" two \"); treemap.put(1, \" one \"); treemap.put(3, \" three \"); treemap.put(6, \" six \"); treemap.put(5, \" five \"); try { // returns a NullPointerException // as key value can't be null // because of natural ordering System.out.println(\"Ceiling key entry for null value : \" + treemap.ceilingKey(null)); } catch (Exception e) { System.out.println(\"Exception: \" + e); } }}",
"e": 28588,
"s": 27817,
"text": null
},
{
"code": null,
"e": 28631,
"s": 28588,
"text": "Exception: java.lang.NullPointerException\n"
},
{
"code": null,
"e": 28676,
"s": 28631,
"text": "Program 5: To demonstrate ClassCastException"
},
{
"code": "import java.util.*; public class Main { public static void main(String[] args) { // creating tree map NavigableMap<Object, String> treemap = new TreeMap<Object, String>(); // populating tree map treemap.put(1, \" A \"); treemap.put(2, \" B \"); treemap.put(3, \" C \"); treemap.put(4, \" E \"); treemap.put(5, \" D \"); try { // returns ClassCastException // as we cannot compare a String object with an Integer object System.out.println(\"Ceiling key entry for \\\"asd\\\": \" + treemap.ceilingKey(new String(\"asd\"))); } catch (Exception e) { System.out.println(\"Exception: \" + e); } }}",
"e": 29433,
"s": 28676,
"text": null
},
{
"code": null,
"e": 29540,
"s": 29433,
"text": "Exception: java.lang.ClassCastException: \n java.lang.Integer cannot be cast to java.lang.String\n"
},
{
"code": null,
"e": 29560,
"s": 29540,
"text": "Java - util package"
},
{
"code": null,
"e": 29575,
"s": 29560,
"text": "Java-Functions"
},
{
"code": null,
"e": 29582,
"s": 29575,
"text": "Picked"
},
{
"code": null,
"e": 29587,
"s": 29582,
"text": "Java"
},
{
"code": null,
"e": 29592,
"s": 29587,
"text": "Java"
},
{
"code": null,
"e": 29690,
"s": 29592,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29699,
"s": 29690,
"text": "Comments"
},
{
"code": null,
"e": 29712,
"s": 29699,
"text": "Old Comments"
},
{
"code": null,
"e": 29742,
"s": 29712,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 29761,
"s": 29742,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 29793,
"s": 29761,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 29811,
"s": 29793,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 29831,
"s": 29811,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 29863,
"s": 29831,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 29887,
"s": 29863,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 29906,
"s": 29887,
"text": "LinkedList in Java"
},
{
"code": null,
"e": 29926,
"s": 29906,
"text": "Collections in Java"
}
] |
Kali Linux - Reporting Tools
|
In this chapter, we will learn about some reporting tools in Kali Linux.
In all this work that we have performed, it is important to share the results that was produced, to track our work, etc. For this purpose, Kali has a reporting tool called dradis which is a web service.
Step 1 − To start Dradis, type “service dradis start”.
Step 2 − To open, go to Applications → Reporting Tools → dradis.
The web URL will open. Anybody in LAN can open it in the following URL https://IP of kali machine:3004
Log in with the username and password that was used for the first time.
Step 3 − After logging in, you can import files from NMAP, NESSUS, NEXPOSE. To do so, go to “Import from file” → click “new importer(with real-time feedback)”.
Step 4 − Select the file type that you want to upload. In this case, it is “Nessus scan” → click “Browse”.
If you go to the home page now, on the left panel you will see that the imported scans have are in a folder with their host and port details.
Metagoofil performs a search in Google to identify and download the documents to the local disk and then extracts the metadata. It extracts metadata of public documents belonging to a specific company, individual, object, etc.
To open it, go to: “usr/share/metagoofil/”.
To start searching, type the following command −
python metagoofil.py
You can use the following parameters with this command −
–d (domain name)
–d (domain name)
–t (filetype to download dox,pdf,etc)
–t (filetype to download dox,pdf,etc)
–l (limit the results 10, 100 )
–l (limit the results 10, 100 )
–n (limit files to download)
–n (limit files to download)
–o ( location to save the files)
–o ( location to save the files)
–f (output file)
–f (output file)
The following example shows only the domain name is hidden.
84 Lectures
6.5 hours
Mohamad Mahjoub
8 Lectures
1 hours
Corey Charles
21 Lectures
4 hours
Atul Tiwari
55 Lectures
3 hours
Musab Zayadneh
29 Lectures
2 hours
Musab Zayadneh
32 Lectures
4 hours
Adnaan Arbaaz Ahmed
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2102,
"s": 2029,
"text": "In this chapter, we will learn about some reporting tools in Kali Linux."
},
{
"code": null,
"e": 2305,
"s": 2102,
"text": "In all this work that we have performed, it is important to share the results that was produced, to track our work, etc. For this purpose, Kali has a reporting tool called dradis which is a web service."
},
{
"code": null,
"e": 2360,
"s": 2305,
"text": "Step 1 − To start Dradis, type “service dradis start”."
},
{
"code": null,
"e": 2425,
"s": 2360,
"text": "Step 2 − To open, go to Applications → Reporting Tools → dradis."
},
{
"code": null,
"e": 2528,
"s": 2425,
"text": "The web URL will open. Anybody in LAN can open it in the following URL https://IP of kali machine:3004"
},
{
"code": null,
"e": 2600,
"s": 2528,
"text": "Log in with the username and password that was used for the first time."
},
{
"code": null,
"e": 2760,
"s": 2600,
"text": "Step 3 − After logging in, you can import files from NMAP, NESSUS, NEXPOSE. To do so, go to “Import from file” → click “new importer(with real-time feedback)”."
},
{
"code": null,
"e": 2867,
"s": 2760,
"text": "Step 4 − Select the file type that you want to upload. In this case, it is “Nessus scan” → click “Browse”."
},
{
"code": null,
"e": 3009,
"s": 2867,
"text": "If you go to the home page now, on the left panel you will see that the imported scans have are in a folder with their host and port details."
},
{
"code": null,
"e": 3236,
"s": 3009,
"text": "Metagoofil performs a search in Google to identify and download the documents to the local disk and then extracts the metadata. It extracts metadata of public documents belonging to a specific company, individual, object, etc."
},
{
"code": null,
"e": 3280,
"s": 3236,
"text": "To open it, go to: “usr/share/metagoofil/”."
},
{
"code": null,
"e": 3329,
"s": 3280,
"text": "To start searching, type the following command −"
},
{
"code": null,
"e": 3352,
"s": 3329,
"text": "python metagoofil.py \n"
},
{
"code": null,
"e": 3409,
"s": 3352,
"text": "You can use the following parameters with this command −"
},
{
"code": null,
"e": 3426,
"s": 3409,
"text": "–d (domain name)"
},
{
"code": null,
"e": 3443,
"s": 3426,
"text": "–d (domain name)"
},
{
"code": null,
"e": 3482,
"s": 3443,
"text": "–t (filetype to download dox,pdf,etc)"
},
{
"code": null,
"e": 3521,
"s": 3482,
"text": "–t (filetype to download dox,pdf,etc)"
},
{
"code": null,
"e": 3554,
"s": 3521,
"text": "–l (limit the results 10, 100 )"
},
{
"code": null,
"e": 3587,
"s": 3554,
"text": "–l (limit the results 10, 100 )"
},
{
"code": null,
"e": 3616,
"s": 3587,
"text": "–n (limit files to download)"
},
{
"code": null,
"e": 3645,
"s": 3616,
"text": "–n (limit files to download)"
},
{
"code": null,
"e": 3679,
"s": 3645,
"text": "–o ( location to save the files) "
},
{
"code": null,
"e": 3713,
"s": 3679,
"text": "–o ( location to save the files) "
},
{
"code": null,
"e": 3730,
"s": 3713,
"text": "–f (output file)"
},
{
"code": null,
"e": 3747,
"s": 3730,
"text": "–f (output file)"
},
{
"code": null,
"e": 3807,
"s": 3747,
"text": "The following example shows only the domain name is hidden."
},
{
"code": null,
"e": 3842,
"s": 3807,
"text": "\n 84 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 3859,
"s": 3842,
"text": " Mohamad Mahjoub"
},
{
"code": null,
"e": 3891,
"s": 3859,
"text": "\n 8 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3906,
"s": 3891,
"text": " Corey Charles"
},
{
"code": null,
"e": 3939,
"s": 3906,
"text": "\n 21 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 3952,
"s": 3939,
"text": " Atul Tiwari"
},
{
"code": null,
"e": 3985,
"s": 3952,
"text": "\n 55 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 4001,
"s": 3985,
"text": " Musab Zayadneh"
},
{
"code": null,
"e": 4034,
"s": 4001,
"text": "\n 29 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 4050,
"s": 4034,
"text": " Musab Zayadneh"
},
{
"code": null,
"e": 4083,
"s": 4050,
"text": "\n 32 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 4104,
"s": 4083,
"text": " Adnaan Arbaaz Ahmed"
},
{
"code": null,
"e": 4111,
"s": 4104,
"text": " Print"
},
{
"code": null,
"e": 4122,
"s": 4111,
"text": " Add Notes"
}
] |
Perl | Reverse an array - GeeksforGeeks
|
23 Sep, 2018
Reverse an array or string in Perl.
Iterative Way:Iterate over the array from 0 to mid of array.Swap the arr[i] element with arr[size-i] element.
#Perl code to reverse an array iteratively #declaring an array of integers@arr = (2, 3, 4, 5, 6, 7); # Store length on array in $n variable$n = $#arr; #Print the original arrayprint "The original array is : ";for $i (0 .. $#arr){ print $arr[$i], " ";} #run a loop from 0 to mid of arrayfor my $i (0 .. $#arr/2){ #swap the current element with size-current element $tmp = $arr[$i]; $arr[$i] = $arr[$n-$i]; $arr[$n-$i] = $tmp;} #Print the reversed arrayprint "\nThe reversed array is : ";for $i (0 .. $#arr){ print $arr[$i], " ";}
The original array is : 2 3 4 5 6 7
The reversed array is : 7 6 5 4 3 2
Using Inbuilt Function:Perl has an inbuilt function to reverse an array or a string or a number.
#Perl code to reverse an array using inbuilt function reverse #declaring an array of integers@arr = (2, 3, 4, 5, 6, 7); #Print the original arrayprint "The original array is : ";for $i (0 .. $#arr){ print $arr[$i], " ";} #store the reversed array in @rev_arr@rev_arr = reverse(@arr); #Print the reversed arrayprint "\nThe reversed array is : ";for $i (0 .. $#rev_arr){ print $rev_arr[$i], " ";}
The original array is : 2 3 4 5 6 7
The reversed array is : 7 6 5 4 3 2
Perl-String
Picked
Reverse
Perl
Reverse
Perl
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Perl | Writing to a File
Perl Tutorial - Learn Perl With Examples
Perl | Multidimensional Hashes
Perl | File Handling Introduction
Perl | Reading Excel Files
Perl | Special Character Classes in Regular Expressions
Perl | shift() Function
Perl | Date and Time
Perl | index() Function
Perl | Appending to a File
|
[
{
"code": null,
"e": 23990,
"s": 23962,
"text": "\n23 Sep, 2018"
},
{
"code": null,
"e": 24026,
"s": 23990,
"text": "Reverse an array or string in Perl."
},
{
"code": null,
"e": 24136,
"s": 24026,
"text": "Iterative Way:Iterate over the array from 0 to mid of array.Swap the arr[i] element with arr[size-i] element."
},
{
"code": "#Perl code to reverse an array iteratively #declaring an array of integers@arr = (2, 3, 4, 5, 6, 7); # Store length on array in $n variable$n = $#arr; #Print the original arrayprint \"The original array is : \";for $i (0 .. $#arr){ print $arr[$i], \" \";} #run a loop from 0 to mid of arrayfor my $i (0 .. $#arr/2){ #swap the current element with size-current element $tmp = $arr[$i]; $arr[$i] = $arr[$n-$i]; $arr[$n-$i] = $tmp;} #Print the reversed arrayprint \"\\nThe reversed array is : \";for $i (0 .. $#arr){ print $arr[$i], \" \";}",
"e": 24688,
"s": 24136,
"text": null
},
{
"code": null,
"e": 24762,
"s": 24688,
"text": "The original array is : 2 3 4 5 6 7 \nThe reversed array is : 7 6 5 4 3 2\n"
},
{
"code": null,
"e": 24859,
"s": 24762,
"text": "Using Inbuilt Function:Perl has an inbuilt function to reverse an array or a string or a number."
},
{
"code": "#Perl code to reverse an array using inbuilt function reverse #declaring an array of integers@arr = (2, 3, 4, 5, 6, 7); #Print the original arrayprint \"The original array is : \";for $i (0 .. $#arr){ print $arr[$i], \" \";} #store the reversed array in @rev_arr@rev_arr = reverse(@arr); #Print the reversed arrayprint \"\\nThe reversed array is : \";for $i (0 .. $#rev_arr){ print $rev_arr[$i], \" \";}",
"e": 25264,
"s": 24859,
"text": null
},
{
"code": null,
"e": 25338,
"s": 25264,
"text": "The original array is : 2 3 4 5 6 7 \nThe reversed array is : 7 6 5 4 3 2\n"
},
{
"code": null,
"e": 25350,
"s": 25338,
"text": "Perl-String"
},
{
"code": null,
"e": 25357,
"s": 25350,
"text": "Picked"
},
{
"code": null,
"e": 25365,
"s": 25357,
"text": "Reverse"
},
{
"code": null,
"e": 25370,
"s": 25365,
"text": "Perl"
},
{
"code": null,
"e": 25378,
"s": 25370,
"text": "Reverse"
},
{
"code": null,
"e": 25383,
"s": 25378,
"text": "Perl"
},
{
"code": null,
"e": 25481,
"s": 25383,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25490,
"s": 25481,
"text": "Comments"
},
{
"code": null,
"e": 25503,
"s": 25490,
"text": "Old Comments"
},
{
"code": null,
"e": 25528,
"s": 25503,
"text": "Perl | Writing to a File"
},
{
"code": null,
"e": 25569,
"s": 25528,
"text": "Perl Tutorial - Learn Perl With Examples"
},
{
"code": null,
"e": 25600,
"s": 25569,
"text": "Perl | Multidimensional Hashes"
},
{
"code": null,
"e": 25634,
"s": 25600,
"text": "Perl | File Handling Introduction"
},
{
"code": null,
"e": 25661,
"s": 25634,
"text": "Perl | Reading Excel Files"
},
{
"code": null,
"e": 25717,
"s": 25661,
"text": "Perl | Special Character Classes in Regular Expressions"
},
{
"code": null,
"e": 25741,
"s": 25717,
"text": "Perl | shift() Function"
},
{
"code": null,
"e": 25762,
"s": 25741,
"text": "Perl | Date and Time"
},
{
"code": null,
"e": 25786,
"s": 25762,
"text": "Perl | index() Function"
}
] |
Batch Script - Creating Files
|
The creation of a new file is done with the help of the redirection filter >. This filter can be used to redirect any output to a file. Following is a simple example of how to create a file using the redirection command.
@echo off
echo "Hello">C:\new.txt
If the file new.txt is not present in C:\, then it will be created with the help of the above command.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2390,
"s": 2169,
"text": "The creation of a new file is done with the help of the redirection filter >. This filter can be used to redirect any output to a file. Following is a simple example of how to create a file using the redirection command."
},
{
"code": null,
"e": 2424,
"s": 2390,
"text": "@echo off\necho \"Hello\">C:\\new.txt"
},
{
"code": null,
"e": 2527,
"s": 2424,
"text": "If the file new.txt is not present in C:\\, then it will be created with the help of the above command."
},
{
"code": null,
"e": 2534,
"s": 2527,
"text": " Print"
},
{
"code": null,
"e": 2545,
"s": 2534,
"text": " Add Notes"
}
] |
Smallest number greater than or equal to X whose sum of digits is divisible by Y - GeeksforGeeks
|
08 Nov, 2021
Given two integers X and Y, the task is to find the smallest number greater than or equal to X whose sum of digits is divisible by Y. Note: 1 <= X <= 1000, 1 <= Y <= 50.Examples:
Input: X = 10, Y = 5 Output: 14 Explanation: 14 is the smallest number greater than 10 whose sum of digits (1+4 = 5) is divisible by 5. Input: X = 5923, Y = 13 Output: 5939
Approach: The idea for this problem is to run a loop from X and check for each integer if its sum of digits is divisible by Y or not. Return the first number whose sum of digits is divisible by Y. Given the constraints of X and Y, the answer always exist. Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to find the smallest number// greater than or equal to X and divisible by Y #include <bits/stdc++.h>using namespace std; #define MAXN 10000000 // Function that returns the sum// of digits of a numberint sumOfDigits(int n){ // Initialize variable to // store the sum int sum = 0; while (n > 0) { // Add the last digit // of the number sum += n % 10; // Remove the last digit // from the number n /= 10; } return sum;} // Function that returns the smallest number// greater than or equal to X and divisible by Yint smallestNum(int X, int Y){ // Initialize result variable int res = -1; // Loop through numbers greater // than equal to X for (int i = X; i < MAXN; i++) { // Calculate sum of digits int sum_of_digit = sumOfDigits(i); // Check if sum of digits // is divisible by Y if (sum_of_digit % Y == 0) { res = i; break; } } return res;} // Driver codeint main(){ int X = 5923, Y = 13; cout << smallestNum(X, Y); return 0;}
// Java program to find the smallest number// greater than or equal to X and divisible by Y class GFG{ static final int MAXN = 10000000; // Function that returns the sum// of digits of a numberstatic int sumOfDigits(int n){ // Initialize variable to // store the sum int sum = 0; while (n > 0) { // Add the last digit // of the number sum += n % 10; // Remove the last digit // from the number n /= 10; } return sum;} // Function that returns the smallest number// greater than or equal to X and divisible by Ystatic int smallestNum(int X, int Y){ // Initialize result variable int res = -1; // Loop through numbers greater // than equal to X for (int i = X; i < MAXN; i++) { // Calculate sum of digits int sum_of_digit = sumOfDigits(i); // Check if sum of digits // is divisible by Y if (sum_of_digit % Y == 0) { res = i; break; } } return res;} // Driver codepublic static void main(String[] args){ int X = 5923, Y = 13; System.out.print(smallestNum(X, Y));}} // This code is contributed by Rohit_ranjan
# Python3 program to find the smallest number# greater than or equal to X and divisible by Y MAXN = 10000000 # Function that returns the # sum of digits of a numberdef sumOfDigits(n): # Initialize variable # to store the sum sum = 0 while(n > 0): # Add the last digit # of the number sum += n % 10 # Remove the last digit # from the number n //= 10 return sum # Function that returns the smallest number# greater than or equal to X and divisible by Ydef smallestNum(X, Y): # Initialize result variable res = -1; # Loop through numbers greater # than equal to X for i in range(X, MAXN): # Calculate sum of digits sum_of_digit = sumOfDigits(i) # Check if sum of digits # is divisible by Y if sum_of_digit % Y == 0: res = i break return res # Driver codeif __name__=='__main__': (X, Y) = (5923, 13) print(smallestNum(X, Y)) # This code is contributed by rutvik_56
// C# program to find the smallest number// greater than or equal to X and divisible by Yusing System; class GFG{ static readonly int MAXN = 10000000; // Function that returns the sum// of digits of a numberstatic int sumOfDigits(int n){ // Initialize variable to // store the sum int sum = 0; while(n > 0) { // Add the last digit // of the number sum += n % 10; // Remove the last digit // from the number n /= 10; } return sum;} // Function that returns the smallest number// greater than or equal to X and divisible by Ystatic int smallestNum(int X, int Y){ // Initialize result variable int res = -1; // Loop through numbers greater // than equal to X for(int i = X; i < MAXN; i++) { // Calculate sum of digits int sum_of_digit = sumOfDigits(i); // Check if sum of digits // is divisible by Y if(sum_of_digit % Y == 0) { res = i; break; } } return res;} // Driver codepublic static void Main(String[] args){ int X = 5923, Y = 13; Console.Write(smallestNum(X, Y));}} // This code is contributed by gauravrajput1
<script> // javascript program to find the smallest number// greater than or equal to X and divisible by Yvar MAXN = 10000000; // Function that returns the sum// of digits of a numberfunction sumOfDigits(n){ // Initialize variable to // store the sum var sum = 0; while (n > 0) { // Add the last digit // of the number sum += n % 10; // Remove the last digit // from the number n = parseInt(n/10); } return sum;} // Function that returns the smallest number// greater than or equal to X and divisible by Yfunction smallestNum(X , Y){ // Initialize result variable var res = -1; // Loop through numbers greater // than equal to X for (i = X; i < MAXN; i++) { // Calculate sum of digits var sum_of_digit = sumOfDigits(i); // Check if sum of digits // is divisible by Y if (sum_of_digit % Y == 0) { res = i; break; } } return res;} // Driver codevar X = 5923, Y = 13;document.write(smallestNum(X, Y)); // This code contributed by shikhasingrajput</script>
5939
Time Complexity: O(MAXN)
Auxiliary Space: O(1)
Rohit_ranjan
GauravRajput1
rutvik_56
shikhasingrajput
sushmitamittal1329
number-digits
Mathematical
School Programming
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Merge two sorted arrays
Modulo Operator (%) in C/C++ with Examples
Prime Numbers
Program to find GCD or HCF of two numbers
Program for Decimal to Binary Conversion
Python Dictionary
Arrays in C/C++
Reverse a string in Java
Inheritance in C++
Constructors in C++
|
[
{
"code": null,
"e": 24833,
"s": 24805,
"text": "\n08 Nov, 2021"
},
{
"code": null,
"e": 25014,
"s": 24833,
"text": "Given two integers X and Y, the task is to find the smallest number greater than or equal to X whose sum of digits is divisible by Y. Note: 1 <= X <= 1000, 1 <= Y <= 50.Examples: "
},
{
"code": null,
"e": 25189,
"s": 25014,
"text": "Input: X = 10, Y = 5 Output: 14 Explanation: 14 is the smallest number greater than 10 whose sum of digits (1+4 = 5) is divisible by 5. Input: X = 5923, Y = 13 Output: 5939 "
},
{
"code": null,
"e": 25500,
"s": 25191,
"text": "Approach: The idea for this problem is to run a loop from X and check for each integer if its sum of digits is divisible by Y or not. Return the first number whose sum of digits is divisible by Y. Given the constraints of X and Y, the answer always exist. Below is the implementation of the above approach: "
},
{
"code": null,
"e": 25504,
"s": 25500,
"text": "C++"
},
{
"code": null,
"e": 25509,
"s": 25504,
"text": "Java"
},
{
"code": null,
"e": 25517,
"s": 25509,
"text": "Python3"
},
{
"code": null,
"e": 25520,
"s": 25517,
"text": "C#"
},
{
"code": null,
"e": 25531,
"s": 25520,
"text": "Javascript"
},
{
"code": "// C++ program to find the smallest number// greater than or equal to X and divisible by Y #include <bits/stdc++.h>using namespace std; #define MAXN 10000000 // Function that returns the sum// of digits of a numberint sumOfDigits(int n){ // Initialize variable to // store the sum int sum = 0; while (n > 0) { // Add the last digit // of the number sum += n % 10; // Remove the last digit // from the number n /= 10; } return sum;} // Function that returns the smallest number// greater than or equal to X and divisible by Yint smallestNum(int X, int Y){ // Initialize result variable int res = -1; // Loop through numbers greater // than equal to X for (int i = X; i < MAXN; i++) { // Calculate sum of digits int sum_of_digit = sumOfDigits(i); // Check if sum of digits // is divisible by Y if (sum_of_digit % Y == 0) { res = i; break; } } return res;} // Driver codeint main(){ int X = 5923, Y = 13; cout << smallestNum(X, Y); return 0;}",
"e": 26635,
"s": 25531,
"text": null
},
{
"code": "// Java program to find the smallest number// greater than or equal to X and divisible by Y class GFG{ static final int MAXN = 10000000; // Function that returns the sum// of digits of a numberstatic int sumOfDigits(int n){ // Initialize variable to // store the sum int sum = 0; while (n > 0) { // Add the last digit // of the number sum += n % 10; // Remove the last digit // from the number n /= 10; } return sum;} // Function that returns the smallest number// greater than or equal to X and divisible by Ystatic int smallestNum(int X, int Y){ // Initialize result variable int res = -1; // Loop through numbers greater // than equal to X for (int i = X; i < MAXN; i++) { // Calculate sum of digits int sum_of_digit = sumOfDigits(i); // Check if sum of digits // is divisible by Y if (sum_of_digit % Y == 0) { res = i; break; } } return res;} // Driver codepublic static void main(String[] args){ int X = 5923, Y = 13; System.out.print(smallestNum(X, Y));}} // This code is contributed by Rohit_ranjan",
"e": 27826,
"s": 26635,
"text": null
},
{
"code": "# Python3 program to find the smallest number# greater than or equal to X and divisible by Y MAXN = 10000000 # Function that returns the # sum of digits of a numberdef sumOfDigits(n): # Initialize variable # to store the sum sum = 0 while(n > 0): # Add the last digit # of the number sum += n % 10 # Remove the last digit # from the number n //= 10 return sum # Function that returns the smallest number# greater than or equal to X and divisible by Ydef smallestNum(X, Y): # Initialize result variable res = -1; # Loop through numbers greater # than equal to X for i in range(X, MAXN): # Calculate sum of digits sum_of_digit = sumOfDigits(i) # Check if sum of digits # is divisible by Y if sum_of_digit % Y == 0: res = i break return res # Driver codeif __name__=='__main__': (X, Y) = (5923, 13) print(smallestNum(X, Y)) # This code is contributed by rutvik_56",
"e": 28919,
"s": 27826,
"text": null
},
{
"code": "// C# program to find the smallest number// greater than or equal to X and divisible by Yusing System; class GFG{ static readonly int MAXN = 10000000; // Function that returns the sum// of digits of a numberstatic int sumOfDigits(int n){ // Initialize variable to // store the sum int sum = 0; while(n > 0) { // Add the last digit // of the number sum += n % 10; // Remove the last digit // from the number n /= 10; } return sum;} // Function that returns the smallest number// greater than or equal to X and divisible by Ystatic int smallestNum(int X, int Y){ // Initialize result variable int res = -1; // Loop through numbers greater // than equal to X for(int i = X; i < MAXN; i++) { // Calculate sum of digits int sum_of_digit = sumOfDigits(i); // Check if sum of digits // is divisible by Y if(sum_of_digit % Y == 0) { res = i; break; } } return res;} // Driver codepublic static void Main(String[] args){ int X = 5923, Y = 13; Console.Write(smallestNum(X, Y));}} // This code is contributed by gauravrajput1",
"e": 30129,
"s": 28919,
"text": null
},
{
"code": "<script> // javascript program to find the smallest number// greater than or equal to X and divisible by Yvar MAXN = 10000000; // Function that returns the sum// of digits of a numberfunction sumOfDigits(n){ // Initialize variable to // store the sum var sum = 0; while (n > 0) { // Add the last digit // of the number sum += n % 10; // Remove the last digit // from the number n = parseInt(n/10); } return sum;} // Function that returns the smallest number// greater than or equal to X and divisible by Yfunction smallestNum(X , Y){ // Initialize result variable var res = -1; // Loop through numbers greater // than equal to X for (i = X; i < MAXN; i++) { // Calculate sum of digits var sum_of_digit = sumOfDigits(i); // Check if sum of digits // is divisible by Y if (sum_of_digit % Y == 0) { res = i; break; } } return res;} // Driver codevar X = 5923, Y = 13;document.write(smallestNum(X, Y)); // This code contributed by shikhasingrajput</script>",
"e": 31263,
"s": 30129,
"text": null
},
{
"code": null,
"e": 31268,
"s": 31263,
"text": "5939"
},
{
"code": null,
"e": 31295,
"s": 31270,
"text": "Time Complexity: O(MAXN)"
},
{
"code": null,
"e": 31317,
"s": 31295,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 31330,
"s": 31317,
"text": "Rohit_ranjan"
},
{
"code": null,
"e": 31344,
"s": 31330,
"text": "GauravRajput1"
},
{
"code": null,
"e": 31354,
"s": 31344,
"text": "rutvik_56"
},
{
"code": null,
"e": 31371,
"s": 31354,
"text": "shikhasingrajput"
},
{
"code": null,
"e": 31390,
"s": 31371,
"text": "sushmitamittal1329"
},
{
"code": null,
"e": 31404,
"s": 31390,
"text": "number-digits"
},
{
"code": null,
"e": 31417,
"s": 31404,
"text": "Mathematical"
},
{
"code": null,
"e": 31436,
"s": 31417,
"text": "School Programming"
},
{
"code": null,
"e": 31449,
"s": 31436,
"text": "Mathematical"
},
{
"code": null,
"e": 31547,
"s": 31449,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31556,
"s": 31547,
"text": "Comments"
},
{
"code": null,
"e": 31569,
"s": 31556,
"text": "Old Comments"
},
{
"code": null,
"e": 31593,
"s": 31569,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 31636,
"s": 31593,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 31650,
"s": 31636,
"text": "Prime Numbers"
},
{
"code": null,
"e": 31692,
"s": 31650,
"text": "Program to find GCD or HCF of two numbers"
},
{
"code": null,
"e": 31733,
"s": 31692,
"text": "Program for Decimal to Binary Conversion"
},
{
"code": null,
"e": 31751,
"s": 31733,
"text": "Python Dictionary"
},
{
"code": null,
"e": 31767,
"s": 31751,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 31792,
"s": 31767,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 31811,
"s": 31792,
"text": "Inheritance in C++"
}
] |
Python - Create list of tuples using for loop - GeeksforGeeks
|
14 Sep, 2021
In this article, we will discuss how to create a List of Tuples using for loop in Python.
Let’s suppose we have a list and we want a create a list of tuples from that list where every element of the tuple will contain the list element and its corresponding index.
Here we will use the for loop along with the append() method. We will iterate through elements of the list and will add a tuple to the resulting list using the append() method.
Example:
Python3
L = [5, 4, 2, 5, 6, 1]res = [] for i in range(len(L)): res.append((L[i], i)) print("List of Tuples")print(res)
List of Tuples
[(5, 0), (4, 1), (2, 2), (5, 3), (6, 4), (1, 5)]
Enumerate() method adds a counter to an iterable and returns it in a form of enumerating object. So we can use this function to create the desired list of tuples.
Example:
Python3
L = [5, 4, 2, 5, 6, 1]res = [] for index, element in enumerate(L): res.append((element, index)) print("List of Tuples")print(res)
List of Tuples
[(5, 0), (4, 1), (2, 2), (5, 3), (6, 4), (1, 5)]
Blogathon-2021
Picked
Python List-of-Tuples
Blogathon
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Import JSON Data into SQL Server?
How to Install Tkinter in Windows?
Difference between write() and writelines() function in Python
SQL Query to Create Table With a Primary Key
SQL Query to Convert Datetime to Date
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": 24732,
"s": 24704,
"text": "\n14 Sep, 2021"
},
{
"code": null,
"e": 24822,
"s": 24732,
"text": "In this article, we will discuss how to create a List of Tuples using for loop in Python."
},
{
"code": null,
"e": 24996,
"s": 24822,
"text": "Let’s suppose we have a list and we want a create a list of tuples from that list where every element of the tuple will contain the list element and its corresponding index."
},
{
"code": null,
"e": 25173,
"s": 24996,
"text": "Here we will use the for loop along with the append() method. We will iterate through elements of the list and will add a tuple to the resulting list using the append() method."
},
{
"code": null,
"e": 25182,
"s": 25173,
"text": "Example:"
},
{
"code": null,
"e": 25190,
"s": 25182,
"text": "Python3"
},
{
"code": "L = [5, 4, 2, 5, 6, 1]res = [] for i in range(len(L)): res.append((L[i], i)) print(\"List of Tuples\")print(res)",
"e": 25310,
"s": 25190,
"text": null
},
{
"code": null,
"e": 25374,
"s": 25310,
"text": "List of Tuples\n[(5, 0), (4, 1), (2, 2), (5, 3), (6, 4), (1, 5)]"
},
{
"code": null,
"e": 25537,
"s": 25374,
"text": "Enumerate() method adds a counter to an iterable and returns it in a form of enumerating object. So we can use this function to create the desired list of tuples."
},
{
"code": null,
"e": 25546,
"s": 25537,
"text": "Example:"
},
{
"code": null,
"e": 25554,
"s": 25546,
"text": "Python3"
},
{
"code": "L = [5, 4, 2, 5, 6, 1]res = [] for index, element in enumerate(L): res.append((element, index)) print(\"List of Tuples\")print(res)",
"e": 25693,
"s": 25554,
"text": null
},
{
"code": null,
"e": 25757,
"s": 25693,
"text": "List of Tuples\n[(5, 0), (4, 1), (2, 2), (5, 3), (6, 4), (1, 5)]"
},
{
"code": null,
"e": 25772,
"s": 25757,
"text": "Blogathon-2021"
},
{
"code": null,
"e": 25779,
"s": 25772,
"text": "Picked"
},
{
"code": null,
"e": 25801,
"s": 25779,
"text": "Python List-of-Tuples"
},
{
"code": null,
"e": 25811,
"s": 25801,
"text": "Blogathon"
},
{
"code": null,
"e": 25818,
"s": 25811,
"text": "Python"
},
{
"code": null,
"e": 25834,
"s": 25818,
"text": "Python Programs"
},
{
"code": null,
"e": 25932,
"s": 25834,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25941,
"s": 25932,
"text": "Comments"
},
{
"code": null,
"e": 25954,
"s": 25941,
"text": "Old Comments"
},
{
"code": null,
"e": 25995,
"s": 25954,
"text": "How to Import JSON Data into SQL Server?"
},
{
"code": null,
"e": 26030,
"s": 25995,
"text": "How to Install Tkinter in Windows?"
},
{
"code": null,
"e": 26093,
"s": 26030,
"text": "Difference between write() and writelines() function in Python"
},
{
"code": null,
"e": 26138,
"s": 26093,
"text": "SQL Query to Create Table With a Primary Key"
},
{
"code": null,
"e": 26176,
"s": 26138,
"text": "SQL Query to Convert Datetime to Date"
},
{
"code": null,
"e": 26204,
"s": 26176,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 26254,
"s": 26204,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 26276,
"s": 26254,
"text": "Python map() function"
}
] |
StringStream in C++ for Decimal to Hexadecimal and back - GeeksforGeeks
|
09 May, 2018
Stringstream is stream class present in C++ which is used for doing operations on a string. It can be used for formatting/parsing/converting a string to number/char etc.Hex is an I/O manipulator that takes reference to an I/O stream as parameter and returns reference to the stream after manipulation.Here is a quick way to convert any decimal to hexadecimal using stringstream:
// CPP program to convert integer to// hexadecimal using stringstream and// hex I/O manipulator.#include <bits/stdc++.h>using namespace std; int main(){ int i = 942; stringstream ss; ss << hex << i; string res = ss.str(); cout << "0x" << res << endl; // this will print 0x3ae return 0;}
Output:
0x3ae
If we want to change hexadecimal string back to decimal you can do it by following way:
// CPP program to convert hexadecimal to// integer using stringstream and// hex I/O manipulator.#include <bits/stdc++.h>using namespace std; int main(){ string hexStr = "0x3ae"; unsigned int x; stringstream ss; ss << std::hex << hexStr; ss >> x; cout << x << endl; // this will print 942 return 0;}
Output:
942
base-conversion
cpp-input-output
cpp-string
cpp-stringstream
C++
C++ Programs
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Map in C++ Standard Template Library (STL)
Inheritance in C++
Constructors in C++
C++ Classes and Objects
Socket Programming in C/C++
Header files in C/C++ and its uses
C++ Program for QuickSort
How to return multiple values from a function in C or C++?
Program to print ASCII Value of a character
C++ program for hashing with chaining
|
[
{
"code": null,
"e": 24303,
"s": 24275,
"text": "\n09 May, 2018"
},
{
"code": null,
"e": 24682,
"s": 24303,
"text": "Stringstream is stream class present in C++ which is used for doing operations on a string. It can be used for formatting/parsing/converting a string to number/char etc.Hex is an I/O manipulator that takes reference to an I/O stream as parameter and returns reference to the stream after manipulation.Here is a quick way to convert any decimal to hexadecimal using stringstream:"
},
{
"code": "// CPP program to convert integer to// hexadecimal using stringstream and// hex I/O manipulator.#include <bits/stdc++.h>using namespace std; int main(){ int i = 942; stringstream ss; ss << hex << i; string res = ss.str(); cout << \"0x\" << res << endl; // this will print 0x3ae return 0;}",
"e": 24988,
"s": 24682,
"text": null
},
{
"code": null,
"e": 24996,
"s": 24988,
"text": "Output:"
},
{
"code": null,
"e": 25003,
"s": 24996,
"text": "0x3ae\n"
},
{
"code": null,
"e": 25091,
"s": 25003,
"text": "If we want to change hexadecimal string back to decimal you can do it by following way:"
},
{
"code": "// CPP program to convert hexadecimal to// integer using stringstream and// hex I/O manipulator.#include <bits/stdc++.h>using namespace std; int main(){ string hexStr = \"0x3ae\"; unsigned int x; stringstream ss; ss << std::hex << hexStr; ss >> x; cout << x << endl; // this will print 942 return 0;}",
"e": 25412,
"s": 25091,
"text": null
},
{
"code": null,
"e": 25420,
"s": 25412,
"text": "Output:"
},
{
"code": null,
"e": 25425,
"s": 25420,
"text": "942\n"
},
{
"code": null,
"e": 25441,
"s": 25425,
"text": "base-conversion"
},
{
"code": null,
"e": 25458,
"s": 25441,
"text": "cpp-input-output"
},
{
"code": null,
"e": 25469,
"s": 25458,
"text": "cpp-string"
},
{
"code": null,
"e": 25486,
"s": 25469,
"text": "cpp-stringstream"
},
{
"code": null,
"e": 25490,
"s": 25486,
"text": "C++"
},
{
"code": null,
"e": 25503,
"s": 25490,
"text": "C++ Programs"
},
{
"code": null,
"e": 25507,
"s": 25503,
"text": "CPP"
},
{
"code": null,
"e": 25605,
"s": 25507,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25614,
"s": 25605,
"text": "Comments"
},
{
"code": null,
"e": 25627,
"s": 25614,
"text": "Old Comments"
},
{
"code": null,
"e": 25670,
"s": 25627,
"text": "Map in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 25689,
"s": 25670,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 25709,
"s": 25689,
"text": "Constructors in C++"
},
{
"code": null,
"e": 25733,
"s": 25709,
"text": "C++ Classes and Objects"
},
{
"code": null,
"e": 25761,
"s": 25733,
"text": "Socket Programming in C/C++"
},
{
"code": null,
"e": 25796,
"s": 25761,
"text": "Header files in C/C++ and its uses"
},
{
"code": null,
"e": 25822,
"s": 25796,
"text": "C++ Program for QuickSort"
},
{
"code": null,
"e": 25881,
"s": 25822,
"text": "How to return multiple values from a function in C or C++?"
},
{
"code": null,
"e": 25925,
"s": 25881,
"text": "Program to print ASCII Value of a character"
}
] |
C - switch statement
|
A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each switch case.
The syntax for a switch statement in C programming language is as follows −
switch(expression) {
case constant-expression :
statement(s);
break; /* optional */
case constant-expression :
statement(s);
break; /* optional */
/* you can have any number of case statements */
default : /* Optional */
statement(s);
}
The following rules apply to a switch statement −
The expression used in a switch statement must have an integral or enumerated type, or be of a class type in which the class has a single conversion function to an integral or enumerated type.
The expression used in a switch statement must have an integral or enumerated type, or be of a class type in which the class has a single conversion function to an integral or enumerated type.
You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon.
You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon.
The constant-expression for a case must be the same data type as the variable in the switch, and it must be a constant or a literal.
The constant-expression for a case must be the same data type as the variable in the switch, and it must be a constant or a literal.
When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached.
When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached.
When a break statement is reached, the switch terminates, and the flow of control jumps to the next line following the switch statement.
When a break statement is reached, the switch terminates, and the flow of control jumps to the next line following the switch statement.
Not every case needs to contain a break. If no break appears, the flow of control will fall through to subsequent cases until a break is reached.
Not every case needs to contain a break. If no break appears, the flow of control will fall through to subsequent cases until a break is reached.
A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case.
A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case.
#include <stdio.h>
int main () {
/* local variable definition */
char grade = 'B';
switch(grade) {
case 'A' :
printf("Excellent!\n" );
break;
case 'B' :
case 'C' :
printf("Well done\n" );
break;
case 'D' :
printf("You passed\n" );
break;
case 'F' :
printf("Better try again\n" );
break;
default :
printf("Invalid grade\n" );
}
printf("Your grade is %c\n", grade );
return 0;
}
When the above code is compiled and executed, it produces the following result −
Well done
Your grade is B
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2270,
"s": 2084,
"text": "A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each switch case."
},
{
"code": null,
"e": 2346,
"s": 2270,
"text": "The syntax for a switch statement in C programming language is as follows −"
},
{
"code": null,
"e": 2630,
"s": 2346,
"text": "switch(expression) {\n\n case constant-expression :\n statement(s);\n break; /* optional */\n\t\n case constant-expression :\n statement(s);\n break; /* optional */\n \n /* you can have any number of case statements */\n default : /* Optional */\n statement(s);\n}"
},
{
"code": null,
"e": 2680,
"s": 2630,
"text": "The following rules apply to a switch statement −"
},
{
"code": null,
"e": 2873,
"s": 2680,
"text": "The expression used in a switch statement must have an integral or enumerated type, or be of a class type in which the class has a single conversion function to an integral or enumerated type."
},
{
"code": null,
"e": 3066,
"s": 2873,
"text": "The expression used in a switch statement must have an integral or enumerated type, or be of a class type in which the class has a single conversion function to an integral or enumerated type."
},
{
"code": null,
"e": 3192,
"s": 3066,
"text": "You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon."
},
{
"code": null,
"e": 3318,
"s": 3192,
"text": "You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon."
},
{
"code": null,
"e": 3451,
"s": 3318,
"text": "The constant-expression for a case must be the same data type as the variable in the switch, and it must be a constant or a literal."
},
{
"code": null,
"e": 3584,
"s": 3451,
"text": "The constant-expression for a case must be the same data type as the variable in the switch, and it must be a constant or a literal."
},
{
"code": null,
"e": 3724,
"s": 3584,
"text": "When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached."
},
{
"code": null,
"e": 3864,
"s": 3724,
"text": "When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached."
},
{
"code": null,
"e": 4001,
"s": 3864,
"text": "When a break statement is reached, the switch terminates, and the flow of control jumps to the next line following the switch statement."
},
{
"code": null,
"e": 4138,
"s": 4001,
"text": "When a break statement is reached, the switch terminates, and the flow of control jumps to the next line following the switch statement."
},
{
"code": null,
"e": 4284,
"s": 4138,
"text": "Not every case needs to contain a break. If no break appears, the flow of control will fall through to subsequent cases until a break is reached."
},
{
"code": null,
"e": 4430,
"s": 4284,
"text": "Not every case needs to contain a break. If no break appears, the flow of control will fall through to subsequent cases until a break is reached."
},
{
"code": null,
"e": 4651,
"s": 4430,
"text": "A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case."
},
{
"code": null,
"e": 4872,
"s": 4651,
"text": "A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case."
},
{
"code": null,
"e": 5395,
"s": 4872,
"text": "#include <stdio.h>\n \nint main () {\n\n /* local variable definition */\n char grade = 'B';\n\n switch(grade) {\n case 'A' :\n printf(\"Excellent!\\n\" );\n break;\n case 'B' :\n case 'C' :\n printf(\"Well done\\n\" );\n break;\n case 'D' :\n printf(\"You passed\\n\" );\n break;\n case 'F' :\n printf(\"Better try again\\n\" );\n break;\n default :\n printf(\"Invalid grade\\n\" );\n }\n \n printf(\"Your grade is %c\\n\", grade );\n \n return 0;\n}"
},
{
"code": null,
"e": 5476,
"s": 5395,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 5503,
"s": 5476,
"text": "Well done\nYour grade is B\n"
},
{
"code": null,
"e": 5510,
"s": 5503,
"text": " Print"
},
{
"code": null,
"e": 5521,
"s": 5510,
"text": " Add Notes"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.