title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
Birthday Reminder Application in Python - GeeksforGeeks | 31 Dec, 2021
This app helps in reminding birthdays and notifying your friend’s birthdays. This app uses Python and Ubuntu notifications to notify users on every startup of the system.
# Python program For# Birthday Reminder Application # time module is must as reminder # is set with the help of datesimport time # os module is used to notify user # using default "Ubuntu" notification barimport os # Birthday file is the one in which the actual birthdays# and dates are present. This file can be # manually edited or can be automated. # For simplicity, we will edit it manually.# Birthdays should be written in this file in# the format: "MonthDay Name Surname" (Without Quotes) birthdayFile = '/path/to/birthday/file' def checkTodaysBirthdays(): fileName = open(birthdayFile, 'r') today = time.strftime('%m%d') flag = 0 for line in fileName: if today in line: line = line.split(' ') flag =1 # line[1] contains Name and line[2] contains Surname os.system('notify-send "Birthdays Today: ' + line[1] + ' ' + line[2] + '"') if flag == 0: os.system('notify-send "No Birthdays Today!"') if __name__ == '__main__': checkTodaysBirthdays()
Adding the script to Startup
After writing the above code now it is the time to add this Python script to startup. This can be done in Ubuntu as follows:
Firstly, we have to create an executable file for our reminder.py scriptThis can be done by typing the following command in the terminalsudo chmod +x reminder.py, where reminder.py is our script file name Now we have to transfer this file to the path where Linux searches for its default files:Type this command in terminal: sudo cp /path/to/our/reminder.py /usr/bin. This will add our executable script to /usr/bin.In global search, search for Startup ApplicationsClick on Add and Give a desired Name for your processType in the command. For example, our file name is reminder.py then type reminder.py in the command field and Select Add
Firstly, we have to create an executable file for our reminder.py script
This can be done by typing the following command in the terminalsudo chmod +x reminder.py, where reminder.py is our script file name
sudo chmod +x reminder.py, where reminder.py is our script file name
Now we have to transfer this file to the path where Linux searches for its default files:Type this command in terminal: sudo cp /path/to/our/reminder.py /usr/bin. This will add our executable script to /usr/bin.
sudo cp /path/to/our/reminder.py /usr/bin
. This will add our executable script to /usr/bin.
In global search, search for Startup Applications
Click on Add and Give a desired Name for your process
Type in the command. For example, our file name is reminder.py then type reminder.py in the command field and Select Add
NOTE: The script runs automatically(once added to startup) everytime you start your system. Also, If you have more than two birthdays on the same day, both the birthdays will be notified in the notification.
How the birthday file should look like
Output after running the script
This article is contributed by Omkar Pathak. 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.
ddeevviissaavviittaa
Python-projects
python-utility
GBlog
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
DSA Sheet by Love Babbar
How to Start Learning DSA?
Supervised and Unsupervised learning
Differences between Procedural and Object Oriented Programming
Introduction to Recurrent Neural Network
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": 26273,
"s": 26245,
"text": "\n31 Dec, 2021"
},
{
"code": null,
"e": 26444,
"s": 26273,
"text": "This app helps in reminding birthdays and notifying your friend’s birthdays. This app uses Python and Ubuntu notifications to notify users on every startup of the system."
},
{
"code": "# Python program For# Birthday Reminder Application # time module is must as reminder # is set with the help of datesimport time # os module is used to notify user # using default \"Ubuntu\" notification barimport os # Birthday file is the one in which the actual birthdays# and dates are present. This file can be # manually edited or can be automated. # For simplicity, we will edit it manually.# Birthdays should be written in this file in# the format: \"MonthDay Name Surname\" (Without Quotes) birthdayFile = '/path/to/birthday/file' def checkTodaysBirthdays(): fileName = open(birthdayFile, 'r') today = time.strftime('%m%d') flag = 0 for line in fileName: if today in line: line = line.split(' ') flag =1 # line[1] contains Name and line[2] contains Surname os.system('notify-send \"Birthdays Today: ' + line[1] + ' ' + line[2] + '\"') if flag == 0: os.system('notify-send \"No Birthdays Today!\"') if __name__ == '__main__': checkTodaysBirthdays()",
"e": 27489,
"s": 26444,
"text": null
},
{
"code": null,
"e": 27518,
"s": 27489,
"text": "Adding the script to Startup"
},
{
"code": null,
"e": 27643,
"s": 27518,
"text": "After writing the above code now it is the time to add this Python script to startup. This can be done in Ubuntu as follows:"
},
{
"code": null,
"e": 28282,
"s": 27643,
"text": "Firstly, we have to create an executable file for our reminder.py scriptThis can be done by typing the following command in the terminalsudo chmod +x reminder.py, where reminder.py is our script file name Now we have to transfer this file to the path where Linux searches for its default files:Type this command in terminal: sudo cp /path/to/our/reminder.py /usr/bin. This will add our executable script to /usr/bin.In global search, search for Startup ApplicationsClick on Add and Give a desired Name for your processType in the command. For example, our file name is reminder.py then type reminder.py in the command field and Select Add"
},
{
"code": null,
"e": 28355,
"s": 28282,
"text": "Firstly, we have to create an executable file for our reminder.py script"
},
{
"code": null,
"e": 28489,
"s": 28355,
"text": "This can be done by typing the following command in the terminalsudo chmod +x reminder.py, where reminder.py is our script file name "
},
{
"code": null,
"e": 28559,
"s": 28489,
"text": "sudo chmod +x reminder.py, where reminder.py is our script file name "
},
{
"code": null,
"e": 28771,
"s": 28559,
"text": "Now we have to transfer this file to the path where Linux searches for its default files:Type this command in terminal: sudo cp /path/to/our/reminder.py /usr/bin. This will add our executable script to /usr/bin."
},
{
"code": null,
"e": 28814,
"s": 28771,
"text": " sudo cp /path/to/our/reminder.py /usr/bin"
},
{
"code": null,
"e": 28865,
"s": 28814,
"text": ". This will add our executable script to /usr/bin."
},
{
"code": null,
"e": 28915,
"s": 28865,
"text": "In global search, search for Startup Applications"
},
{
"code": null,
"e": 28969,
"s": 28915,
"text": "Click on Add and Give a desired Name for your process"
},
{
"code": null,
"e": 29090,
"s": 28969,
"text": "Type in the command. For example, our file name is reminder.py then type reminder.py in the command field and Select Add"
},
{
"code": null,
"e": 29298,
"s": 29090,
"text": "NOTE: The script runs automatically(once added to startup) everytime you start your system. Also, If you have more than two birthdays on the same day, both the birthdays will be notified in the notification."
},
{
"code": null,
"e": 29337,
"s": 29298,
"text": "How the birthday file should look like"
},
{
"code": null,
"e": 29369,
"s": 29337,
"text": "Output after running the script"
},
{
"code": null,
"e": 29665,
"s": 29369,
"text": "This article is contributed by Omkar Pathak. 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": 29790,
"s": 29665,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 29811,
"s": 29790,
"text": "ddeevviissaavviittaa"
},
{
"code": null,
"e": 29827,
"s": 29811,
"text": "Python-projects"
},
{
"code": null,
"e": 29842,
"s": 29827,
"text": "python-utility"
},
{
"code": null,
"e": 29848,
"s": 29842,
"text": "GBlog"
},
{
"code": null,
"e": 29855,
"s": 29848,
"text": "Python"
},
{
"code": null,
"e": 29953,
"s": 29855,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29978,
"s": 29953,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 30005,
"s": 29978,
"text": "How to Start Learning DSA?"
},
{
"code": null,
"e": 30042,
"s": 30005,
"text": "Supervised and Unsupervised learning"
},
{
"code": null,
"e": 30105,
"s": 30042,
"text": "Differences between Procedural and Object Oriented Programming"
},
{
"code": null,
"e": 30146,
"s": 30105,
"text": "Introduction to Recurrent Neural Network"
},
{
"code": null,
"e": 30174,
"s": 30146,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 30224,
"s": 30174,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 30246,
"s": 30224,
"text": "Python map() function"
}
] |
string.punctuation in Python - GeeksforGeeks | 15 Oct, 2019
In Python3, string.punctuation is a pre-initialized string used as string constant. In Python, string.punctuation will give the all sets of punctuation.
Syntax : string.punctuation
Parameters : Doesn’t take any parameter, since it’s not a function.
Returns : Return all sets of punctuation.
Note : Make sure to import string library function inorder to use string.punctuation
Code #1 :
# import string library function import string # Storing the sets of punctuation in variable result result = string.punctuation # Printing the punctuation values print(result)
Output :
!"#$%&'()*+, -./:;<=>?@[\]^_`{|}~
Code #2 : Given code tests for punctuation.
# import string library function import string # An input string.Sentence = "Hey, Geeks !, How are you?" for i in Sentence: # checking whether the char is punctuation. if i in string.punctuation: # Printing the punctuation values print("Punctuation: " + i)
Output:
Punctuation:,
Punctuation: !
Punctuation:,
Punctuation: ?
shubham_singh
python-string
Python-string-functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
*args and **kwargs in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
Check if element exists in list in Python
sum() function in Python | [
{
"code": null,
"e": 26158,
"s": 26130,
"text": "\n15 Oct, 2019"
},
{
"code": null,
"e": 26311,
"s": 26158,
"text": "In Python3, string.punctuation is a pre-initialized string used as string constant. In Python, string.punctuation will give the all sets of punctuation."
},
{
"code": null,
"e": 26339,
"s": 26311,
"text": "Syntax : string.punctuation"
},
{
"code": null,
"e": 26407,
"s": 26339,
"text": "Parameters : Doesn’t take any parameter, since it’s not a function."
},
{
"code": null,
"e": 26449,
"s": 26407,
"text": "Returns : Return all sets of punctuation."
},
{
"code": null,
"e": 26534,
"s": 26449,
"text": "Note : Make sure to import string library function inorder to use string.punctuation"
},
{
"code": null,
"e": 26544,
"s": 26534,
"text": "Code #1 :"
},
{
"code": "# import string library function import string # Storing the sets of punctuation in variable result result = string.punctuation # Printing the punctuation values print(result) ",
"e": 26729,
"s": 26544,
"text": null
},
{
"code": null,
"e": 26738,
"s": 26729,
"text": "Output :"
},
{
"code": null,
"e": 26773,
"s": 26738,
"text": "!\"#$%&'()*+, -./:;<=>?@[\\]^_`{|}~\n"
},
{
"code": null,
"e": 26818,
"s": 26773,
"text": " Code #2 : Given code tests for punctuation."
},
{
"code": "# import string library function import string # An input string.Sentence = \"Hey, Geeks !, How are you?\" for i in Sentence: # checking whether the char is punctuation. if i in string.punctuation: # Printing the punctuation values print(\"Punctuation: \" + i) ",
"e": 27120,
"s": 26818,
"text": null
},
{
"code": null,
"e": 27128,
"s": 27120,
"text": "Output:"
},
{
"code": null,
"e": 27187,
"s": 27128,
"text": "Punctuation:,\nPunctuation: !\nPunctuation:,\nPunctuation: ?\n"
},
{
"code": null,
"e": 27201,
"s": 27187,
"text": "shubham_singh"
},
{
"code": null,
"e": 27215,
"s": 27201,
"text": "python-string"
},
{
"code": null,
"e": 27239,
"s": 27215,
"text": "Python-string-functions"
},
{
"code": null,
"e": 27246,
"s": 27239,
"text": "Python"
},
{
"code": null,
"e": 27344,
"s": 27246,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27362,
"s": 27344,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27394,
"s": 27362,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27416,
"s": 27394,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27458,
"s": 27416,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27484,
"s": 27458,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27513,
"s": 27484,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 27550,
"s": 27513,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 27586,
"s": 27550,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 27628,
"s": 27586,
"text": "Check if element exists in list in Python"
}
] |
Python | Numpy numpy.choose() - GeeksforGeeks | 10 Apr, 2019
With the help of Numpy numpy.choose() method, we can select the elements from an multidimensional array by passing a parameter as an array which contain the index of row number to be selected. Output array having the same size as passed in the parameter.
Syntax : numpy.choose()
Return : Return an array of element choice
Example #1 :In this example we can see that with the help of numpy.choose() method we are able to extract an array of choices from multidimensional array.
# import the important module in pythonimport numpy as np # make a matrix with numpygfg = [[1, 2, 3, 4], [3, 1, 5, 6]] # applying numpy.choose() methodgeeks = np.choose([1, 0, 1, 0], gfg) print(geeks)
array([3 2 5 4])
Example #2 :
# import the important module in pythonimport numpy as np # make a matrix with numpygfg = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] # applying numpy.choose() methodgeeks = np.choose([2, 0, 1], gfg) print(geeks)
array([7 2 6])
Python numpy-arrayManipulation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n10 Apr, 2019"
},
{
"code": null,
"e": 25792,
"s": 25537,
"text": "With the help of Numpy numpy.choose() method, we can select the elements from an multidimensional array by passing a parameter as an array which contain the index of row number to be selected. Output array having the same size as passed in the parameter."
},
{
"code": null,
"e": 25816,
"s": 25792,
"text": "Syntax : numpy.choose()"
},
{
"code": null,
"e": 25859,
"s": 25816,
"text": "Return : Return an array of element choice"
},
{
"code": null,
"e": 26014,
"s": 25859,
"text": "Example #1 :In this example we can see that with the help of numpy.choose() method we are able to extract an array of choices from multidimensional array."
},
{
"code": "# import the important module in pythonimport numpy as np # make a matrix with numpygfg = [[1, 2, 3, 4], [3, 1, 5, 6]] # applying numpy.choose() methodgeeks = np.choose([1, 0, 1, 0], gfg) print(geeks)",
"e": 26245,
"s": 26014,
"text": null
},
{
"code": null,
"e": 26263,
"s": 26245,
"text": "array([3 2 5 4])\n"
},
{
"code": null,
"e": 26276,
"s": 26263,
"text": "Example #2 :"
},
{
"code": "# import the important module in pythonimport numpy as np # make a matrix with numpygfg = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] # applying numpy.choose() methodgeeks = np.choose([2, 0, 1], gfg) print(geeks)",
"e": 26509,
"s": 26276,
"text": null
},
{
"code": null,
"e": 26525,
"s": 26509,
"text": "array([7 2 6])\n"
},
{
"code": null,
"e": 26556,
"s": 26525,
"text": "Python numpy-arrayManipulation"
},
{
"code": null,
"e": 26569,
"s": 26556,
"text": "Python-numpy"
},
{
"code": null,
"e": 26576,
"s": 26569,
"text": "Python"
},
{
"code": null,
"e": 26674,
"s": 26576,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26706,
"s": 26674,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26748,
"s": 26706,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26790,
"s": 26748,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26846,
"s": 26790,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26873,
"s": 26846,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 26904,
"s": 26873,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 26943,
"s": 26904,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 26972,
"s": 26943,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 26994,
"s": 26972,
"text": "Defaultdict in Python"
}
] |
Magnet Puzzle | Backtracking-9 - GeeksforGeeks | 26 Apr, 2020
The puzzle game Magnets involves placing a set of domino-shaped magnets (or electrets or other polarized objects) in a subset of slots on a board so as to satisfy a set of constraints. For example, the puzzle on the left has the solution shown on the right:Each slot contains either a blank entry (indicated by ‘x’s), or a “magnet” with a positive and negative end. The numbers along the left and top sides show the numbers of ‘+’ squares in particular rows or columns. Those along the right and bottom show the number of ‘-’ signs in particular rows or columns. Rows and columns without a number at one or both ends are unconstrained as to the number of ‘+’ or ‘-’ signs, depending on which number is not present. In addition to fulfilling these numerical constraints, a puzzle solution must also satisfy the constraint that no two orthogonally touching squares may have the same sign (diagonally joined squares are not constrained).
You are given top[], bottom[], left[], right[] arrays indicates the count of + or – along the top(+), bottom(-), left(+) and right(-) edges respectively. Values of -1 indicate any number of + and – signs. Also given matrix rules[][] contain any one T, B, L or R characters. For a vertical slot in the board, T indicates its top end and B indicates the bottom end. For a horizontal slot in the board, L indicates left end and R indicates the right end.
Examples:
Input : M = 5, N = 6
top[] = { 1, -1, -1, 2, 1, -1 }
bottom[] = { 2, -1, -1, 2, -1, 3 }
left[] = { 2, 3, -1, -1, -1 }
right[] = { -1, -1, -1, 1, -1 }
rules[][] = { { L, R, L, R, T, T },
{ L, R, L, R, B, B },
{ T, T, T, T, L, R },
{ B, B, B, B, T, T },
{ L, R, L, R, B, B }};
Output : + - + - X -
- + - + X +
X X + - + -
X X - + X +
- + X X X -
Input : M = 4, N = 3
top[] = { 2, -1, -1 }
bottom[] = { -1, -1, 2 }
left[] = { -1, -1, 2, -1 }
right[] = { 0, -1, -1, -1 }
rules[][] = { { T, T, T },
{ B, B, B },
{ T, L, R },
{ B, L, R } };
Output : + X +
– X –
+ – +
– + –
We can solve this problem using Backtracking.
# Write Python3 code hereM = 5N = 6top = [ 1, -1, -1, 2, 1, -1 ]bottom = [ 2, -1, -1, 2, -1, 3 ]left = [ 2, 3, -1, -1, -1 ]right = [ -1, -1, -1, 1, -1 ] rules = [["L","R","L","R","T","T" ], [ "L","R","L","R","B","B" ], [ "T","T","T","T","L","R" ], [ "B","B","B","B","T","T" ], [ "L","R","L","R","B","B" ]]; def canPutPatternHorizontally(rules,i,j,pat): if j-1>=0 and rules[i][j-1] == pat[0]: return False elif i-1>=0 and rules[i-1][j] == pat[0]: return False elif i-1>=0 and rules[i-1][j+1] == pat[1]: return False elif j+2 < len(rules[0]) and rules[i][j+2] == pat[1]: return False return True def canPutPatternVertically(rules,i,j,pat): if j-1>=0 and rules[i][j-1] == pat[0]: return False elif i-1>=0 and rules[i-1][j] == pat[0]: return False elif j+1 < len(rules[0]) and rules[i][j+1] == pat[0]: return False return True def doTheStuff(rules,i,j): if rules[i][j] == "L" or rules[i][j] == "R": # option 1 +- if canPutPatternHorizontally(rules,i,j,"+-"): rules[i][j] = "+" rules[i][j+1] = "-" solveMagnets(rules,i,j) # option 2 -+ # option 3 xx def checkConstraints(rules): pCountH = [0 for i in range(len(rules))] nCountH = [0 for i in range(len(rules))] for row in range(len(rules)): for col in range(len(rules[0])): ch = rules[row][col] if ch == "+": pCountH[row] += 1 elif ch == "-": nCountH[row] += 1 pCountV = [0 for i in range(len(rules[0]))] nCountV = [0 for i in range(len(rules[0]))] for col in range(len(rules[0])): for row in range(len(rules)): ch = rules[row][col] if ch == "+": pCountV[col] += 1 elif ch == "-": nCountV[col] += 1 for row in range(len(rules)): if left[row] != -1: if pCountH[row] != left[row]: return False if right[row] != -1: if nCountH[row] != right[row]: return False for col in range(len(rules[0])): if top[col] != -1: if pCountV[col] != top[col]: return False if bottom[col] != -1: if nCountV[col] != bottom[col]: return False # # if (top[col] != -1 and pCountH[col] != top[col]) or (bottom[col] != -1 and nCountH[col] != bottom[col]) : # return False return True def solveMagnets(rules,i,j): if i == len(rules) and j == 0: # check the constraint before printing if checkConstraints(rules): print(rules) elif j >= len(rules[0]): solveMagnets(rules,i+1,0) # normal cases else: if rules[i][j] == "L": # option 1 +- if canPutPatternHorizontally(rules,i,j,"+-"): rules[i][j] = "+" rules[i][j+1] = "-" solveMagnets(rules,i,j+2) rules[i][j] = "L" rules[i][j+1] = "R" # option 2 -+ if canPutPatternHorizontally(rules,i,j,"-+"): rules[i][j] = "-" rules[i][j+1] = "+" solveMagnets(rules,i,j+2) rules[i][j] = "L" rules[i][j+1] = "R" # option 3 xx if True or canPutPatternHorizontally(rules,i,j,"xx"): rules[i][j] = "x" rules[i][j+1] = "x" solveMagnets(rules,i,j+2) rules[i][j] = "L" rules[i][j+1] = "R" # vertical check elif rules[i][j] == "T": # option 1 +- if canPutPatternVertically(rules,i,j,"+-"): rules[i][j] = "+" rules[i+1][j] = "-" solveMagnets(rules,i,j+1) rules[i][j] = "T" rules[i+1][j] = "B" # option 2 -+ if canPutPatternVertically(rules,i,j,"-+"): rules[i][j] = "-" rules[i+1][j] = "+" solveMagnets(rules,i,j+1) rules[i][j] = "T" rules[i+1][j] = "B" # option 3 xx if True or canPutPatternVertically(rules,i,j,"xx"): rules[i][j] = "x" rules[i+1][j] = "x" solveMagnets(rules,i,j+1) rules[i][j] = "T" rules[i+1][j] = "B" else: solveMagnets(rules,i,j+1) # Driver code solveMagnets(rules,0,0)
Source :https://people.eecs.berkeley.edu/~hilfingr/programming-contest/f2012-contest.pdf
This article is contributed by Anuj Chauhan (anuj0503). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.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.
rahul verma 3
Backtracking
Backtracking
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
m Coloring Problem | Backtracking-5
Hamiltonian Cycle | Backtracking-6
Backtracking to find all subsets
Subset Sum | Backtracking-4
Combinational Sum
Print all permutations of a string in Java
Count all possible paths between two vertices
Travelling Salesman Problem implementation using BackTracking
8 queen problem
Find all distinct subsets of a given set using BitMasking Approach | [
{
"code": null,
"e": 26251,
"s": 26223,
"text": "\n26 Apr, 2020"
},
{
"code": null,
"e": 27186,
"s": 26251,
"text": "The puzzle game Magnets involves placing a set of domino-shaped magnets (or electrets or other polarized objects) in a subset of slots on a board so as to satisfy a set of constraints. For example, the puzzle on the left has the solution shown on the right:Each slot contains either a blank entry (indicated by ‘x’s), or a “magnet” with a positive and negative end. The numbers along the left and top sides show the numbers of ‘+’ squares in particular rows or columns. Those along the right and bottom show the number of ‘-’ signs in particular rows or columns. Rows and columns without a number at one or both ends are unconstrained as to the number of ‘+’ or ‘-’ signs, depending on which number is not present. In addition to fulfilling these numerical constraints, a puzzle solution must also satisfy the constraint that no two orthogonally touching squares may have the same sign (diagonally joined squares are not constrained)."
},
{
"code": null,
"e": 27638,
"s": 27186,
"text": "You are given top[], bottom[], left[], right[] arrays indicates the count of + or – along the top(+), bottom(-), left(+) and right(-) edges respectively. Values of -1 indicate any number of + and – signs. Also given matrix rules[][] contain any one T, B, L or R characters. For a vertical slot in the board, T indicates its top end and B indicates the bottom end. For a horizontal slot in the board, L indicates left end and R indicates the right end."
},
{
"code": null,
"e": 27648,
"s": 27638,
"text": "Examples:"
},
{
"code": null,
"e": 28518,
"s": 27648,
"text": "Input : M = 5, N = 6\n top[] = { 1, -1, -1, 2, 1, -1 }\n bottom[] = { 2, -1, -1, 2, -1, 3 }\n left[] = { 2, 3, -1, -1, -1 }\n right[] = { -1, -1, -1, 1, -1 }\n rules[][] = { { L, R, L, R, T, T },\n { L, R, L, R, B, B },\n { T, T, T, T, L, R },\n { B, B, B, B, T, T },\n { L, R, L, R, B, B }};\nOutput : + - + - X - \n - + - + X + \n X X + - + - \n X X - + X + \n - + X X X - \n\nInput : M = 4, N = 3\n top[] = { 2, -1, -1 }\n bottom[] = { -1, -1, 2 }\n left[] = { -1, -1, 2, -1 }\n right[] = { 0, -1, -1, -1 }\n rules[][] = { { T, T, T },\n { B, B, B },\n { T, L, R },\n { B, L, R } };\nOutput : + X +\n – X –\n + – +\n – + –\n"
},
{
"code": null,
"e": 28564,
"s": 28518,
"text": "We can solve this problem using Backtracking."
},
{
"code": "# Write Python3 code hereM = 5N = 6top = [ 1, -1, -1, 2, 1, -1 ]bottom = [ 2, -1, -1, 2, -1, 3 ]left = [ 2, 3, -1, -1, -1 ]right = [ -1, -1, -1, 1, -1 ] rules = [[\"L\",\"R\",\"L\",\"R\",\"T\",\"T\" ], [ \"L\",\"R\",\"L\",\"R\",\"B\",\"B\" ], [ \"T\",\"T\",\"T\",\"T\",\"L\",\"R\" ], [ \"B\",\"B\",\"B\",\"B\",\"T\",\"T\" ], [ \"L\",\"R\",\"L\",\"R\",\"B\",\"B\" ]]; def canPutPatternHorizontally(rules,i,j,pat): if j-1>=0 and rules[i][j-1] == pat[0]: return False elif i-1>=0 and rules[i-1][j] == pat[0]: return False elif i-1>=0 and rules[i-1][j+1] == pat[1]: return False elif j+2 < len(rules[0]) and rules[i][j+2] == pat[1]: return False return True def canPutPatternVertically(rules,i,j,pat): if j-1>=0 and rules[i][j-1] == pat[0]: return False elif i-1>=0 and rules[i-1][j] == pat[0]: return False elif j+1 < len(rules[0]) and rules[i][j+1] == pat[0]: return False return True def doTheStuff(rules,i,j): if rules[i][j] == \"L\" or rules[i][j] == \"R\": # option 1 +- if canPutPatternHorizontally(rules,i,j,\"+-\"): rules[i][j] = \"+\" rules[i][j+1] = \"-\" solveMagnets(rules,i,j) # option 2 -+ # option 3 xx def checkConstraints(rules): pCountH = [0 for i in range(len(rules))] nCountH = [0 for i in range(len(rules))] for row in range(len(rules)): for col in range(len(rules[0])): ch = rules[row][col] if ch == \"+\": pCountH[row] += 1 elif ch == \"-\": nCountH[row] += 1 pCountV = [0 for i in range(len(rules[0]))] nCountV = [0 for i in range(len(rules[0]))] for col in range(len(rules[0])): for row in range(len(rules)): ch = rules[row][col] if ch == \"+\": pCountV[col] += 1 elif ch == \"-\": nCountV[col] += 1 for row in range(len(rules)): if left[row] != -1: if pCountH[row] != left[row]: return False if right[row] != -1: if nCountH[row] != right[row]: return False for col in range(len(rules[0])): if top[col] != -1: if pCountV[col] != top[col]: return False if bottom[col] != -1: if nCountV[col] != bottom[col]: return False # # if (top[col] != -1 and pCountH[col] != top[col]) or (bottom[col] != -1 and nCountH[col] != bottom[col]) : # return False return True def solveMagnets(rules,i,j): if i == len(rules) and j == 0: # check the constraint before printing if checkConstraints(rules): print(rules) elif j >= len(rules[0]): solveMagnets(rules,i+1,0) # normal cases else: if rules[i][j] == \"L\": # option 1 +- if canPutPatternHorizontally(rules,i,j,\"+-\"): rules[i][j] = \"+\" rules[i][j+1] = \"-\" solveMagnets(rules,i,j+2) rules[i][j] = \"L\" rules[i][j+1] = \"R\" # option 2 -+ if canPutPatternHorizontally(rules,i,j,\"-+\"): rules[i][j] = \"-\" rules[i][j+1] = \"+\" solveMagnets(rules,i,j+2) rules[i][j] = \"L\" rules[i][j+1] = \"R\" # option 3 xx if True or canPutPatternHorizontally(rules,i,j,\"xx\"): rules[i][j] = \"x\" rules[i][j+1] = \"x\" solveMagnets(rules,i,j+2) rules[i][j] = \"L\" rules[i][j+1] = \"R\" # vertical check elif rules[i][j] == \"T\": # option 1 +- if canPutPatternVertically(rules,i,j,\"+-\"): rules[i][j] = \"+\" rules[i+1][j] = \"-\" solveMagnets(rules,i,j+1) rules[i][j] = \"T\" rules[i+1][j] = \"B\" # option 2 -+ if canPutPatternVertically(rules,i,j,\"-+\"): rules[i][j] = \"-\" rules[i+1][j] = \"+\" solveMagnets(rules,i,j+1) rules[i][j] = \"T\" rules[i+1][j] = \"B\" # option 3 xx if True or canPutPatternVertically(rules,i,j,\"xx\"): rules[i][j] = \"x\" rules[i+1][j] = \"x\" solveMagnets(rules,i,j+1) rules[i][j] = \"T\" rules[i+1][j] = \"B\" else: solveMagnets(rules,i,j+1) # Driver code solveMagnets(rules,0,0)",
"e": 33751,
"s": 28564,
"text": null
},
{
"code": null,
"e": 33840,
"s": 33751,
"text": "Source :https://people.eecs.berkeley.edu/~hilfingr/programming-contest/f2012-contest.pdf"
},
{
"code": null,
"e": 34151,
"s": 33840,
"text": "This article is contributed by Anuj Chauhan (anuj0503). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.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": 34276,
"s": 34151,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 34290,
"s": 34276,
"text": "rahul verma 3"
},
{
"code": null,
"e": 34303,
"s": 34290,
"text": "Backtracking"
},
{
"code": null,
"e": 34316,
"s": 34303,
"text": "Backtracking"
},
{
"code": null,
"e": 34414,
"s": 34316,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34450,
"s": 34414,
"text": "m Coloring Problem | Backtracking-5"
},
{
"code": null,
"e": 34485,
"s": 34450,
"text": "Hamiltonian Cycle | Backtracking-6"
},
{
"code": null,
"e": 34518,
"s": 34485,
"text": "Backtracking to find all subsets"
},
{
"code": null,
"e": 34546,
"s": 34518,
"text": "Subset Sum | Backtracking-4"
},
{
"code": null,
"e": 34564,
"s": 34546,
"text": "Combinational Sum"
},
{
"code": null,
"e": 34607,
"s": 34564,
"text": "Print all permutations of a string in Java"
},
{
"code": null,
"e": 34653,
"s": 34607,
"text": "Count all possible paths between two vertices"
},
{
"code": null,
"e": 34715,
"s": 34653,
"text": "Travelling Salesman Problem implementation using BackTracking"
},
{
"code": null,
"e": 34731,
"s": 34715,
"text": "8 queen problem"
}
] |
Difference between Structure and Union in C - GeeksforGeeks | 12 Sep, 2021
structures in C
A structure is a user-defined data type available in C that allows to combining data items of different kinds. Structures are used to represent a record.
Defining a structure: To define a structure, you must use the struct statement. The struct statement defines a new data type, with more than or equal to one member. The format of the struct statement is as follows:
struct [structure name]
{
member definition;
member definition;
...
member definition;
};
union
A union is a special data type available in C that allows storing different data types in the same memory location. You can define a union with many members, but only one member can contain a value at any given time. Unions provide an efficient way of using the same memory location for multiple purposes.
Defining a Union: To define a union, you must use the union statement in the same way as you did while defining a structure. The union statement defines a new data type with more than one member for your program. The format of the union statement is as follows:
union [union name]
{
member definition;
member definition;
...
member definition;
};
Similarities between Structure and Union
Both are user-defined data types used to store data of different types as a single unit.Their members can be objects of any type, including other structures and unions or arrays. A member can also consist of a bit field.Both structures and unions support only assignment = and sizeof operators. The two structures or unions in the assignment must have the same members and member types.A structure or a union can be passed by value to functions and returned by value by functions. The argument must have the same type as the function parameter. A structure or union is passed by value just like a scalar variable as a corresponding parameter.‘.’ operator is used for accessing members.
Both are user-defined data types used to store data of different types as a single unit.
Their members can be objects of any type, including other structures and unions or arrays. A member can also consist of a bit field.
Both structures and unions support only assignment = and sizeof operators. The two structures or unions in the assignment must have the same members and member types.
A structure or a union can be passed by value to functions and returned by value by functions. The argument must have the same type as the function parameter. A structure or union is passed by value just like a scalar variable as a corresponding parameter.
‘.’ operator is used for accessing members.
Differences:
C
// C program to illustrate differences// between structure and Union#include <stdio.h>#include <string.h> // declaring structurestruct struct_example{ int integer; float decimal; char name[20];}; // declaring union union union_example{ int integer; float decimal; char name[20];}; void main(){ // creating variable for structure // and initializing values difference // six struct struct_example s={18,38,"geeksforgeeks"}; // creating variable for union // and initializing values union union_example u={18,38,"geeksforgeeks"}; printf("structure data:\n integer: %d\n" "decimal: %.2f\n name: %s\n", s.integer, s.decimal, s.name); printf("\nunion data:\n integer: %d\n" "decimal: %.2f\n name: %s\n", u.integer, u.decimal, u.name); // difference two and three printf("\nsizeof structure : %d\n", sizeof(s)); printf("sizeof union : %d\n", sizeof(u)); // difference five printf("\n Accessing all members at a time:"); s.integer = 183; s.decimal = 90; strcpy(s.name, "geeksforgeeks"); printf("structure data:\n integer: %d\n " "decimal: %.2f\n name: %s\n", s.integer, s.decimal, s.name); u.integer = 183; u.decimal = 90; strcpy(u.name, "geeksforgeeks"); printf("\nunion data:\n integer: %d\n " "decimal: %.2f\n name: %s\n", u.integer, u.decimal, u.name); printf("\n Accessing one member at time:"); printf("\nstructure data:"); s.integer = 240; printf("\ninteger: %d", s.integer); s.decimal = 120; printf("\ndecimal: %f", s.decimal); strcpy(s.name, "C programming"); printf("\nname: %s\n", s.name); printf("\n union data:"); u.integer = 240; printf("\ninteger: %d", u.integer); u.decimal = 120; printf("\ndecimal: %f", u.decimal); strcpy(u.name, "C programming"); printf("\nname: %s\n", u.name); //difference four printf("\nAltering a member value:\n"); s.integer = 1218; printf("structure data:\n integer: %d\n " " decimal: %.2f\n name: %s\n", s.integer, s.decimal, s.name); u.integer = 1218; printf("union data:\n integer: %d\n" " decimal: %.2f\n name: %s\n", u.integer, u.decimal, u.name);}
Output:
structure data:
integer: 18
decimal: 38.00
name: geeksforgeeks
union data:
integer: 18
decimal: 0.00
name: ?
sizeof structure: 28
sizeof union: 20
Accessing all members at a time: structure data:
integer: 183
decimal: 90.00
name: geeksforgeeks
union data:
integer: 1801807207
decimal: 277322871721159510000000000.00
name: geeksforgeeks
Accessing one member at a time:
structure data:
integer: 240
decimal: 120.000000
name: C programming
union data:
integer: 240
decimal: 120.000000
name: C programming
Altering a member value:
structure data:
integer: 1218
decimal: 120.00
name: C programming
union data:
integer: 1218
decimal: 0.00
name: ?
In my opinion, structure is better because as memory is shared in union ambiguity is more. Quiz on structures and Union This article is contributed by Harish Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
arvindchoudhary6572
qeerransoo
anikaseth98
simmytarika5
C Language
Difference Between
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Multidimensional Arrays in C / C++
Converting Strings to Numbers in C/C++
Left Shift and Right Shift Operators in C/C++
Function Pointer in C
Difference between BFS and DFS
Class method vs Static method in Python
Differences between TCP and UDP
Difference between var, let and const keywords in JavaScript
Differences between IPv4 and IPv6 | [
{
"code": null,
"e": 25575,
"s": 25547,
"text": "\n12 Sep, 2021"
},
{
"code": null,
"e": 25591,
"s": 25575,
"text": "structures in C"
},
{
"code": null,
"e": 25746,
"s": 25591,
"text": "A structure is a user-defined data type available in C that allows to combining data items of different kinds. Structures are used to represent a record. "
},
{
"code": null,
"e": 25961,
"s": 25746,
"text": "Defining a structure: To define a structure, you must use the struct statement. The struct statement defines a new data type, with more than or equal to one member. The format of the struct statement is as follows:"
},
{
"code": null,
"e": 26088,
"s": 25961,
"text": " struct [structure name]\n {\n member definition;\n member definition;\n ...\n member definition;\n };"
},
{
"code": null,
"e": 26094,
"s": 26088,
"text": "union"
},
{
"code": null,
"e": 26401,
"s": 26094,
"text": "A union is a special data type available in C that allows storing different data types in the same memory location. You can define a union with many members, but only one member can contain a value at any given time. Unions provide an efficient way of using the same memory location for multiple purposes. "
},
{
"code": null,
"e": 26664,
"s": 26401,
"text": "Defining a Union: To define a union, you must use the union statement in the same way as you did while defining a structure. The union statement defines a new data type with more than one member for your program. The format of the union statement is as follows: "
},
{
"code": null,
"e": 26789,
"s": 26664,
"text": " union [union name]\n {\n member definition;\n member definition;\n ...\n member definition;\n };"
},
{
"code": null,
"e": 26830,
"s": 26789,
"text": "Similarities between Structure and Union"
},
{
"code": null,
"e": 27516,
"s": 26830,
"text": "Both are user-defined data types used to store data of different types as a single unit.Their members can be objects of any type, including other structures and unions or arrays. A member can also consist of a bit field.Both structures and unions support only assignment = and sizeof operators. The two structures or unions in the assignment must have the same members and member types.A structure or a union can be passed by value to functions and returned by value by functions. The argument must have the same type as the function parameter. A structure or union is passed by value just like a scalar variable as a corresponding parameter.‘.’ operator is used for accessing members."
},
{
"code": null,
"e": 27605,
"s": 27516,
"text": "Both are user-defined data types used to store data of different types as a single unit."
},
{
"code": null,
"e": 27738,
"s": 27605,
"text": "Their members can be objects of any type, including other structures and unions or arrays. A member can also consist of a bit field."
},
{
"code": null,
"e": 27905,
"s": 27738,
"text": "Both structures and unions support only assignment = and sizeof operators. The two structures or unions in the assignment must have the same members and member types."
},
{
"code": null,
"e": 28162,
"s": 27905,
"text": "A structure or a union can be passed by value to functions and returned by value by functions. The argument must have the same type as the function parameter. A structure or union is passed by value just like a scalar variable as a corresponding parameter."
},
{
"code": null,
"e": 28206,
"s": 28162,
"text": "‘.’ operator is used for accessing members."
},
{
"code": null,
"e": 28219,
"s": 28206,
"text": "Differences:"
},
{
"code": null,
"e": 28221,
"s": 28219,
"text": "C"
},
{
"code": "// C program to illustrate differences// between structure and Union#include <stdio.h>#include <string.h> // declaring structurestruct struct_example{ int integer; float decimal; char name[20];}; // declaring union union union_example{ int integer; float decimal; char name[20];}; void main(){ // creating variable for structure // and initializing values difference // six struct struct_example s={18,38,\"geeksforgeeks\"}; // creating variable for union // and initializing values union union_example u={18,38,\"geeksforgeeks\"}; printf(\"structure data:\\n integer: %d\\n\" \"decimal: %.2f\\n name: %s\\n\", s.integer, s.decimal, s.name); printf(\"\\nunion data:\\n integer: %d\\n\" \"decimal: %.2f\\n name: %s\\n\", u.integer, u.decimal, u.name); // difference two and three printf(\"\\nsizeof structure : %d\\n\", sizeof(s)); printf(\"sizeof union : %d\\n\", sizeof(u)); // difference five printf(\"\\n Accessing all members at a time:\"); s.integer = 183; s.decimal = 90; strcpy(s.name, \"geeksforgeeks\"); printf(\"structure data:\\n integer: %d\\n \" \"decimal: %.2f\\n name: %s\\n\", s.integer, s.decimal, s.name); u.integer = 183; u.decimal = 90; strcpy(u.name, \"geeksforgeeks\"); printf(\"\\nunion data:\\n integer: %d\\n \" \"decimal: %.2f\\n name: %s\\n\", u.integer, u.decimal, u.name); printf(\"\\n Accessing one member at time:\"); printf(\"\\nstructure data:\"); s.integer = 240; printf(\"\\ninteger: %d\", s.integer); s.decimal = 120; printf(\"\\ndecimal: %f\", s.decimal); strcpy(s.name, \"C programming\"); printf(\"\\nname: %s\\n\", s.name); printf(\"\\n union data:\"); u.integer = 240; printf(\"\\ninteger: %d\", u.integer); u.decimal = 120; printf(\"\\ndecimal: %f\", u.decimal); strcpy(u.name, \"C programming\"); printf(\"\\nname: %s\\n\", u.name); //difference four printf(\"\\nAltering a member value:\\n\"); s.integer = 1218; printf(\"structure data:\\n integer: %d\\n \" \" decimal: %.2f\\n name: %s\\n\", s.integer, s.decimal, s.name); u.integer = 1218; printf(\"union data:\\n integer: %d\\n\" \" decimal: %.2f\\n name: %s\\n\", u.integer, u.decimal, u.name);}",
"e": 30621,
"s": 28221,
"text": null
},
{
"code": null,
"e": 30629,
"s": 30621,
"text": "Output:"
},
{
"code": null,
"e": 31298,
"s": 30629,
"text": "structure data:\n integer: 18\n decimal: 38.00\n name: geeksforgeeks\n\nunion data:\n integer: 18\n decimal: 0.00\n name: ?\n\nsizeof structure: 28\nsizeof union: 20\n\n Accessing all members at a time: structure data:\n integer: 183\n decimal: 90.00\n name: geeksforgeeks\n\nunion data:\n integer: 1801807207\n decimal: 277322871721159510000000000.00\n name: geeksforgeeks\n\n Accessing one member at a time:\nstructure data:\ninteger: 240\ndecimal: 120.000000\nname: C programming\n\n union data:\ninteger: 240\ndecimal: 120.000000\nname: C programming\n\nAltering a member value:\nstructure data:\n integer: 1218\n decimal: 120.00\n name: C programming\nunion data:\n integer: 1218\n decimal: 0.00\n name: ?"
},
{
"code": null,
"e": 31838,
"s": 31298,
"text": "In my opinion, structure is better because as memory is shared in union ambiguity is more. Quiz on structures and Union This article is contributed by Harish Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 31858,
"s": 31838,
"text": "arvindchoudhary6572"
},
{
"code": null,
"e": 31869,
"s": 31858,
"text": "qeerransoo"
},
{
"code": null,
"e": 31881,
"s": 31869,
"text": "anikaseth98"
},
{
"code": null,
"e": 31894,
"s": 31881,
"text": "simmytarika5"
},
{
"code": null,
"e": 31905,
"s": 31894,
"text": "C Language"
},
{
"code": null,
"e": 31924,
"s": 31905,
"text": "Difference Between"
},
{
"code": null,
"e": 32022,
"s": 31924,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32039,
"s": 32022,
"text": "Substring in C++"
},
{
"code": null,
"e": 32074,
"s": 32039,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 32113,
"s": 32074,
"text": "Converting Strings to Numbers in C/C++"
},
{
"code": null,
"e": 32159,
"s": 32113,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 32181,
"s": 32159,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 32212,
"s": 32181,
"text": "Difference between BFS and DFS"
},
{
"code": null,
"e": 32252,
"s": 32212,
"text": "Class method vs Static method in Python"
},
{
"code": null,
"e": 32284,
"s": 32252,
"text": "Differences between TCP and UDP"
},
{
"code": null,
"e": 32345,
"s": 32284,
"text": "Difference between var, let and const keywords in JavaScript"
}
] |
Python program to add two Octal numbers - GeeksforGeeks | 26 Nov, 2020
Given two octal numbers, the task is to write a Python program to compute their sum.
Examples:
Input: a = "123", b = "456"
Output: 601
Input: a = "654", b = "321"
Output: 1175
Approach:
To add two octal values in python we will first convert them into decimal values then add them and then finally again convert them to an octal value. To convert the numbers we will make use of the oct() function. The oct() function is one of the built-in methods in Python3. The oct() method takes an integer and returns its octal representation in a string format. We will also use the int() function to convert the number to decimal form. The int() function in Python and Python3 converts a number in the given base to decimal.
Below are the implementations based on the above explanation:
Example 1:
Python3
# Python program to add two hexadecimal numbers. # Driver code# Declaring the variablesa = "123"b = "456" # Calculating octal value using functionsum = oct(int(a, 8) + int(b, 8)) # Printing resultprint(sum[2:])
Output:
601
Example 2:
Python3
# Python program to add two hexadecimal numbers. # Driver code# Declaring the variablesa = "654"b = "321" # Calculating octal value using functionsum = oct(int(a, 8) + int(b, 8)) # Printing resultprint(sum[2:])
Output:
1175
Numbers
Python
Python Programs
Numbers
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python? | [
{
"code": null,
"e": 25563,
"s": 25535,
"text": "\n26 Nov, 2020"
},
{
"code": null,
"e": 25648,
"s": 25563,
"text": "Given two octal numbers, the task is to write a Python program to compute their sum."
},
{
"code": null,
"e": 25658,
"s": 25648,
"text": "Examples:"
},
{
"code": null,
"e": 25740,
"s": 25658,
"text": "Input: a = \"123\", b = \"456\"\nOutput: 601\n\nInput: a = \"654\", b = \"321\"\nOutput: 1175"
},
{
"code": null,
"e": 25750,
"s": 25740,
"text": "Approach:"
},
{
"code": null,
"e": 26280,
"s": 25750,
"text": "To add two octal values in python we will first convert them into decimal values then add them and then finally again convert them to an octal value. To convert the numbers we will make use of the oct() function. The oct() function is one of the built-in methods in Python3. The oct() method takes an integer and returns its octal representation in a string format. We will also use the int() function to convert the number to decimal form. The int() function in Python and Python3 converts a number in the given base to decimal."
},
{
"code": null,
"e": 26342,
"s": 26280,
"text": "Below are the implementations based on the above explanation:"
},
{
"code": null,
"e": 26353,
"s": 26342,
"text": "Example 1:"
},
{
"code": null,
"e": 26361,
"s": 26353,
"text": "Python3"
},
{
"code": "# Python program to add two hexadecimal numbers. # Driver code# Declaring the variablesa = \"123\"b = \"456\" # Calculating octal value using functionsum = oct(int(a, 8) + int(b, 8)) # Printing resultprint(sum[2:])",
"e": 26575,
"s": 26361,
"text": null
},
{
"code": null,
"e": 26583,
"s": 26575,
"text": "Output:"
},
{
"code": null,
"e": 26587,
"s": 26583,
"text": "601"
},
{
"code": null,
"e": 26600,
"s": 26589,
"text": "Example 2:"
},
{
"code": null,
"e": 26608,
"s": 26600,
"text": "Python3"
},
{
"code": "# Python program to add two hexadecimal numbers. # Driver code# Declaring the variablesa = \"654\"b = \"321\" # Calculating octal value using functionsum = oct(int(a, 8) + int(b, 8)) # Printing resultprint(sum[2:])",
"e": 26822,
"s": 26608,
"text": null
},
{
"code": null,
"e": 26830,
"s": 26822,
"text": "Output:"
},
{
"code": null,
"e": 26835,
"s": 26830,
"text": "1175"
},
{
"code": null,
"e": 26843,
"s": 26835,
"text": "Numbers"
},
{
"code": null,
"e": 26850,
"s": 26843,
"text": "Python"
},
{
"code": null,
"e": 26866,
"s": 26850,
"text": "Python Programs"
},
{
"code": null,
"e": 26874,
"s": 26866,
"text": "Numbers"
},
{
"code": null,
"e": 26972,
"s": 26874,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27004,
"s": 26972,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27046,
"s": 27004,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27088,
"s": 27046,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27115,
"s": 27088,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27171,
"s": 27115,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27193,
"s": 27171,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27232,
"s": 27193,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 27278,
"s": 27232,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 27316,
"s": 27278,
"text": "Python | Convert a list to dictionary"
}
] |
Loops in LISP - GeeksforGeeks | 06 Oct, 2021
Loops allow executing a set of instructions repeatedly while some condition is true. LISP provides the following types of loops:
The dotimes loop allows executing instructions for a fixed number of times.Syntax:
(dotimes( variableName numberOfIterations ) (
expressions
))
Where,
variableName => Name of the variable, this can be used to get current iteration number
numberOfIterations => Total number of iterations
expressions => Statements to be executed in each iteration
Example:
Lisp
(dotimes (a 4) (print a))(write-line "")
Output:
You can also return from the loop if a certain condition is met
Lisp
(dotimes (i 7) (if (> i 5) (return) (print i)) )(write-line "")
Here, the loop is set to iterate 7 times, however, when the value becomes more than 5, the loop stops because the condition is met. Output:
The loop construct allows executing some statement(s) repeatedly until it finds a return statement.
Syntax:
( loop
(expressions)
( when (condition) (return returnValue))
)
Where,
expressions => Statements to be executed in each iteration
condition => Condition that specifies when to exit loop
returnValue => Value to be returned
Example:
Lisp
(defvar n 3)(loop (print n) (setq n (+ n 1)) (when (> n 6) (return n)))(write-line "")
Here, n is printed and incremented until it becomes greater than 6.Output:
The loop for construct is similar to the for-loops in popular languages like java, c++, etc. It can also be used to traverse lists and other data structures.
Syntax:
( loop for variableName from startValue to endValue by changeValue do
(expressions)
)
Where,
variableName => Name of the variable, this can be used to get the value of variable in current iteration.
startValue => Initial value of variable
endValue => End value of variable (after last iteration)
changeValue => Specifies by how much to increment or decrement value after every iteration
expressions => Statements to be executed in each iteration
Example:
Lisp
; initialize x=12, execute instructions, ; increment it by 3 and perform iteration until it is less than 25(loop for x from 12 to 25 by 3 do (print x))(write-line "")
Output:
The do construct allows a structured form of iteration.Syntax:
(do ((variable_1 value_1 updated-value_1)
(variable_2 value_2 updated-value_2)
(variable_3 value_3 updated-value_3)
...)
(test return_value)
(s-expressions)
)
Where,
variable_1 => First variable
value_1 => Initial Value for first variable
updated-value_1 => Specifies how to update variable_1 after each iteration.
variable_2 => Second variable
value_2 => Initial Value for second variable
updated-value_2 => Specifies how to update variable_2 after each iteration. ... similar till variable_n
test => Condition that specifies when to stop the loop
return value => Value that is returned at the end of iteration
expressions => Other statements to be executed in every iteration
The initial values of each variable are evaluated and bound to the respective variable. The updated value in every clause is with respect to an optional update statement which indicates how to update variables in each iteration.The test is performed on each iteration and if the test expression results in a non-null or true value, the returned value is evaluated and returned.If the last optional s-expression(s) are specified, they’re executed on every iteration while test expression results are true.Example:
Lisp
(do ((a 0 (+ 2 a)) (b 20 ( - b 2))) ((= a b)(- a b)) (format t "~% a = ~d b = ~d" a b))(write-line "")
Output:
The dolist construct provides an easy way to traverse lists.
Syntax:
(dolist (listItemVariable list)
(expressions)
)
Where,
listItemVariable => Holds value of each list item during every iteration
list => List to traverse
expressions => Statements to be executed in every iteration
Example:
Lisp
(defvar nums `(9 5 2 3))(dolist (item nums) (print item))(write-line "")
Output:
References:
Official docs for loops in LISP
LISP-Basics
Picked
LISP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Cond Construct in LISP
Data Types in LISP
LISP - Comparison Operators on Characters & Strings
Mapping Functions in LISP
Symbols in LISP
Case Construct in LISP
Do Construct in LISP
Property Lists in LISP
Naming Conventions in LISP
Loop Construct in LISP | [
{
"code": null,
"e": 24841,
"s": 24813,
"text": "\n06 Oct, 2021"
},
{
"code": null,
"e": 24970,
"s": 24841,
"text": "Loops allow executing a set of instructions repeatedly while some condition is true. LISP provides the following types of loops:"
},
{
"code": null,
"e": 25054,
"s": 24970,
"text": "The dotimes loop allows executing instructions for a fixed number of times.Syntax: "
},
{
"code": null,
"e": 25118,
"s": 25054,
"text": "(dotimes( variableName numberOfIterations ) (\n expressions \n))"
},
{
"code": null,
"e": 25125,
"s": 25118,
"text": "Where,"
},
{
"code": null,
"e": 25212,
"s": 25125,
"text": "variableName => Name of the variable, this can be used to get current iteration number"
},
{
"code": null,
"e": 25261,
"s": 25212,
"text": "numberOfIterations => Total number of iterations"
},
{
"code": null,
"e": 25320,
"s": 25261,
"text": "expressions => Statements to be executed in each iteration"
},
{
"code": null,
"e": 25329,
"s": 25320,
"text": "Example:"
},
{
"code": null,
"e": 25334,
"s": 25329,
"text": "Lisp"
},
{
"code": "(dotimes (a 4) (print a))(write-line \"\")",
"e": 25376,
"s": 25334,
"text": null
},
{
"code": null,
"e": 25384,
"s": 25376,
"text": "Output:"
},
{
"code": null,
"e": 25448,
"s": 25384,
"text": "You can also return from the loop if a certain condition is met"
},
{
"code": null,
"e": 25453,
"s": 25448,
"text": "Lisp"
},
{
"code": "(dotimes (i 7) (if (> i 5) (return) (print i)) )(write-line \"\")",
"e": 25534,
"s": 25453,
"text": null
},
{
"code": null,
"e": 25674,
"s": 25534,
"text": "Here, the loop is set to iterate 7 times, however, when the value becomes more than 5, the loop stops because the condition is met. Output:"
},
{
"code": null,
"e": 25774,
"s": 25674,
"text": "The loop construct allows executing some statement(s) repeatedly until it finds a return statement."
},
{
"code": null,
"e": 25783,
"s": 25774,
"text": "Syntax: "
},
{
"code": null,
"e": 25854,
"s": 25783,
"text": "( loop \n (expressions)\n ( when (condition) (return returnValue))\n)"
},
{
"code": null,
"e": 25861,
"s": 25854,
"text": "Where,"
},
{
"code": null,
"e": 25920,
"s": 25861,
"text": "expressions => Statements to be executed in each iteration"
},
{
"code": null,
"e": 25976,
"s": 25920,
"text": "condition => Condition that specifies when to exit loop"
},
{
"code": null,
"e": 26012,
"s": 25976,
"text": "returnValue => Value to be returned"
},
{
"code": null,
"e": 26021,
"s": 26012,
"text": "Example:"
},
{
"code": null,
"e": 26026,
"s": 26021,
"text": "Lisp"
},
{
"code": "(defvar n 3)(loop (print n) (setq n (+ n 1)) (when (> n 6) (return n)))(write-line \"\")",
"e": 26122,
"s": 26026,
"text": null
},
{
"code": null,
"e": 26197,
"s": 26122,
"text": "Here, n is printed and incremented until it becomes greater than 6.Output:"
},
{
"code": null,
"e": 26355,
"s": 26197,
"text": "The loop for construct is similar to the for-loops in popular languages like java, c++, etc. It can also be used to traverse lists and other data structures."
},
{
"code": null,
"e": 26363,
"s": 26355,
"text": "Syntax:"
},
{
"code": null,
"e": 26452,
"s": 26363,
"text": "( loop for variableName from startValue to endValue by changeValue do\n (expressions)\n)"
},
{
"code": null,
"e": 26459,
"s": 26452,
"text": "Where,"
},
{
"code": null,
"e": 26566,
"s": 26459,
"text": "variableName => Name of the variable, this can be used to get the value of variable in current iteration. "
},
{
"code": null,
"e": 26606,
"s": 26566,
"text": "startValue => Initial value of variable"
},
{
"code": null,
"e": 26663,
"s": 26606,
"text": "endValue => End value of variable (after last iteration)"
},
{
"code": null,
"e": 26754,
"s": 26663,
"text": "changeValue => Specifies by how much to increment or decrement value after every iteration"
},
{
"code": null,
"e": 26813,
"s": 26754,
"text": "expressions => Statements to be executed in each iteration"
},
{
"code": null,
"e": 26822,
"s": 26813,
"text": "Example:"
},
{
"code": null,
"e": 26827,
"s": 26822,
"text": "Lisp"
},
{
"code": "; initialize x=12, execute instructions, ; increment it by 3 and perform iteration until it is less than 25(loop for x from 12 to 25 by 3 do (print x))(write-line \"\")",
"e": 26997,
"s": 26827,
"text": null
},
{
"code": null,
"e": 27005,
"s": 26997,
"text": "Output:"
},
{
"code": null,
"e": 27068,
"s": 27005,
"text": "The do construct allows a structured form of iteration.Syntax:"
},
{
"code": null,
"e": 27261,
"s": 27068,
"text": "(do ((variable_1 value_1 updated-value_1)\n (variable_2 value_2 updated-value_2)\n (variable_3 value_3 updated-value_3)\n ...)\n (test return_value)\n (s-expressions)\n)"
},
{
"code": null,
"e": 27268,
"s": 27261,
"text": "Where,"
},
{
"code": null,
"e": 27297,
"s": 27268,
"text": "variable_1 => First variable"
},
{
"code": null,
"e": 27341,
"s": 27297,
"text": "value_1 => Initial Value for first variable"
},
{
"code": null,
"e": 27417,
"s": 27341,
"text": "updated-value_1 => Specifies how to update variable_1 after each iteration."
},
{
"code": null,
"e": 27447,
"s": 27417,
"text": "variable_2 => Second variable"
},
{
"code": null,
"e": 27492,
"s": 27447,
"text": "value_2 => Initial Value for second variable"
},
{
"code": null,
"e": 27596,
"s": 27492,
"text": "updated-value_2 => Specifies how to update variable_2 after each iteration. ... similar till variable_n"
},
{
"code": null,
"e": 27651,
"s": 27596,
"text": "test => Condition that specifies when to stop the loop"
},
{
"code": null,
"e": 27714,
"s": 27651,
"text": "return value => Value that is returned at the end of iteration"
},
{
"code": null,
"e": 27780,
"s": 27714,
"text": "expressions => Other statements to be executed in every iteration"
},
{
"code": null,
"e": 28293,
"s": 27780,
"text": "The initial values of each variable are evaluated and bound to the respective variable. The updated value in every clause is with respect to an optional update statement which indicates how to update variables in each iteration.The test is performed on each iteration and if the test expression results in a non-null or true value, the returned value is evaluated and returned.If the last optional s-expression(s) are specified, they’re executed on every iteration while test expression results are true.Example:"
},
{
"code": null,
"e": 28298,
"s": 28293,
"text": "Lisp"
},
{
"code": "(do ((a 0 (+ 2 a)) (b 20 ( - b 2))) ((= a b)(- a b)) (format t \"~% a = ~d b = ~d\" a b))(write-line \"\")",
"e": 28408,
"s": 28298,
"text": null
},
{
"code": null,
"e": 28416,
"s": 28408,
"text": "Output:"
},
{
"code": null,
"e": 28477,
"s": 28416,
"text": "The dolist construct provides an easy way to traverse lists."
},
{
"code": null,
"e": 28485,
"s": 28477,
"text": "Syntax:"
},
{
"code": null,
"e": 28537,
"s": 28485,
"text": "(dolist (listItemVariable list)\n (expressions)\n) "
},
{
"code": null,
"e": 28544,
"s": 28537,
"text": "Where,"
},
{
"code": null,
"e": 28617,
"s": 28544,
"text": "listItemVariable => Holds value of each list item during every iteration"
},
{
"code": null,
"e": 28642,
"s": 28617,
"text": "list => List to traverse"
},
{
"code": null,
"e": 28702,
"s": 28642,
"text": "expressions => Statements to be executed in every iteration"
},
{
"code": null,
"e": 28711,
"s": 28702,
"text": "Example:"
},
{
"code": null,
"e": 28716,
"s": 28711,
"text": "Lisp"
},
{
"code": "(defvar nums `(9 5 2 3))(dolist (item nums) (print item))(write-line \"\")",
"e": 28790,
"s": 28716,
"text": null
},
{
"code": null,
"e": 28798,
"s": 28790,
"text": "Output:"
},
{
"code": null,
"e": 28810,
"s": 28798,
"text": "References:"
},
{
"code": null,
"e": 28842,
"s": 28810,
"text": "Official docs for loops in LISP"
},
{
"code": null,
"e": 28854,
"s": 28842,
"text": "LISP-Basics"
},
{
"code": null,
"e": 28861,
"s": 28854,
"text": "Picked"
},
{
"code": null,
"e": 28866,
"s": 28861,
"text": "LISP"
},
{
"code": null,
"e": 28964,
"s": 28866,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28987,
"s": 28964,
"text": "Cond Construct in LISP"
},
{
"code": null,
"e": 29006,
"s": 28987,
"text": "Data Types in LISP"
},
{
"code": null,
"e": 29058,
"s": 29006,
"text": "LISP - Comparison Operators on Characters & Strings"
},
{
"code": null,
"e": 29084,
"s": 29058,
"text": "Mapping Functions in LISP"
},
{
"code": null,
"e": 29100,
"s": 29084,
"text": "Symbols in LISP"
},
{
"code": null,
"e": 29123,
"s": 29100,
"text": "Case Construct in LISP"
},
{
"code": null,
"e": 29144,
"s": 29123,
"text": "Do Construct in LISP"
},
{
"code": null,
"e": 29167,
"s": 29144,
"text": "Property Lists in LISP"
},
{
"code": null,
"e": 29194,
"s": 29167,
"text": "Naming Conventions in LISP"
}
] |
D3.js axis.tickValues() Function - GeeksforGeeks | 07 Aug, 2020
The d3.axis.tickValues() Function in D3.js is used to generate ticks at specific values. This function returns the current tick values, which defaults to null.
Syntax:
axis.tickValues([values])
Parameters: This function accepts the following parameters.
values: This parameter is used for ticks rather than using the scale’s automatic tick generator
Return Value: This function returns ticks at specific values.
Note: The explicit tick values take precedent over the tick arguments set by axis.tickArguments.
Below programs illustrate the d3.axis.tickValues() function in D3.js:
Example 1:
<!DOCTYPE html> <html> <head> <title> D3.js | D3.axis.tickValues() Function </title> <script type="text/javascript" src="https://d3js.org/d3.v4.min.js"> </script> <style> svg text { fill: green; font: 15px sans-serif; text-anchor: center; } </style> </head> <body> <script> var width = 400, height = 400; var svg = d3.select("body") .append("svg") .attr("width", width) .attr("height", height); var xscale = d3.scaleLinear() .domain([0, 10]) .range([0, width - 60]); var x_axis = d3.axisBottom(xscale) .tickValues([2, 4, 6, 7]); var xAxisTranslate = height / 2; svg.append("g") .attr("transform", "translate(50, " + xAxisTranslate + ")") .call(x_axis) </script> </body> </html>
Output:
Example 2:
<!DOCTYPE html> <html> <head> <title> D3.js | D3.axis.tickValues() Function </title> <script type="text/javascript" src="https://d3js.org/d3.v4.min.js"> </script> <style> svg text { fill: green; font: 15px sans-serif; text-anchor: center; } </style> </head> <body> <script> var width = 400, height = 400; var svg = d3.select("body") .append("svg") .attr("width", width) .attr("height", height); var yscale = d3.scaleLinear() .domain([0, 1]) .range([height - 50, 0]); var y_axis = d3.axisLeft() .scale(yscale).tickValues([ 0, 0.5, 1]); svg.append("g") .attr("transform", "translate(100, 20)") .call(y_axis) </script></body> </html>
Output:
D3.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills | [
{
"code": null,
"e": 25883,
"s": 25855,
"text": "\n07 Aug, 2020"
},
{
"code": null,
"e": 26043,
"s": 25883,
"text": "The d3.axis.tickValues() Function in D3.js is used to generate ticks at specific values. This function returns the current tick values, which defaults to null."
},
{
"code": null,
"e": 26051,
"s": 26043,
"text": "Syntax:"
},
{
"code": null,
"e": 26077,
"s": 26051,
"text": "axis.tickValues([values])"
},
{
"code": null,
"e": 26137,
"s": 26077,
"text": "Parameters: This function accepts the following parameters."
},
{
"code": null,
"e": 26233,
"s": 26137,
"text": "values: This parameter is used for ticks rather than using the scale’s automatic tick generator"
},
{
"code": null,
"e": 26295,
"s": 26233,
"text": "Return Value: This function returns ticks at specific values."
},
{
"code": null,
"e": 26392,
"s": 26295,
"text": "Note: The explicit tick values take precedent over the tick arguments set by axis.tickArguments."
},
{
"code": null,
"e": 26462,
"s": 26392,
"text": "Below programs illustrate the d3.axis.tickValues() function in D3.js:"
},
{
"code": null,
"e": 26473,
"s": 26462,
"text": "Example 1:"
},
{
"code": "<!DOCTYPE html> <html> <head> <title> D3.js | D3.axis.tickValues() Function </title> <script type=\"text/javascript\" src=\"https://d3js.org/d3.v4.min.js\"> </script> <style> svg text { fill: green; font: 15px sans-serif; text-anchor: center; } </style> </head> <body> <script> var width = 400, height = 400; var svg = d3.select(\"body\") .append(\"svg\") .attr(\"width\", width) .attr(\"height\", height); var xscale = d3.scaleLinear() .domain([0, 10]) .range([0, width - 60]); var x_axis = d3.axisBottom(xscale) .tickValues([2, 4, 6, 7]); var xAxisTranslate = height / 2; svg.append(\"g\") .attr(\"transform\", \"translate(50, \" + xAxisTranslate + \")\") .call(x_axis) </script> </body> </html>",
"e": 27419,
"s": 26473,
"text": null
},
{
"code": null,
"e": 27427,
"s": 27419,
"text": "Output:"
},
{
"code": null,
"e": 27438,
"s": 27427,
"text": "Example 2:"
},
{
"code": "<!DOCTYPE html> <html> <head> <title> D3.js | D3.axis.tickValues() Function </title> <script type=\"text/javascript\" src=\"https://d3js.org/d3.v4.min.js\"> </script> <style> svg text { fill: green; font: 15px sans-serif; text-anchor: center; } </style> </head> <body> <script> var width = 400, height = 400; var svg = d3.select(\"body\") .append(\"svg\") .attr(\"width\", width) .attr(\"height\", height); var yscale = d3.scaleLinear() .domain([0, 1]) .range([height - 50, 0]); var y_axis = d3.axisLeft() .scale(yscale).tickValues([ 0, 0.5, 1]); svg.append(\"g\") .attr(\"transform\", \"translate(100, 20)\") .call(y_axis) </script></body> </html>",
"e": 28317,
"s": 27438,
"text": null
},
{
"code": null,
"e": 28325,
"s": 28317,
"text": "Output:"
},
{
"code": null,
"e": 28331,
"s": 28325,
"text": "D3.js"
},
{
"code": null,
"e": 28342,
"s": 28331,
"text": "JavaScript"
},
{
"code": null,
"e": 28359,
"s": 28342,
"text": "Web Technologies"
},
{
"code": null,
"e": 28457,
"s": 28359,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28497,
"s": 28457,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28542,
"s": 28497,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28603,
"s": 28542,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 28675,
"s": 28603,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 28727,
"s": 28675,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 28767,
"s": 28727,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28800,
"s": 28767,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28845,
"s": 28800,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28888,
"s": 28845,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Factorial program in Java without using recursion. | Following is the required program.
Live Demo
public class Tester {
static int factorial(int n) {
if (n == 0)
return 1;
else
return (n * factorial(n - 1));
}
public static void main(String args[]) {
int i, fact = 1;
int number = 5;
fact = factorial(number);
System.out.println(number + "! = " + fact);
}
}
5! = 120 | [
{
"code": null,
"e": 1097,
"s": 1062,
"text": "Following is the required program."
},
{
"code": null,
"e": 1107,
"s": 1097,
"text": "Live Demo"
},
{
"code": null,
"e": 1433,
"s": 1107,
"text": "public class Tester {\n static int factorial(int n) {\n if (n == 0)\n return 1;\n else\n return (n * factorial(n - 1));\n }\n public static void main(String args[]) {\n int i, fact = 1;\n int number = 5;\n fact = factorial(number);\n System.out.println(number + \"! = \" + fact);\n }\n}"
},
{
"code": null,
"e": 1442,
"s": 1433,
"text": "5! = 120"
}
] |
How to BIND all the packages in a collection COLLA to a plan PLANA? | The package is a database object which contains the SQL statements from DBRM in a DB2-optimized form.
The collection is a group of packages using which we can segregate the DB2 packages belonging to the different applications. For example, in a production environment for a Telecom company, we can have different collections for order handling, billing and customer service.
The package or group of packages (collections) are binded into a plan. A plan is an executable object which contains the DB2 access paths of all the SQL queries within it. We can bind a package into a plan directly or we can first generate a collection using package(s) and then bind it to a plan.
Using the below JCL step we can directly bind all the packages inside a collection using a single BIND command.
//BIND EXEC PGM=IKJEFT01
//STEPLIB DD DSN=DIS.TEST.LOADLIB,DISP=SHR
//SYSOUT DD SYSOUT=*
//SYSTSIN DD *
DSN SYSTEM(TB3)
BIND PLAN(PLANA) -
PKLIST(COLLA.*) -
/*
We can use BIND PLAN and PKLIST parameters for this purpose. The argument COLLA.* will take into account all the packages in collection COLLA and bind it to plan PLAN A. | [
{
"code": null,
"e": 1164,
"s": 1062,
"text": "The package is a database object which contains the SQL statements from DBRM in a DB2-optimized form."
},
{
"code": null,
"e": 1437,
"s": 1164,
"text": "The collection is a group of packages using which we can segregate the DB2 packages belonging to the different applications. For example, in a production environment for a Telecom company, we can have different collections for order handling, billing and customer service."
},
{
"code": null,
"e": 1735,
"s": 1437,
"text": "The package or group of packages (collections) are binded into a plan. A plan is an executable object which contains the DB2 access paths of all the SQL queries within it. We can bind a package into a plan directly or we can first generate a collection using package(s) and then bind it to a plan."
},
{
"code": null,
"e": 1847,
"s": 1735,
"text": "Using the below JCL step we can directly bind all the packages inside a collection using a single BIND command."
},
{
"code": null,
"e": 2007,
"s": 1847,
"text": "//BIND EXEC PGM=IKJEFT01\n//STEPLIB DD DSN=DIS.TEST.LOADLIB,DISP=SHR\n//SYSOUT DD SYSOUT=*\n//SYSTSIN DD *\nDSN SYSTEM(TB3)\nBIND PLAN(PLANA) -\nPKLIST(COLLA.*) -\n/*"
},
{
"code": null,
"e": 2177,
"s": 2007,
"text": "We can use BIND PLAN and PKLIST parameters for this purpose. The argument COLLA.* will take into account all the packages in collection COLLA and bind it to plan PLAN A."
}
] |
Convert list-like column elements to separate rows in Pandas - GeeksforGeeks | 12 Nov, 2020
A dataframe is a tabular structure where data is arranged in rows and columns. Often while working with real data, columns having list-like elements are encountered. List-like means that the elements are of a form that can be easily converted into a list. In this article, we will see various approaches to convert list-like column elements to separate rows.
First, let us create a data frame which we will use for all the approaches.
Python
# import Pandas libraryimport pandas as pd # create dataframe with a column (names) having list-like elementsdata = {'id': [1, 2, 3], 'names': ["Tom,Rick,Hardy", "Ritu,Shalini,Anjana", "Ali,Amir"]} df = pd.DataFrame(data) print(df)
Output:
Method 1: Using Pandas melt function
First, convert each string of names to a list.
Python
# assign the names series to a variable with # the same name and create a list columndf_melt = df.assign(names=df.names.str.split(",")) print(df_melt)
Output:
Now, split names column list values (columns with individual list values are created).
Python
df_melt.names.apply(pd.Series)
Merge the new columns with the rest of the data set.
Python
df_melt.names.apply(pd.Series) \ .merge(df_melt, right_index = True, left_index = True)
Drop the old names list column and then transform the new columns into separate rows using the melt function.
Python
df_melt.names.apply(pd.Series) \ .merge(df_melt, right_index = True, left_index = True) \ .drop(["names"], axis = 1) \ .melt(id_vars = ['id'], value_name = "names")
Now combine the above steps. Also, an additional column ‘variable’ containing the ids of the numeric columns is seen. This column is dropped and empty values are removed.
Python
df_melt = df.assign(names=df.names.str.split(","))df_melt = df_melt.names.apply(pd.Series) \ .merge(df_melt, right_index=True, left_index=True) \ .drop(["names"], axis=1) \ .melt(id_vars=['id'], value_name="names") \ .drop("variable", axis=1) \ .dropna() print(df_melt)
Output:
Method 2: Using Pandas stack function
Convert each string of names to a list then use the pandas stack() function for pivoting the columns to index.
Python
# convert names series into string using str method# split the string on basis of comma delimiter# convert the series into list using to_list method# use stack to finally convert list elements to rows df_stack = pd.DataFrame(df.names.str.split(",").to_list(), index=df.id).stack()df_stack = df_stack.reset_index(["id"])df_stack.columns = ["id", "names"] print(df_stack)
Output:
Method 3: Using Pandas explode function
Convert each string of names to a list and use Pandas explode() function to split the list by each element and create a new row for each of them.
Python
# use explode to convert list elements to rowsdf_explode = df.assign(names=df.names.str.split(",")).explode('names') print(df_explode)
Output:
Python pandas-dataFrame
Python Pandas-exercise
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Python | os.path.join() method
Defaultdict in Python
Selecting rows in pandas DataFrame based on conditions
Python | Get unique values from a list
Create a directory in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 24292,
"s": 24264,
"text": "\n12 Nov, 2020"
},
{
"code": null,
"e": 24651,
"s": 24292,
"text": "A dataframe is a tabular structure where data is arranged in rows and columns. Often while working with real data, columns having list-like elements are encountered. List-like means that the elements are of a form that can be easily converted into a list. In this article, we will see various approaches to convert list-like column elements to separate rows."
},
{
"code": null,
"e": 24727,
"s": 24651,
"text": "First, let us create a data frame which we will use for all the approaches."
},
{
"code": null,
"e": 24734,
"s": 24727,
"text": "Python"
},
{
"code": "# import Pandas libraryimport pandas as pd # create dataframe with a column (names) having list-like elementsdata = {'id': [1, 2, 3], 'names': [\"Tom,Rick,Hardy\", \"Ritu,Shalini,Anjana\", \"Ali,Amir\"]} df = pd.DataFrame(data) print(df)",
"e": 24976,
"s": 24734,
"text": null
},
{
"code": null,
"e": 24984,
"s": 24976,
"text": "Output:"
},
{
"code": null,
"e": 25021,
"s": 24984,
"text": "Method 1: Using Pandas melt function"
},
{
"code": null,
"e": 25068,
"s": 25021,
"text": "First, convert each string of names to a list."
},
{
"code": null,
"e": 25075,
"s": 25068,
"text": "Python"
},
{
"code": "# assign the names series to a variable with # the same name and create a list columndf_melt = df.assign(names=df.names.str.split(\",\")) print(df_melt)",
"e": 25227,
"s": 25075,
"text": null
},
{
"code": null,
"e": 25235,
"s": 25227,
"text": "Output:"
},
{
"code": null,
"e": 25322,
"s": 25235,
"text": "Now, split names column list values (columns with individual list values are created)."
},
{
"code": null,
"e": 25329,
"s": 25322,
"text": "Python"
},
{
"code": "df_melt.names.apply(pd.Series)",
"e": 25360,
"s": 25329,
"text": null
},
{
"code": null,
"e": 25413,
"s": 25360,
"text": "Merge the new columns with the rest of the data set."
},
{
"code": null,
"e": 25420,
"s": 25413,
"text": "Python"
},
{
"code": "df_melt.names.apply(pd.Series) \\ .merge(df_melt, right_index = True, left_index = True)",
"e": 25511,
"s": 25420,
"text": null
},
{
"code": null,
"e": 25621,
"s": 25511,
"text": "Drop the old names list column and then transform the new columns into separate rows using the melt function."
},
{
"code": null,
"e": 25628,
"s": 25621,
"text": "Python"
},
{
"code": "df_melt.names.apply(pd.Series) \\ .merge(df_melt, right_index = True, left_index = True) \\ .drop([\"names\"], axis = 1) \\ .melt(id_vars = ['id'], value_name = \"names\")",
"e": 25799,
"s": 25628,
"text": null
},
{
"code": null,
"e": 25970,
"s": 25799,
"text": "Now combine the above steps. Also, an additional column ‘variable’ containing the ids of the numeric columns is seen. This column is dropped and empty values are removed."
},
{
"code": null,
"e": 25977,
"s": 25970,
"text": "Python"
},
{
"code": "df_melt = df.assign(names=df.names.str.split(\",\"))df_melt = df_melt.names.apply(pd.Series) \\ .merge(df_melt, right_index=True, left_index=True) \\ .drop([\"names\"], axis=1) \\ .melt(id_vars=['id'], value_name=\"names\") \\ .drop(\"variable\", axis=1) \\ .dropna() print(df_melt)",
"e": 26263,
"s": 25977,
"text": null
},
{
"code": null,
"e": 26271,
"s": 26263,
"text": "Output:"
},
{
"code": null,
"e": 26309,
"s": 26271,
"text": "Method 2: Using Pandas stack function"
},
{
"code": null,
"e": 26421,
"s": 26309,
"text": "Convert each string of names to a list then use the pandas stack() function for pivoting the columns to index. "
},
{
"code": null,
"e": 26428,
"s": 26421,
"text": "Python"
},
{
"code": "# convert names series into string using str method# split the string on basis of comma delimiter# convert the series into list using to_list method# use stack to finally convert list elements to rows df_stack = pd.DataFrame(df.names.str.split(\",\").to_list(), index=df.id).stack()df_stack = df_stack.reset_index([\"id\"])df_stack.columns = [\"id\", \"names\"] print(df_stack)",
"e": 26800,
"s": 26428,
"text": null
},
{
"code": null,
"e": 26808,
"s": 26800,
"text": "Output:"
},
{
"code": null,
"e": 26848,
"s": 26808,
"text": "Method 3: Using Pandas explode function"
},
{
"code": null,
"e": 26994,
"s": 26848,
"text": "Convert each string of names to a list and use Pandas explode() function to split the list by each element and create a new row for each of them."
},
{
"code": null,
"e": 27001,
"s": 26994,
"text": "Python"
},
{
"code": "# use explode to convert list elements to rowsdf_explode = df.assign(names=df.names.str.split(\",\")).explode('names') print(df_explode)",
"e": 27137,
"s": 27001,
"text": null
},
{
"code": null,
"e": 27145,
"s": 27137,
"text": "Output:"
},
{
"code": null,
"e": 27169,
"s": 27145,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 27192,
"s": 27169,
"text": "Python Pandas-exercise"
},
{
"code": null,
"e": 27206,
"s": 27192,
"text": "Python-pandas"
},
{
"code": null,
"e": 27213,
"s": 27206,
"text": "Python"
},
{
"code": null,
"e": 27311,
"s": 27213,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27343,
"s": 27311,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27385,
"s": 27343,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27441,
"s": 27385,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27483,
"s": 27441,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27514,
"s": 27483,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27536,
"s": 27514,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27591,
"s": 27536,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 27630,
"s": 27591,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27659,
"s": 27630,
"text": "Create a directory in Python"
}
] |
C# Program to Check a Specified Type is a Value Type or Not - GeeksforGeeks | 23 Nov, 2021
In C#, the value type represents a sequence of bits. It is not a class or an interface, it is referred to as a struct or enum(a special case of value type). So to check whether the specified type is Value Type or not we use the IsValueType property of the Type class. It is a read-only property. It will return true if the type is Value Type. Otherwise, it will return false. It will return true for enumeration but not return true for Enum type.
Syntax:
public bool IsValueType { get; }
Example 1:
C#
// C# program to check whether the specified// type is a value type or notusing System;using System.Reflection; // Declare a structurestruct myStructure{ // Declaring a method public static void display() { Console.WriteLine("Hello! GeeksforGeeks"); }} // Declare a classpublic class Geeks{ // Declaring a method public static void show() { Console.WriteLine("Hey! GeeksforGeeks"); } } public class GFG{ // Driver classpublic static void Main(string[] args){ // Checking the given type is a value type or not // Using IsValueType Property Console.WriteLine(typeof(myStructure).IsValueType); Console.WriteLine(typeof(Geeks).IsValueType);}}
Output:
True
False
Example 2:
C#
// C# program to check whether the specified// type is a value type or notusing System;using System.Reflection; // Declare a structurestruct myGFG{ // Declaring a method public static void display() { Console.WriteLine("Welcome to GeeksforGeeks"); }} public class GFG{ // Driver classpublic static void Main(string[] args){ // Checking the given type is a value type or not // Using IsValueType Property if (typeof(myGFG).IsValueType == true) { Console.WriteLine("The given type is value type"); } else { Console.WriteLine("The given type is not a value type"); }}}
Output:
The given type is value type
Picked
C#
C# Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Extension Method in C#
HashSet in C# with Examples
Top 50 C# Interview Questions & Answers
C# | How to insert an element in an Array?
C# | Inheritance
Convert String to Character Array in C#
Socket Programming in C#
Program to Print a New Line in C#
Getting a Month Name Using Month Number in C#
Program to find absolute value of a given number | [
{
"code": null,
"e": 24302,
"s": 24274,
"text": "\n23 Nov, 2021"
},
{
"code": null,
"e": 24749,
"s": 24302,
"text": "In C#, the value type represents a sequence of bits. It is not a class or an interface, it is referred to as a struct or enum(a special case of value type). So to check whether the specified type is Value Type or not we use the IsValueType property of the Type class. It is a read-only property. It will return true if the type is Value Type. Otherwise, it will return false. It will return true for enumeration but not return true for Enum type."
},
{
"code": null,
"e": 24757,
"s": 24749,
"text": "Syntax:"
},
{
"code": null,
"e": 24790,
"s": 24757,
"text": "public bool IsValueType { get; }"
},
{
"code": null,
"e": 24801,
"s": 24790,
"text": "Example 1:"
},
{
"code": null,
"e": 24804,
"s": 24801,
"text": "C#"
},
{
"code": "// C# program to check whether the specified// type is a value type or notusing System;using System.Reflection; // Declare a structurestruct myStructure{ // Declaring a method public static void display() { Console.WriteLine(\"Hello! GeeksforGeeks\"); }} // Declare a classpublic class Geeks{ // Declaring a method public static void show() { Console.WriteLine(\"Hey! GeeksforGeeks\"); } } public class GFG{ // Driver classpublic static void Main(string[] args){ // Checking the given type is a value type or not // Using IsValueType Property Console.WriteLine(typeof(myStructure).IsValueType); Console.WriteLine(typeof(Geeks).IsValueType);}}",
"e": 25526,
"s": 24804,
"text": null
},
{
"code": null,
"e": 25534,
"s": 25526,
"text": "Output:"
},
{
"code": null,
"e": 25545,
"s": 25534,
"text": "True\nFalse"
},
{
"code": null,
"e": 25556,
"s": 25545,
"text": "Example 2:"
},
{
"code": null,
"e": 25559,
"s": 25556,
"text": "C#"
},
{
"code": "// C# program to check whether the specified// type is a value type or notusing System;using System.Reflection; // Declare a structurestruct myGFG{ // Declaring a method public static void display() { Console.WriteLine(\"Welcome to GeeksforGeeks\"); }} public class GFG{ // Driver classpublic static void Main(string[] args){ // Checking the given type is a value type or not // Using IsValueType Property if (typeof(myGFG).IsValueType == true) { Console.WriteLine(\"The given type is value type\"); } else { Console.WriteLine(\"The given type is not a value type\"); }}}",
"e": 26202,
"s": 25559,
"text": null
},
{
"code": null,
"e": 26210,
"s": 26202,
"text": "Output:"
},
{
"code": null,
"e": 26239,
"s": 26210,
"text": "The given type is value type"
},
{
"code": null,
"e": 26246,
"s": 26239,
"text": "Picked"
},
{
"code": null,
"e": 26249,
"s": 26246,
"text": "C#"
},
{
"code": null,
"e": 26261,
"s": 26249,
"text": "C# Programs"
},
{
"code": null,
"e": 26359,
"s": 26261,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26368,
"s": 26359,
"text": "Comments"
},
{
"code": null,
"e": 26381,
"s": 26368,
"text": "Old Comments"
},
{
"code": null,
"e": 26404,
"s": 26381,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 26432,
"s": 26404,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 26472,
"s": 26432,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 26515,
"s": 26472,
"text": "C# | How to insert an element in an Array?"
},
{
"code": null,
"e": 26532,
"s": 26515,
"text": "C# | Inheritance"
},
{
"code": null,
"e": 26572,
"s": 26532,
"text": "Convert String to Character Array in C#"
},
{
"code": null,
"e": 26597,
"s": 26572,
"text": "Socket Programming in C#"
},
{
"code": null,
"e": 26631,
"s": 26597,
"text": "Program to Print a New Line in C#"
},
{
"code": null,
"e": 26677,
"s": 26631,
"text": "Getting a Month Name Using Month Number in C#"
}
] |
ProressBar in Android using Jetpack Compose - GeeksforGeeks | 25 Feb, 2021
ProressBar is a material UI component in Android which is used to indicate the progress of any process such as for showing any downloading procedure, as a placeholder screen, and many more. In this article, we will take a look at the implementation of ProressBar in Android using Jetpack Compose.
Attributes
Uses
Step 1: Create a New Project
To create a new project in the Android Studio Canary Version please refer to How to Create a new Project in Android Studio Canary Version with Jetpack Compose.
Step 2: Working with the MainActivity.kt file
Navigate to the app > java > your app’s package name and open the MainActivity.kt file. Inside that file add the below code to it. Comments are added inside the code to understand the code in more detail.
Kotlin
import android.graphics.drawable.shapes.Shapeimport android.media.Imageimport android.os.Bundleimport android.widget.Toastimport androidx.appcompat.app.AppCompatActivityimport androidx.compose.foundation.*import androidx.compose.foundation.Textimport androidx.compose.foundation.layout.*import androidx.compose.foundation.shape.CircleShapeimport androidx.compose.foundation.shape.RoundedCornerShapeimport androidx.compose.foundation.text.KeyboardOptionsimport androidx.compose.material.*import androidx.compose.material.Iconimport androidx.compose.material.icons.Iconsimport androidx.compose.material.icons.filled.AccountCircleimport androidx.compose.material.icons.filled.Infoimport androidx.compose.material.icons.filled.Menuimport androidx.compose.material.icons.filled.Phoneimport androidx.compose.runtime.*import androidx.compose.runtime.savedinstancestate.savedInstanceStateimport androidx.compose.ui.Alignmentimport androidx.compose.ui.layout.ContentScaleimport androidx.compose.ui.platform.setContentimport androidx.compose.ui.res.imageResourceimport androidx.compose.ui.tooling.preview.Previewimport androidx.compose.ui.unit.dpimport com.example.gfgapp.ui.GFGAppThemeimport androidx.compose.ui.Modifierimport androidx.compose.ui.draw.clipimport androidx.compose.ui.graphics.Colorimport androidx.compose.ui.graphics.SolidColorimport androidx.compose.ui.platform.ContextAmbientimport androidx.compose.ui.platform.testTagimport androidx.compose.ui.res.colorResourceimport androidx.compose.ui.semantics.SemanticsProperties.ToggleableStateimport androidx.compose.ui.text.TextStyleimport androidx.compose.ui.text.font.FontFamilyimport androidx.compose.ui.text.input.*import androidx.compose.ui.unit.Dpimport androidx.compose.ui.unit.TextUnit class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { Column { // in below line we are calling // a progress bar method. SimpleCircularProgressComponent() } } }} @Preview(showBackground = true)@Composablefun DefaultPreview() { GFGAppTheme { SimpleCircularProgressComponent(); }} @Composablefun SimpleCircularProgressComponent() { // CircularProgressIndicator is generally used // at the loading screen and it indicates that // some progress is going on so please wait. Column( // we are using column to align our // imageview to center of the screen. modifier = Modifier.fillMaxWidth().fillMaxHeight(), // below line is used for specifying // vertical arrangement. verticalArrangement = Arrangement.Center, // below line is used for specifying // horizontal arrangement. horizontalAlignment = Alignment.CenterHorizontally, ) { // below line is use to display // a circular progress bar. CircularProgressIndicator( // below line is use to add padding // to our progress bar. modifier = Modifier.padding(16.dp), // below line is use to add color // to our progress bar. color = colorResource(id = R.color.purple_200), // below line is use to add stroke // width to our progress bar. strokeWidth = Dp(value = 4F) ) }}
Now run your app and see the output of the app.
Android-Jetpack
Technical Scripter 2020
Android
Kotlin
Technical Scripter
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Flutter - Custom Bottom Navigation Bar
How to View and Locate SQLite Database in Android Studio?
How to Read Data from SQLite Database in Android?
Retrofit with Kotlin Coroutine in Android
Android Listview in Java with Example
Android UI Layouts
Kotlin Array
Retrofit with Kotlin Coroutine in Android
Kotlin Setters and Getters
MVP (Model View Presenter) Architecture Pattern in Android with Example | [
{
"code": null,
"e": 25056,
"s": 25028,
"text": "\n25 Feb, 2021"
},
{
"code": null,
"e": 25353,
"s": 25056,
"text": "ProressBar is a material UI component in Android which is used to indicate the progress of any process such as for showing any downloading procedure, as a placeholder screen, and many more. In this article, we will take a look at the implementation of ProressBar in Android using Jetpack Compose."
},
{
"code": null,
"e": 25364,
"s": 25353,
"text": "Attributes"
},
{
"code": null,
"e": 25369,
"s": 25364,
"text": "Uses"
},
{
"code": null,
"e": 25398,
"s": 25369,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 25558,
"s": 25398,
"text": "To create a new project in the Android Studio Canary Version please refer to How to Create a new Project in Android Studio Canary Version with Jetpack Compose."
},
{
"code": null,
"e": 25604,
"s": 25558,
"text": "Step 2: Working with the MainActivity.kt file"
},
{
"code": null,
"e": 25809,
"s": 25604,
"text": "Navigate to the app > java > your app’s package name and open the MainActivity.kt file. Inside that file add the below code to it. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 25816,
"s": 25809,
"text": "Kotlin"
},
{
"code": "import android.graphics.drawable.shapes.Shapeimport android.media.Imageimport android.os.Bundleimport android.widget.Toastimport androidx.appcompat.app.AppCompatActivityimport androidx.compose.foundation.*import androidx.compose.foundation.Textimport androidx.compose.foundation.layout.*import androidx.compose.foundation.shape.CircleShapeimport androidx.compose.foundation.shape.RoundedCornerShapeimport androidx.compose.foundation.text.KeyboardOptionsimport androidx.compose.material.*import androidx.compose.material.Iconimport androidx.compose.material.icons.Iconsimport androidx.compose.material.icons.filled.AccountCircleimport androidx.compose.material.icons.filled.Infoimport androidx.compose.material.icons.filled.Menuimport androidx.compose.material.icons.filled.Phoneimport androidx.compose.runtime.*import androidx.compose.runtime.savedinstancestate.savedInstanceStateimport androidx.compose.ui.Alignmentimport androidx.compose.ui.layout.ContentScaleimport androidx.compose.ui.platform.setContentimport androidx.compose.ui.res.imageResourceimport androidx.compose.ui.tooling.preview.Previewimport androidx.compose.ui.unit.dpimport com.example.gfgapp.ui.GFGAppThemeimport androidx.compose.ui.Modifierimport androidx.compose.ui.draw.clipimport androidx.compose.ui.graphics.Colorimport androidx.compose.ui.graphics.SolidColorimport androidx.compose.ui.platform.ContextAmbientimport androidx.compose.ui.platform.testTagimport androidx.compose.ui.res.colorResourceimport androidx.compose.ui.semantics.SemanticsProperties.ToggleableStateimport androidx.compose.ui.text.TextStyleimport androidx.compose.ui.text.font.FontFamilyimport androidx.compose.ui.text.input.*import androidx.compose.ui.unit.Dpimport androidx.compose.ui.unit.TextUnit class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { Column { // in below line we are calling // a progress bar method. SimpleCircularProgressComponent() } } }} @Preview(showBackground = true)@Composablefun DefaultPreview() { GFGAppTheme { SimpleCircularProgressComponent(); }} @Composablefun SimpleCircularProgressComponent() { // CircularProgressIndicator is generally used // at the loading screen and it indicates that // some progress is going on so please wait. Column( // we are using column to align our // imageview to center of the screen. modifier = Modifier.fillMaxWidth().fillMaxHeight(), // below line is used for specifying // vertical arrangement. verticalArrangement = Arrangement.Center, // below line is used for specifying // horizontal arrangement. horizontalAlignment = Alignment.CenterHorizontally, ) { // below line is use to display // a circular progress bar. CircularProgressIndicator( // below line is use to add padding // to our progress bar. modifier = Modifier.padding(16.dp), // below line is use to add color // to our progress bar. color = colorResource(id = R.color.purple_200), // below line is use to add stroke // width to our progress bar. strokeWidth = Dp(value = 4F) ) }}",
"e": 29229,
"s": 25816,
"text": null
},
{
"code": null,
"e": 29278,
"s": 29229,
"text": "Now run your app and see the output of the app. "
},
{
"code": null,
"e": 29294,
"s": 29278,
"text": "Android-Jetpack"
},
{
"code": null,
"e": 29318,
"s": 29294,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 29326,
"s": 29318,
"text": "Android"
},
{
"code": null,
"e": 29333,
"s": 29326,
"text": "Kotlin"
},
{
"code": null,
"e": 29352,
"s": 29333,
"text": "Technical Scripter"
},
{
"code": null,
"e": 29360,
"s": 29352,
"text": "Android"
},
{
"code": null,
"e": 29458,
"s": 29360,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29497,
"s": 29458,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 29555,
"s": 29497,
"text": "How to View and Locate SQLite Database in Android Studio?"
},
{
"code": null,
"e": 29605,
"s": 29555,
"text": "How to Read Data from SQLite Database in Android?"
},
{
"code": null,
"e": 29647,
"s": 29605,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 29685,
"s": 29647,
"text": "Android Listview in Java with Example"
},
{
"code": null,
"e": 29704,
"s": 29685,
"text": "Android UI Layouts"
},
{
"code": null,
"e": 29717,
"s": 29704,
"text": "Kotlin Array"
},
{
"code": null,
"e": 29759,
"s": 29717,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 29786,
"s": 29759,
"text": "Kotlin Setters and Getters"
}
] |
HTTP basic authentication URL with “@” in password. | We can do HTTP basic authentication URL with @ in password. We have to pass the credentials appended with the URL. The username and password must be added with the format − https://username:password@URL.
Let us make an attempt to handle the below browser authentication.
Once the User Name and Password are entered correctly and the OK button is clicked, we should be navigated to the actual page with the text Congratulations! You must have the proper credentials.
https://username:password@URL
https://admin:[email protected]/basic_auth
Here, the username and password value is admin.
URL is www.the-internet.herokuapp.com/basic_auth
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class BrwAuthnPopup{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver",
"C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
String a = "admin";
// appending username, password with URL
String s = "https://" + a + ":" + a + "@" +
"the-internet.herokuapp.com/basic_auth";
driver.get(s);
// identify text
String m = driver.findElement(By.cssSelector("p")).getText();
System.out.println("Text is: " + m);
driver.close();
}
} | [
{
"code": null,
"e": 1266,
"s": 1062,
"text": "We can do HTTP basic authentication URL with @ in password. We have to pass the credentials appended with the URL. The username and password must be added with the format − https://username:password@URL."
},
{
"code": null,
"e": 1333,
"s": 1266,
"text": "Let us make an attempt to handle the below browser authentication."
},
{
"code": null,
"e": 1528,
"s": 1333,
"text": "Once the User Name and Password are entered correctly and the OK button is clicked, we should be navigated to the actual page with the text Congratulations! You must have the proper credentials."
},
{
"code": null,
"e": 1616,
"s": 1528,
"text": "https://username:password@URL\nhttps://admin:[email protected]/basic_auth"
},
{
"code": null,
"e": 1664,
"s": 1616,
"text": "Here, the username and password value is admin."
},
{
"code": null,
"e": 1713,
"s": 1664,
"text": "URL is www.the-internet.herokuapp.com/basic_auth"
},
{
"code": null,
"e": 2457,
"s": 1713,
"text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.chrome.ChromeDriver;\npublic class BrwAuthnPopup{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.chrome.driver\",\n \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n String a = \"admin\";\n // appending username, password with URL\n String s = \"https://\" + a + \":\" + a + \"@\" +\n \"the-internet.herokuapp.com/basic_auth\";\n driver.get(s);\n // identify text\n String m = driver.findElement(By.cssSelector(\"p\")).getText();\n System.out.println(\"Text is: \" + m);\n driver.close();\n }\n}"
}
] |
Java.io.FilterOutputStream Class in Java - GeeksforGeeks | 12 Oct, 2021
java.io.FilterInputStream Class in Java
Java.io.FilterOutputStream class is the superclass of all those classes which filters output streams. The write() method of FilterOutputStream Class filters the data and write it to the underlying stream, filtering which is done depending on the Streams.
Declaration :
public class FilterOutputStream
extends OutputStream
Constructors :
FilterOutputStream(OutputStream geekout) : Creates an output stream filter.
Methods:
write(int arg) : java.io.FilterOutputStream.write(int arg) writes specified byte to the Output stream. Syntax :
public void write(int arg)
Parameters :
arg : Source Bytes
Return :
void
Exception :
In case any I/O error occurs.
Implementation :
Java
// Java program illustrating the working of work(int arg)// methodimport java.io.*;import java.lang.*; public class NewClass{ public static void main(String[] args) throws IOException { // OutputStream, FileInputStream & FilterOutputStream // initially null OutputStream geek_out = null; FilterOutputStream geek_filter = null; // FileInputStream used here FileInputStream geekinput = null; char c; int a; try { // create output streams geek_out = new FileOutputStream("GEEKS.txt"); geek_filter = new FilterOutputStream(geek_out); // write(int arg) : Used to write 'M' in the file // - "ABC.txt" geek_filter.write(77); // Flushes the Output Stream geek_filter.flush(); // Creating Input Stream geekinput = new FileInputStream("GEEKS.txt"); // read() method of FileInputStream : // reading the bytes and converting next bytes to int a = geekinput.read(); /* Since, read() converts bytes to int, so we convert int to char for our program output*/ c = (char)a; // print character System.out.println("Character written by" + " FilterOutputStream : " + c); } catch(IOException except) { // if any I/O error occurs System.out.print("Write Not working properly"); } finally{ // releases any system resources associated with // the stream if (geek_out != null) geek_out.close(); if (geek_filter != null) geek_filter.close(); } }}
Note : In the program I have used GEEKS.txt file, the program will create a new file of the name given in the code and write in it. Output :
Character written by FilterOutputStream : M
write(byte[] buffer) : java.io.FilterOutputStream.write(byte[] buffer) writes ‘arg.length’ byte to the Output stream. Syntax :
public void write(byte[] arg)
Parameters :
buffer : Source Buffer to be written to the Output Stream
Return :
void
Exception :
In case any I/O error occurs.
Implementation :
Java
// Java program illustrating the working of work(byte// buffer) methodimport java.io.*;import java.lang.*; public class NewClass{ public static void main(String[] args) throws IOException { // OutputStream, FileInputStream & FilterOutputStream // initially null OutputStream geek_out = null; FilterOutputStream geek_filter = null; // FileInputStream used here FileInputStream geekinput = null; byte[] buffer = {77, 79, 72, 73, 84}; char c; int a; try { // create output streams geek_out = new FileOutputStream("ABC.txt"); geek_filter = new FilterOutputStream(geek_out); // writes buffer to the output stream geek_filter.write(buffer); // forces byte contents to written out to the stream geek_filter.flush(); // create input streams geekinput = new FileInputStream("ABC.txt"); while ((a=geekinput.read())!=-1) { // converts integer to the character c = (char)a; // prints System.out.print(c); } } catch(IOException except) { // if any I/O error occurs System.out.print("Write Not working properly"); } finally { // releases any system resources associated // with the stream if (geek_out != null) geek_out.close(); if (geek_filter != null) geek_filter.close(); } }}
Note : In the program I have use GEEKS.txt file, the program will create a new file of the name given in the code and write in it.
Output :
MOHIT
write(byte[] buffer, int offset, int maxlen) : java.io.FilterOutputStream.write(byte[] buffer, int offset, int maxlen) writes maxlen bytes from the specified Buffer starting at offset position to the Output stream.
Syntax :
public void write(write(byte[] buffer, int offset, int maxlen)
Parameters :
buffer : Source Buffer to be written to the Output Stream
Return :
buffer : Source Buffer to be written
offset : Starting offset
maxlen : max no. of bytes to bewriten to the Output Stream
Exception :
In case any I/O error occurs.
flush() : java.io.FilterOutputStream.flush() flushes the Output Stream and no data is allowed to be written to the Stream. Syntax :
public void flush()
Parameters :
------
Return :
void
Exception :
In case any I/O error occurs.
close() : java.io.FilterOutputStream.close() closes the stream and releases all allocated resources to the Stream. Syntax :
public void close()
Parameters :
------
Return :
void
Exception :
In case any I/O error occurs.
Java program illustrating : write(byte[] buffer, int offset, int maxlen), flush(), close() methods
Java
// Java program illustrating the working of// write(byte[] buffer, int offset, int maxlen),// flush(), close() methodimport java.io.*;import java.lang.*; public class NewClass{ public static void main(String[] args) throws IOException { // OutputStream, FileInputStream & FilterOutputStream // initially null OutputStream geek_out = null; FilterOutputStream geek_filter = null; // FileInputStream used here FileInputStream geekinput = null; byte[] buffer = {65, 66, 77, 79, 72, 73, 84}; char c; int a; try { // create output streams geek_out = new FileOutputStream("ABC.txt"); geek_filter = new FilterOutputStream(geek_out); // write(byte[] buffer, int offset, int maxlen) : // writes buffer to the output stream // Here offset = 2, so it won't read first two bytes // then maxlen = 5, so it will print max of 5 characters geek_filter.write(buffer, 2, 5); // forces byte contents to written out to the stream geek_filter.flush(); // create input streams geekinput = new FileInputStream("ABC.txt"); while ((a = geekinput.read())!=-1) { // converts integer to the character c = (char)a; // prints System.out.print(c); } } catch(IOException except) { // if any I/O error occurs System.out.print("Write Not working properly"); } finally { // releases any system resources associated // with the stream if (geek_out != null) geek_out.close(); if (geek_filter != null) geek_filter.close(); } }}
Note : In the program I have use GEEKS.txt file, the program will create a new file of the name given in the code and write in it.
Output :
MOHIT
This article is contributed by Mohit Gupta . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [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.
adnanirshad158
simranarora5sos
sooda367
gulshankumarar231
Java-I/O
java-stream
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Different ways of Reading a text file in Java
Stream In Java
Constructors in Java
Generics in Java
Exceptions in Java
Functional Interfaces in Java
Comparator Interface in Java with Examples
Commonly Asked Java Programming Interview Questions | Set 2
HashMap get() Method in Java
Strings in Java | [
{
"code": null,
"e": 23948,
"s": 23920,
"text": "\n12 Oct, 2021"
},
{
"code": null,
"e": 23988,
"s": 23948,
"text": "java.io.FilterInputStream Class in Java"
},
{
"code": null,
"e": 24243,
"s": 23988,
"text": "Java.io.FilterOutputStream class is the superclass of all those classes which filters output streams. The write() method of FilterOutputStream Class filters the data and write it to the underlying stream, filtering which is done depending on the Streams."
},
{
"code": null,
"e": 24258,
"s": 24243,
"text": "Declaration : "
},
{
"code": null,
"e": 24314,
"s": 24258,
"text": "public class FilterOutputStream\n extends OutputStream"
},
{
"code": null,
"e": 24331,
"s": 24314,
"text": "Constructors : "
},
{
"code": null,
"e": 24407,
"s": 24331,
"text": "FilterOutputStream(OutputStream geekout) : Creates an output stream filter."
},
{
"code": null,
"e": 24417,
"s": 24407,
"text": "Methods: "
},
{
"code": null,
"e": 24530,
"s": 24417,
"text": "write(int arg) : java.io.FilterOutputStream.write(int arg) writes specified byte to the Output stream. Syntax : "
},
{
"code": null,
"e": 24648,
"s": 24530,
"text": "public void write(int arg)\nParameters : \narg : Source Bytes\nReturn :\nvoid\nException : \nIn case any I/O error occurs."
},
{
"code": null,
"e": 24665,
"s": 24648,
"text": "Implementation :"
},
{
"code": null,
"e": 24670,
"s": 24665,
"text": "Java"
},
{
"code": "// Java program illustrating the working of work(int arg)// methodimport java.io.*;import java.lang.*; public class NewClass{ public static void main(String[] args) throws IOException { // OutputStream, FileInputStream & FilterOutputStream // initially null OutputStream geek_out = null; FilterOutputStream geek_filter = null; // FileInputStream used here FileInputStream geekinput = null; char c; int a; try { // create output streams geek_out = new FileOutputStream(\"GEEKS.txt\"); geek_filter = new FilterOutputStream(geek_out); // write(int arg) : Used to write 'M' in the file // - \"ABC.txt\" geek_filter.write(77); // Flushes the Output Stream geek_filter.flush(); // Creating Input Stream geekinput = new FileInputStream(\"GEEKS.txt\"); // read() method of FileInputStream : // reading the bytes and converting next bytes to int a = geekinput.read(); /* Since, read() converts bytes to int, so we convert int to char for our program output*/ c = (char)a; // print character System.out.println(\"Character written by\" + \" FilterOutputStream : \" + c); } catch(IOException except) { // if any I/O error occurs System.out.print(\"Write Not working properly\"); } finally{ // releases any system resources associated with // the stream if (geek_out != null) geek_out.close(); if (geek_filter != null) geek_filter.close(); } }}",
"e": 26448,
"s": 24670,
"text": null
},
{
"code": null,
"e": 26590,
"s": 26448,
"text": "Note : In the program I have used GEEKS.txt file, the program will create a new file of the name given in the code and write in it. Output : "
},
{
"code": null,
"e": 26634,
"s": 26590,
"text": "Character written by FilterOutputStream : M"
},
{
"code": null,
"e": 26762,
"s": 26634,
"text": "write(byte[] buffer) : java.io.FilterOutputStream.write(byte[] buffer) writes ‘arg.length’ byte to the Output stream. Syntax : "
},
{
"code": null,
"e": 26922,
"s": 26762,
"text": "public void write(byte[] arg)\nParameters : \nbuffer : Source Buffer to be written to the Output Stream\nReturn :\nvoid\nException : \nIn case any I/O error occurs."
},
{
"code": null,
"e": 26939,
"s": 26922,
"text": "Implementation :"
},
{
"code": null,
"e": 26944,
"s": 26939,
"text": "Java"
},
{
"code": "// Java program illustrating the working of work(byte// buffer) methodimport java.io.*;import java.lang.*; public class NewClass{ public static void main(String[] args) throws IOException { // OutputStream, FileInputStream & FilterOutputStream // initially null OutputStream geek_out = null; FilterOutputStream geek_filter = null; // FileInputStream used here FileInputStream geekinput = null; byte[] buffer = {77, 79, 72, 73, 84}; char c; int a; try { // create output streams geek_out = new FileOutputStream(\"ABC.txt\"); geek_filter = new FilterOutputStream(geek_out); // writes buffer to the output stream geek_filter.write(buffer); // forces byte contents to written out to the stream geek_filter.flush(); // create input streams geekinput = new FileInputStream(\"ABC.txt\"); while ((a=geekinput.read())!=-1) { // converts integer to the character c = (char)a; // prints System.out.print(c); } } catch(IOException except) { // if any I/O error occurs System.out.print(\"Write Not working properly\"); } finally { // releases any system resources associated // with the stream if (geek_out != null) geek_out.close(); if (geek_filter != null) geek_filter.close(); } }}",
"e": 28488,
"s": 26944,
"text": null
},
{
"code": null,
"e": 28619,
"s": 28488,
"text": "Note : In the program I have use GEEKS.txt file, the program will create a new file of the name given in the code and write in it."
},
{
"code": null,
"e": 28628,
"s": 28619,
"text": "Output :"
},
{
"code": null,
"e": 28634,
"s": 28628,
"text": "MOHIT"
},
{
"code": null,
"e": 28849,
"s": 28634,
"text": "write(byte[] buffer, int offset, int maxlen) : java.io.FilterOutputStream.write(byte[] buffer, int offset, int maxlen) writes maxlen bytes from the specified Buffer starting at offset position to the Output stream."
},
{
"code": null,
"e": 28859,
"s": 28849,
"text": "Syntax : "
},
{
"code": null,
"e": 29169,
"s": 28859,
"text": "public void write(write(byte[] buffer, int offset, int maxlen)\nParameters : \nbuffer : Source Buffer to be written to the Output Stream\nReturn :\nbuffer : Source Buffer to be written\noffset : Starting offset \nmaxlen : max no. of bytes to bewriten to the Output Stream\nException : \nIn case any I/O error occurs."
},
{
"code": null,
"e": 29302,
"s": 29169,
"text": "flush() : java.io.FilterOutputStream.flush() flushes the Output Stream and no data is allowed to be written to the Stream. Syntax : "
},
{
"code": null,
"e": 29401,
"s": 29302,
"text": "public void flush()\nParameters : \n------\nReturn :\nvoid\nException : \nIn case any I/O error occurs."
},
{
"code": null,
"e": 29526,
"s": 29401,
"text": "close() : java.io.FilterOutputStream.close() closes the stream and releases all allocated resources to the Stream. Syntax : "
},
{
"code": null,
"e": 29625,
"s": 29526,
"text": "public void close()\nParameters : \n------\nReturn :\nvoid\nException : \nIn case any I/O error occurs."
},
{
"code": null,
"e": 29724,
"s": 29625,
"text": "Java program illustrating : write(byte[] buffer, int offset, int maxlen), flush(), close() methods"
},
{
"code": null,
"e": 29729,
"s": 29724,
"text": "Java"
},
{
"code": "// Java program illustrating the working of// write(byte[] buffer, int offset, int maxlen),// flush(), close() methodimport java.io.*;import java.lang.*; public class NewClass{ public static void main(String[] args) throws IOException { // OutputStream, FileInputStream & FilterOutputStream // initially null OutputStream geek_out = null; FilterOutputStream geek_filter = null; // FileInputStream used here FileInputStream geekinput = null; byte[] buffer = {65, 66, 77, 79, 72, 73, 84}; char c; int a; try { // create output streams geek_out = new FileOutputStream(\"ABC.txt\"); geek_filter = new FilterOutputStream(geek_out); // write(byte[] buffer, int offset, int maxlen) : // writes buffer to the output stream // Here offset = 2, so it won't read first two bytes // then maxlen = 5, so it will print max of 5 characters geek_filter.write(buffer, 2, 5); // forces byte contents to written out to the stream geek_filter.flush(); // create input streams geekinput = new FileInputStream(\"ABC.txt\"); while ((a = geekinput.read())!=-1) { // converts integer to the character c = (char)a; // prints System.out.print(c); } } catch(IOException except) { // if any I/O error occurs System.out.print(\"Write Not working properly\"); } finally { // releases any system resources associated // with the stream if (geek_out != null) geek_out.close(); if (geek_filter != null) geek_filter.close(); } }}",
"e": 31581,
"s": 29729,
"text": null
},
{
"code": null,
"e": 31712,
"s": 31581,
"text": "Note : In the program I have use GEEKS.txt file, the program will create a new file of the name given in the code and write in it."
},
{
"code": null,
"e": 31722,
"s": 31712,
"text": "Output : "
},
{
"code": null,
"e": 31728,
"s": 31722,
"text": "MOHIT"
},
{
"code": null,
"e": 32149,
"s": 31728,
"text": "This article is contributed by Mohit Gupta . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [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": 32164,
"s": 32149,
"text": "adnanirshad158"
},
{
"code": null,
"e": 32180,
"s": 32164,
"text": "simranarora5sos"
},
{
"code": null,
"e": 32189,
"s": 32180,
"text": "sooda367"
},
{
"code": null,
"e": 32207,
"s": 32189,
"text": "gulshankumarar231"
},
{
"code": null,
"e": 32216,
"s": 32207,
"text": "Java-I/O"
},
{
"code": null,
"e": 32228,
"s": 32216,
"text": "java-stream"
},
{
"code": null,
"e": 32233,
"s": 32228,
"text": "Java"
},
{
"code": null,
"e": 32238,
"s": 32233,
"text": "Java"
},
{
"code": null,
"e": 32336,
"s": 32238,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32345,
"s": 32336,
"text": "Comments"
},
{
"code": null,
"e": 32358,
"s": 32345,
"text": "Old Comments"
},
{
"code": null,
"e": 32404,
"s": 32358,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 32419,
"s": 32404,
"text": "Stream In Java"
},
{
"code": null,
"e": 32440,
"s": 32419,
"text": "Constructors in Java"
},
{
"code": null,
"e": 32457,
"s": 32440,
"text": "Generics in Java"
},
{
"code": null,
"e": 32476,
"s": 32457,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 32506,
"s": 32476,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 32549,
"s": 32506,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 32609,
"s": 32549,
"text": "Commonly Asked Java Programming Interview Questions | Set 2"
},
{
"code": null,
"e": 32638,
"s": 32609,
"text": "HashMap get() Method in Java"
}
] |
Formatting day of week in EEEE format in Java | EEEEE format is used in Java Date to format day of week like Monday, Tuesday, Wednesday, etc. Let us use it −
// displaying day of week
SimpleDateFormat simpleformat = new SimpleDateFormat("EEEE");
String strDayofWeek = simpleformat.format(new Date());
System.out.println("Day of Week = "+strDayofWeek);
Above, we have used the SimpleDateFormat class, therefore the following package is imported −
import java.text.SimpleDateFormat;
The following is an example −
Live Demo
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Calendar;
public class Demo {
public static void main(String[] args) throws Exception {
// displaying current date and time
Calendar cal = Calendar.getInstance();
SimpleDateFormat simpleformat = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss Z");
System.out.println("Today's date and time = "+simpleformat.format(cal.getTime()));
// displaying date
simpleformat = new SimpleDateFormat("dd/MMMM/yyyy");
String str = simpleformat.format(new Date());
System.out.println("Current Date = "+str);
// displaying day of week
simpleformat = new SimpleDateFormat("EEEE");
String strDayofWeek = simpleformat.format(new Date());
System.out.println("Day of Week = "+strDayofWeek);
// current time
simpleformat = new SimpleDateFormat("HH.mm.ss Z");
String strTime = simpleformat.format(new Date());
System.out.println("Current Time = "+strTime);
}
}
Today's date and time = Mon, 26 Nov 2018 09:40:25 +0000
Current Date = 26/November/2018
Day of Week = Monday
Current Time = 09.40.25 +0000 | [
{
"code": null,
"e": 1172,
"s": 1062,
"text": "EEEEE format is used in Java Date to format day of week like Monday, Tuesday, Wednesday, etc. Let us use it −"
},
{
"code": null,
"e": 1366,
"s": 1172,
"text": "// displaying day of week\nSimpleDateFormat simpleformat = new SimpleDateFormat(\"EEEE\");\nString strDayofWeek = simpleformat.format(new Date());\nSystem.out.println(\"Day of Week = \"+strDayofWeek);"
},
{
"code": null,
"e": 1460,
"s": 1366,
"text": "Above, we have used the SimpleDateFormat class, therefore the following package is imported −"
},
{
"code": null,
"e": 1495,
"s": 1460,
"text": "import java.text.SimpleDateFormat;"
},
{
"code": null,
"e": 1525,
"s": 1495,
"text": "The following is an example −"
},
{
"code": null,
"e": 1536,
"s": 1525,
"text": " Live Demo"
},
{
"code": null,
"e": 2573,
"s": 1536,
"text": "import java.text.Format;\nimport java.text.SimpleDateFormat;\nimport java.util.Date;\nimport java.util.Calendar;\npublic class Demo {\n public static void main(String[] args) throws Exception {\n // displaying current date and time\n Calendar cal = Calendar.getInstance();\n SimpleDateFormat simpleformat = new SimpleDateFormat(\"E, dd MMM yyyy HH:mm:ss Z\");\n System.out.println(\"Today's date and time = \"+simpleformat.format(cal.getTime()));\n // displaying date\n simpleformat = new SimpleDateFormat(\"dd/MMMM/yyyy\");\n String str = simpleformat.format(new Date());\n System.out.println(\"Current Date = \"+str);\n // displaying day of week\n simpleformat = new SimpleDateFormat(\"EEEE\");\n String strDayofWeek = simpleformat.format(new Date());\n System.out.println(\"Day of Week = \"+strDayofWeek);\n // current time\n simpleformat = new SimpleDateFormat(\"HH.mm.ss Z\");\n String strTime = simpleformat.format(new Date());\n System.out.println(\"Current Time = \"+strTime);\n }\n}"
},
{
"code": null,
"e": 2712,
"s": 2573,
"text": "Today's date and time = Mon, 26 Nov 2018 09:40:25 +0000\nCurrent Date = 26/November/2018\nDay of Week = Monday\nCurrent Time = 09.40.25 +0000"
}
] |
IS MISSING and IS NOT MISSING Operators in SAS Programming - GeeksforGeeks | 23 Jul, 2019
IS MISSING Operator: Selecting Missing ValuesTask 1: Suppose you want to select only those observations in which students did not fill their section information.data readin;input name $ Section $ Score;cards;Raj A 80Atul . 77Priya B 45Sandeep A 95Rahul . 84Shreya . 44;run; data readin1;set readin;where Section is missing;run;Output:Where Section is missing => This would tell SAS to select missing values for variable SECTION.IS NOT MISSING Operator: Selecting Non-Missing ValuesTask 2: Suppose you want to select only those observations in which students filled their section information.data readin;input name $ Section $ Score;cards;Raj A 80Atul . 77Priya B 45Sandeep A 95Rahul . 84Shreya C 44;run; data readin1;set readin;where Section is not missing;run;Output:Where Section is not missing => This would tell SAS to select non-missing values.The NOT operator can be used with WHERE statement in many other ways:where the section is not missing and the score is missing;where not (score in (34, 44, 84));where not (Score between 50 and 90);where NOT(Section EQ “A”);
IS MISSING Operator: Selecting Missing ValuesTask 1: Suppose you want to select only those observations in which students did not fill their section information.data readin;input name $ Section $ Score;cards;Raj A 80Atul . 77Priya B 45Sandeep A 95Rahul . 84Shreya . 44;run; data readin1;set readin;where Section is missing;run;Output:Where Section is missing => This would tell SAS to select missing values for variable SECTION.
Task 1: Suppose you want to select only those observations in which students did not fill their section information.
data readin;input name $ Section $ Score;cards;Raj A 80Atul . 77Priya B 45Sandeep A 95Rahul . 84Shreya . 44;run; data readin1;set readin;where Section is missing;run;
Output:
Where Section is missing => This would tell SAS to select missing values for variable SECTION.
IS NOT MISSING Operator: Selecting Non-Missing ValuesTask 2: Suppose you want to select only those observations in which students filled their section information.data readin;input name $ Section $ Score;cards;Raj A 80Atul . 77Priya B 45Sandeep A 95Rahul . 84Shreya C 44;run; data readin1;set readin;where Section is not missing;run;Output:Where Section is not missing => This would tell SAS to select non-missing values.The NOT operator can be used with WHERE statement in many other ways:where the section is not missing and the score is missing;where not (score in (34, 44, 84));where not (Score between 50 and 90);where NOT(Section EQ “A”);
Task 2: Suppose you want to select only those observations in which students filled their section information.
data readin;input name $ Section $ Score;cards;Raj A 80Atul . 77Priya B 45Sandeep A 95Rahul . 84Shreya C 44;run; data readin1;set readin;where Section is not missing;run;
Output:
Where Section is not missing => This would tell SAS to select non-missing values.
The NOT operator can be used with WHERE statement in many other ways:
where the section is not missing and the score is missing;
where the section is not missing and the score is missing;
where not (score in (34, 44, 84));
where not (score in (34, 44, 84));
where not (Score between 50 and 90);
where not (Score between 50 and 90);
where NOT(Section EQ “A”);
where NOT(Section EQ “A”);
SAS Programming
Programming Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 10 Programming Languages to Learn in 2022
Shallow Copy and Deep Copy in C++
C# | Data Types
Difference between Shallow and Deep copy of a class
Advantages and Disadvantages of OOP
Kotlin Array
Java Swing | JComboBox with examples
Prolog | An Introduction
Program to calculate Electricity Bill
Difference between while and do-while loop in C, C++, Java | [
{
"code": null,
"e": 24868,
"s": 24840,
"text": "\n23 Jul, 2019"
},
{
"code": null,
"e": 25945,
"s": 24868,
"text": "IS MISSING Operator: Selecting Missing ValuesTask 1: Suppose you want to select only those observations in which students did not fill their section information.data readin;input name $ Section $ Score;cards;Raj A 80Atul . 77Priya B 45Sandeep A 95Rahul . 84Shreya . 44;run; data readin1;set readin;where Section is missing;run;Output:Where Section is missing => This would tell SAS to select missing values for variable SECTION.IS NOT MISSING Operator: Selecting Non-Missing ValuesTask 2: Suppose you want to select only those observations in which students filled their section information.data readin;input name $ Section $ Score;cards;Raj A 80Atul . 77Priya B 45Sandeep A 95Rahul . 84Shreya C 44;run; data readin1;set readin;where Section is not missing;run;Output:Where Section is not missing => This would tell SAS to select non-missing values.The NOT operator can be used with WHERE statement in many other ways:where the section is not missing and the score is missing;where not (score in (34, 44, 84));where not (Score between 50 and 90);where NOT(Section EQ “A”);"
},
{
"code": null,
"e": 26376,
"s": 25945,
"text": "IS MISSING Operator: Selecting Missing ValuesTask 1: Suppose you want to select only those observations in which students did not fill their section information.data readin;input name $ Section $ Score;cards;Raj A 80Atul . 77Priya B 45Sandeep A 95Rahul . 84Shreya . 44;run; data readin1;set readin;where Section is missing;run;Output:Where Section is missing => This would tell SAS to select missing values for variable SECTION."
},
{
"code": null,
"e": 26493,
"s": 26376,
"text": "Task 1: Suppose you want to select only those observations in which students did not fill their section information."
},
{
"code": "data readin;input name $ Section $ Score;cards;Raj A 80Atul . 77Priya B 45Sandeep A 95Rahul . 84Shreya . 44;run; data readin1;set readin;where Section is missing;run;",
"e": 26662,
"s": 26493,
"text": null
},
{
"code": null,
"e": 26670,
"s": 26662,
"text": "Output:"
},
{
"code": null,
"e": 26765,
"s": 26670,
"text": "Where Section is missing => This would tell SAS to select missing values for variable SECTION."
},
{
"code": null,
"e": 27412,
"s": 26765,
"text": "IS NOT MISSING Operator: Selecting Non-Missing ValuesTask 2: Suppose you want to select only those observations in which students filled their section information.data readin;input name $ Section $ Score;cards;Raj A 80Atul . 77Priya B 45Sandeep A 95Rahul . 84Shreya C 44;run; data readin1;set readin;where Section is not missing;run;Output:Where Section is not missing => This would tell SAS to select non-missing values.The NOT operator can be used with WHERE statement in many other ways:where the section is not missing and the score is missing;where not (score in (34, 44, 84));where not (Score between 50 and 90);where NOT(Section EQ “A”);"
},
{
"code": null,
"e": 27523,
"s": 27412,
"text": "Task 2: Suppose you want to select only those observations in which students filled their section information."
},
{
"code": "data readin;input name $ Section $ Score;cards;Raj A 80Atul . 77Priya B 45Sandeep A 95Rahul . 84Shreya C 44;run; data readin1;set readin;where Section is not missing;run;",
"e": 27696,
"s": 27523,
"text": null
},
{
"code": null,
"e": 27704,
"s": 27696,
"text": "Output:"
},
{
"code": null,
"e": 27786,
"s": 27704,
"text": "Where Section is not missing => This would tell SAS to select non-missing values."
},
{
"code": null,
"e": 27856,
"s": 27786,
"text": "The NOT operator can be used with WHERE statement in many other ways:"
},
{
"code": null,
"e": 27915,
"s": 27856,
"text": "where the section is not missing and the score is missing;"
},
{
"code": null,
"e": 27974,
"s": 27915,
"text": "where the section is not missing and the score is missing;"
},
{
"code": null,
"e": 28009,
"s": 27974,
"text": "where not (score in (34, 44, 84));"
},
{
"code": null,
"e": 28044,
"s": 28009,
"text": "where not (score in (34, 44, 84));"
},
{
"code": null,
"e": 28081,
"s": 28044,
"text": "where not (Score between 50 and 90);"
},
{
"code": null,
"e": 28118,
"s": 28081,
"text": "where not (Score between 50 and 90);"
},
{
"code": null,
"e": 28145,
"s": 28118,
"text": "where NOT(Section EQ “A”);"
},
{
"code": null,
"e": 28172,
"s": 28145,
"text": "where NOT(Section EQ “A”);"
},
{
"code": null,
"e": 28188,
"s": 28172,
"text": "SAS Programming"
},
{
"code": null,
"e": 28209,
"s": 28188,
"text": "Programming Language"
},
{
"code": null,
"e": 28307,
"s": 28209,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28316,
"s": 28307,
"text": "Comments"
},
{
"code": null,
"e": 28329,
"s": 28316,
"text": "Old Comments"
},
{
"code": null,
"e": 28375,
"s": 28329,
"text": "Top 10 Programming Languages to Learn in 2022"
},
{
"code": null,
"e": 28409,
"s": 28375,
"text": "Shallow Copy and Deep Copy in C++"
},
{
"code": null,
"e": 28425,
"s": 28409,
"text": "C# | Data Types"
},
{
"code": null,
"e": 28477,
"s": 28425,
"text": "Difference between Shallow and Deep copy of a class"
},
{
"code": null,
"e": 28513,
"s": 28477,
"text": "Advantages and Disadvantages of OOP"
},
{
"code": null,
"e": 28526,
"s": 28513,
"text": "Kotlin Array"
},
{
"code": null,
"e": 28563,
"s": 28526,
"text": "Java Swing | JComboBox with examples"
},
{
"code": null,
"e": 28588,
"s": 28563,
"text": "Prolog | An Introduction"
},
{
"code": null,
"e": 28626,
"s": 28588,
"text": "Program to calculate Electricity Bill"
}
] |
Distinct Numbers obtained by generating all permutations of a Binary String - GeeksforGeeks | 08 Jun, 2021
Given a binary string S, the task is to print all distinct decimal numbers that can be obtained by generating all permutations of the binary string.
Examples:
Input: S = “110”Output: {3, 5, 6}Explanation: All possible permutations are {“110”, “101”, “110”, “101”, “011”, “011”}.Equivalent decimal numbers of these binary strings are {6, 5, 6, 5, 3, 3} respectively.Therefore, the distinct decimal numbers obtained are {3, 5, 6}.
Input: S = “1010”Output: {3, 5, 6, 9, 10, 12}
Approach: The problem can be solved using a Set. Follow the steps below to solve the problem:
Convert the given string to a list of characters.
Permute this list using built-in python function itertools. permutations().
Initialize an empty string s.
Traverse the list of permutations and perform the following steps for each permutation:
Iterate over the characters and add them to the string.
Convert this binary string to equivalent decimal.
Insert the current decimal value obtained into a set.
Iterate over the characters and add them to the string.
Convert this binary string to equivalent decimal.
Insert the current decimal value obtained into a set.
Finally, print the numbers present in the set.
Below is the implementation of the above approach:
Python3
# Python3 program for the above approach
from itertools import permutations
# Function to convert binary
# string to equivalent decimal
def binToDec(n):
num = n
dec_value = 0
# Initializing base
# value to 1, i.e 2 ^ 0
base1 = 1
len1 = len(num)
for i in range(len1 - 1, -1, -1):
if (num[i] == '1'):
dec_value += base1
base1 = base1 * 2
# Return the resultant
# decimal number
return dec_value
# Function to print all distinct
# decimals represented by the
# all permutations of the string
def printDecimal(permute):
# Set to store distinct
# decimal representations
allDecimals = set()
# Iterate over all permutations
for i in permute:
# Initialize an empty string
s = ""
# Traverse the list
for j in i:
# Add each element
# to the string
s += j
# Convert the current binary
# representation to decimal
result = binToDec(s)
# Add the current decimal
# value into the set
allDecimals.add(result)
# Print the distinct decimals
print(allDecimals)
# Utility function to print all
# distinct decimal representations
# of all permutations of string
def totalPermutations(string):
# Convert string to list
lis = list(string)
# Built in method to store all
# the permutations of the list
permutelist = permutations(lis)
printDecimal(permutelist)
# Given binary string
binarystring = '1010'
# Function call to print all distinct
# decimal values represented by all
# permutations of the given string
totalPermutations(binarystring)
{3, 5, 6, 9, 10, 12}
Time Complexity: O(N * N!)Auxiliary Space: O(N * N!)
ruhelaa48
base-conversion
binary-string
permutation
python-set
Bit Magic
Combinatorial
Hash
Mathematical
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Set, Clear and Toggle a given bit of a number in C
Check whether K-th bit is set or not
Write an Efficient Method to Check if a Number is Multiple of 3
Reverse actual bits of the given number
Program to find parity
Write a program to print all permutations of a given string
Permutation and Combination in Python
itertools.combinations() module in Python to print all possible combinations
Factorial of a large number
Program to calculate value of nCr | [
{
"code": null,
"e": 24697,
"s": 24666,
"text": " \n08 Jun, 2021\n"
},
{
"code": null,
"e": 24846,
"s": 24697,
"text": "Given a binary string S, the task is to print all distinct decimal numbers that can be obtained by generating all permutations of the binary string."
},
{
"code": null,
"e": 24856,
"s": 24846,
"text": "Examples:"
},
{
"code": null,
"e": 25126,
"s": 24856,
"text": "Input: S = “110”Output: {3, 5, 6}Explanation: All possible permutations are {“110”, “101”, “110”, “101”, “011”, “011”}.Equivalent decimal numbers of these binary strings are {6, 5, 6, 5, 3, 3} respectively.Therefore, the distinct decimal numbers obtained are {3, 5, 6}."
},
{
"code": null,
"e": 25172,
"s": 25126,
"text": "Input: S = “1010”Output: {3, 5, 6, 9, 10, 12}"
},
{
"code": null,
"e": 25266,
"s": 25172,
"text": "Approach: The problem can be solved using a Set. Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 25316,
"s": 25266,
"text": "Convert the given string to a list of characters."
},
{
"code": null,
"e": 25392,
"s": 25316,
"text": "Permute this list using built-in python function itertools. permutations()."
},
{
"code": null,
"e": 25422,
"s": 25392,
"text": "Initialize an empty string s."
},
{
"code": null,
"e": 25673,
"s": 25422,
"text": "Traverse the list of permutations and perform the following steps for each permutation:\n\nIterate over the characters and add them to the string.\nConvert this binary string to equivalent decimal.\nInsert the current decimal value obtained into a set.\n\n"
},
{
"code": null,
"e": 25729,
"s": 25673,
"text": "Iterate over the characters and add them to the string."
},
{
"code": null,
"e": 25779,
"s": 25729,
"text": "Convert this binary string to equivalent decimal."
},
{
"code": null,
"e": 25833,
"s": 25779,
"text": "Insert the current decimal value obtained into a set."
},
{
"code": null,
"e": 25880,
"s": 25833,
"text": "Finally, print the numbers present in the set."
},
{
"code": null,
"e": 25931,
"s": 25880,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 25939,
"s": 25931,
"text": "Python3"
},
{
"code": "\n\n\n\n\n\n\n# Python3 program for the above approach\n \nfrom itertools import permutations\n \n# Function to convert binary\n# string to equivalent decimal\ndef binToDec(n):\n \n num = n\n dec_value = 0\n \n # Initializing base\n # value to 1, i.e 2 ^ 0\n base1 = 1\n \n len1 = len(num)\n \n for i in range(len1 - 1, -1, -1):\n \n if (num[i] == '1'):\n dec_value += base1\n \n base1 = base1 * 2\n \n # Return the resultant\n # decimal number\n return dec_value\n \n# Function to print all distinct\n# decimals represented by the\n# all permutations of the string\ndef printDecimal(permute):\n \n # Set to store distinct\n # decimal representations\n allDecimals = set()\n \n # Iterate over all permutations\n for i in permute:\n \n # Initialize an empty string\n s = \"\"\n \n # Traverse the list\n for j in i:\n \n # Add each element\n # to the string\n s += j\n \n # Convert the current binary\n # representation to decimal\n result = binToDec(s)\n \n # Add the current decimal\n # value into the set\n allDecimals.add(result)\n \n # Print the distinct decimals \n print(allDecimals) \n \n# Utility function to print all\n# distinct decimal representations\n# of all permutations of string\ndef totalPermutations(string):\n \n # Convert string to list\n lis = list(string)\n \n # Built in method to store all\n # the permutations of the list\n permutelist = permutations(lis)\n \n printDecimal(permutelist)\n \n \n# Given binary string\nbinarystring = '1010'\n \n# Function call to print all distinct\n# decimal values represented by all\n# permutations of the given string\ntotalPermutations(binarystring)\n\n\n\n\n\n",
"e": 27772,
"s": 25949,
"text": null
},
{
"code": null,
"e": 27793,
"s": 27772,
"text": "{3, 5, 6, 9, 10, 12}"
},
{
"code": null,
"e": 27848,
"s": 27795,
"text": "Time Complexity: O(N * N!)Auxiliary Space: O(N * N!)"
},
{
"code": null,
"e": 27858,
"s": 27848,
"text": "ruhelaa48"
},
{
"code": null,
"e": 27876,
"s": 27858,
"text": "\nbase-conversion\n"
},
{
"code": null,
"e": 27892,
"s": 27876,
"text": "\nbinary-string\n"
},
{
"code": null,
"e": 27906,
"s": 27892,
"text": "\npermutation\n"
},
{
"code": null,
"e": 27919,
"s": 27906,
"text": "\npython-set\n"
},
{
"code": null,
"e": 27931,
"s": 27919,
"text": "\nBit Magic\n"
},
{
"code": null,
"e": 27947,
"s": 27931,
"text": "\nCombinatorial\n"
},
{
"code": null,
"e": 27954,
"s": 27947,
"text": "\nHash\n"
},
{
"code": null,
"e": 27969,
"s": 27954,
"text": "\nMathematical\n"
},
{
"code": null,
"e": 27979,
"s": 27969,
"text": "\nStrings\n"
},
{
"code": null,
"e": 28184,
"s": 27979,
"text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n "
},
{
"code": null,
"e": 28235,
"s": 28184,
"text": "Set, Clear and Toggle a given bit of a number in C"
},
{
"code": null,
"e": 28272,
"s": 28235,
"text": "Check whether K-th bit is set or not"
},
{
"code": null,
"e": 28336,
"s": 28272,
"text": "Write an Efficient Method to Check if a Number is Multiple of 3"
},
{
"code": null,
"e": 28376,
"s": 28336,
"text": "Reverse actual bits of the given number"
},
{
"code": null,
"e": 28399,
"s": 28376,
"text": "Program to find parity"
},
{
"code": null,
"e": 28460,
"s": 28399,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 28498,
"s": 28460,
"text": "Permutation and Combination in Python"
},
{
"code": null,
"e": 28575,
"s": 28498,
"text": "itertools.combinations() module in Python to print all possible combinations"
},
{
"code": null,
"e": 28603,
"s": 28575,
"text": "Factorial of a large number"
}
] |
Difference between Traditional Collections and Concurrent Collections in java - GeeksforGeeks | 08 Jan, 2018
We all know about about Traditional Collections ( i.e. List, Set, Queue and its implemented Classes) and Concurrent Collection (i.e. ConcurrentMap interface, ConcurrentHashMap class, CopyOnWriteArrayList class etc). In these two Collections, there are few differences like:
Most of the Classes which are present in Traditional Collections (i.e ArrayList, LinkedList, HashMap etc) are non-synchronized in nature and Hence there is no thread-safety. But All the classes present in Concurrent Collections are synchronized in nature. Therefore In Concurrent classes, we dont have to take care about Thread-safety.
While Traditional Collections also have some classes (like Vector, Stack etc) which are synchronized in nature and Traditional Collections also have SynchronizedSet, SynchronizedList, SynchronizedMap methods through which we can get Synchronized version of non-synchronized objects. But these above Synchronized classes are not good in terms of performance because of wide-locking mechanism .Whereas Concurrent Collections classes performance are relatively high than Traditional Collections classes.
In the Traditional Collections, if a thread is iterating a Collection object and if another thread try to add new element in that iterating object simultaneously then we will get RuntimeException ConcurrentModificationException. Whereas In the above case, we will not get any Runtime Exception if we are Working with Concurrent Collections Classes.
Traditional Collections classes is good choice if we are not dealing with thread in our application. whereas because of the Concurrent/Synchronized Collection we can use multiple Threads which are dealing with Collections Object. Therefore Concurrent Collections are best choice if we are dealing Multiple Threads in our application.
// Java program to illustrate Traditional // Collections Problemimport java.util.*;class ConcurrentDemo extends Thread { static ArrayList l = new ArrayList(); public void run() { try { Thread.sleep(2000); } catch (InterruptedException e) { System.out.println("Child Thread" + " going to add element"); } // Child thread trying to add new // element in the Collection object l.add("D"); } public static void main(String[] args) throws InterruptedException { l.add("A"); l.add("B"); l.add("c"); // We create a child thread that is // going to modify ArrayList l. ConcurrentDemo t = new ConcurrentDemo(); t.start(); // Now we iterate through the ArrayList // and get exception. Iterator itr = l.iterator(); while (itr.hasNext()) { String s = (String)itr.next(); System.out.println(s); Thread.sleep(6000); } System.out.println(l); }}
Output:
Exception in thread “main” java.util.ConcurrentModificationException
// Java program to illustrate ConcurrentCollection usesimport java.util.concurrent.CopyOnWriteArrayList;import java.util.*;class ConcurrentDemo extends Thread { static CopyOnWriteArrayList l = new CopyOnWriteArrayList(); public void run() { try { Thread.sleep(2000); } catch (InterruptedException e) { System.out.println("Child Thread" + " going to add element"); } // Child thread trying to add new // element in the Collection object l.add("D"); } public static void main(String[] args) throws InterruptedException { l.add("A"); l.add("B"); l.add("c"); // We create a child thread that is // going to modify ArrayList l. ConcurrentDemo t = new ConcurrentDemo(); t.start(); // Now we iterate through the ArrayList // and get exception. Iterator itr = l.iterator(); while (itr.hasNext()) { String s = (String)itr.next(); System.out.println(s); Thread.sleep(6000); } System.out.println(l); }}
output:
A
B
c
Java-Collections
Java-Multithreading
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Initialize an ArrayList in Java
Interfaces in Java
Object Oriented Programming (OOPs) Concept in Java
ArrayList in Java
How to iterate any Map in Java
Multidimensional Arrays in Java
Singleton Class in Java
Stack Class in Java
Overriding in Java
LinkedList in Java | [
{
"code": null,
"e": 24506,
"s": 24478,
"text": "\n08 Jan, 2018"
},
{
"code": null,
"e": 24780,
"s": 24506,
"text": "We all know about about Traditional Collections ( i.e. List, Set, Queue and its implemented Classes) and Concurrent Collection (i.e. ConcurrentMap interface, ConcurrentHashMap class, CopyOnWriteArrayList class etc). In these two Collections, there are few differences like:"
},
{
"code": null,
"e": 25116,
"s": 24780,
"text": "Most of the Classes which are present in Traditional Collections (i.e ArrayList, LinkedList, HashMap etc) are non-synchronized in nature and Hence there is no thread-safety. But All the classes present in Concurrent Collections are synchronized in nature. Therefore In Concurrent classes, we dont have to take care about Thread-safety."
},
{
"code": null,
"e": 25617,
"s": 25116,
"text": "While Traditional Collections also have some classes (like Vector, Stack etc) which are synchronized in nature and Traditional Collections also have SynchronizedSet, SynchronizedList, SynchronizedMap methods through which we can get Synchronized version of non-synchronized objects. But these above Synchronized classes are not good in terms of performance because of wide-locking mechanism .Whereas Concurrent Collections classes performance are relatively high than Traditional Collections classes."
},
{
"code": null,
"e": 25966,
"s": 25617,
"text": "In the Traditional Collections, if a thread is iterating a Collection object and if another thread try to add new element in that iterating object simultaneously then we will get RuntimeException ConcurrentModificationException. Whereas In the above case, we will not get any Runtime Exception if we are Working with Concurrent Collections Classes."
},
{
"code": null,
"e": 26300,
"s": 25966,
"text": "Traditional Collections classes is good choice if we are not dealing with thread in our application. whereas because of the Concurrent/Synchronized Collection we can use multiple Threads which are dealing with Collections Object. Therefore Concurrent Collections are best choice if we are dealing Multiple Threads in our application."
},
{
"code": "// Java program to illustrate Traditional // Collections Problemimport java.util.*;class ConcurrentDemo extends Thread { static ArrayList l = new ArrayList(); public void run() { try { Thread.sleep(2000); } catch (InterruptedException e) { System.out.println(\"Child Thread\" + \" going to add element\"); } // Child thread trying to add new // element in the Collection object l.add(\"D\"); } public static void main(String[] args) throws InterruptedException { l.add(\"A\"); l.add(\"B\"); l.add(\"c\"); // We create a child thread that is // going to modify ArrayList l. ConcurrentDemo t = new ConcurrentDemo(); t.start(); // Now we iterate through the ArrayList // and get exception. Iterator itr = l.iterator(); while (itr.hasNext()) { String s = (String)itr.next(); System.out.println(s); Thread.sleep(6000); } System.out.println(l); }}",
"e": 27380,
"s": 26300,
"text": null
},
{
"code": null,
"e": 27388,
"s": 27380,
"text": "Output:"
},
{
"code": null,
"e": 27458,
"s": 27388,
"text": "Exception in thread “main” java.util.ConcurrentModificationException\n"
},
{
"code": "// Java program to illustrate ConcurrentCollection usesimport java.util.concurrent.CopyOnWriteArrayList;import java.util.*;class ConcurrentDemo extends Thread { static CopyOnWriteArrayList l = new CopyOnWriteArrayList(); public void run() { try { Thread.sleep(2000); } catch (InterruptedException e) { System.out.println(\"Child Thread\" + \" going to add element\"); } // Child thread trying to add new // element in the Collection object l.add(\"D\"); } public static void main(String[] args) throws InterruptedException { l.add(\"A\"); l.add(\"B\"); l.add(\"c\"); // We create a child thread that is // going to modify ArrayList l. ConcurrentDemo t = new ConcurrentDemo(); t.start(); // Now we iterate through the ArrayList // and get exception. Iterator itr = l.iterator(); while (itr.hasNext()) { String s = (String)itr.next(); System.out.println(s); Thread.sleep(6000); } System.out.println(l); }}",
"e": 28622,
"s": 27458,
"text": null
},
{
"code": null,
"e": 28630,
"s": 28622,
"text": "output:"
},
{
"code": null,
"e": 28637,
"s": 28630,
"text": "A\nB\nc\n"
},
{
"code": null,
"e": 28654,
"s": 28637,
"text": "Java-Collections"
},
{
"code": null,
"e": 28674,
"s": 28654,
"text": "Java-Multithreading"
},
{
"code": null,
"e": 28679,
"s": 28674,
"text": "Java"
},
{
"code": null,
"e": 28684,
"s": 28679,
"text": "Java"
},
{
"code": null,
"e": 28701,
"s": 28684,
"text": "Java-Collections"
},
{
"code": null,
"e": 28799,
"s": 28701,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28831,
"s": 28799,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 28850,
"s": 28831,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 28901,
"s": 28850,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 28919,
"s": 28901,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 28950,
"s": 28919,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 28982,
"s": 28950,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 29006,
"s": 28982,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 29026,
"s": 29006,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 29045,
"s": 29026,
"text": "Overriding in Java"
}
] |
SQL - EXCEPT Clause | The SQL EXCEPT clause/operator is used to combine two SELECT statements and returns rows from the first SELECT statement that are not returned by the second SELECT statement. This means EXCEPT returns only rows, which are not available in the second SELECT statement.
Just as with the UNION operator, the same rules apply when using the EXCEPT operator. MySQL does not support the EXCEPT operator.
The basic syntax of EXCEPT is as follows.
SELECT column1 [, column2 ]
FROM table1 [, table2 ]
[WHERE condition]
EXCEPT
SELECT column1 [, column2 ]
FROM table1 [, table2 ]
[WHERE condition]
Here, the given condition could be any given expression based on your requirement.
Consider the following two tables.
Table 1 − CUSTOMERS Table is as follows.
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Table 2 − ORDERS table is as follows.
+-----+---------------------+-------------+--------+
|OID | DATE | CUSTOMER_ID | AMOUNT |
+-----+---------------------+-------------+--------+
| 102 | 2009-10-08 00:00:00 | 3 | 3000 |
| 100 | 2009-10-08 00:00:00 | 3 | 1500 |
| 101 | 2009-11-20 00:00:00 | 2 | 1560 |
| 103 | 2008-05-20 00:00:00 | 4 | 2060 |
+-----+---------------------+-------------+--------+
Now, let us join these two tables in our SELECT statement as shown below.
SQL> SELECT ID, NAME, AMOUNT, DATE
FROM CUSTOMERS
LEFT JOIN ORDERS
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID
EXCEPT
SELECT ID, NAME, AMOUNT, DATE
FROM CUSTOMERS
RIGHT JOIN ORDERS
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;
This would produce the following result.
+----+---------+--------+---------------------+
| ID | NAME | AMOUNT | DATE |
+----+---------+--------+---------------------+
| 1 | Ramesh | NULL | NULL |
| 5 | Hardik | NULL | NULL |
| 6 | Komal | NULL | NULL |
| 7 | Muffy | NULL | NULL |
+----+---------+--------+---------------------+
42 Lectures
5 hours
Anadi Sharma
14 Lectures
2 hours
Anadi Sharma
44 Lectures
4.5 hours
Anadi Sharma
94 Lectures
7 hours
Abhishek And Pukhraj
80 Lectures
6.5 hours
Oracle Master Training | 150,000+ Students Worldwide
31 Lectures
6 hours
Eduonix Learning Solutions
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2721,
"s": 2453,
"text": "The SQL EXCEPT clause/operator is used to combine two SELECT statements and returns rows from the first SELECT statement that are not returned by the second SELECT statement. This means EXCEPT returns only rows, which are not available in the second SELECT statement."
},
{
"code": null,
"e": 2851,
"s": 2721,
"text": "Just as with the UNION operator, the same rules apply when using the EXCEPT operator. MySQL does not support the EXCEPT operator."
},
{
"code": null,
"e": 2893,
"s": 2851,
"text": "The basic syntax of EXCEPT is as follows."
},
{
"code": null,
"e": 3043,
"s": 2893,
"text": "SELECT column1 [, column2 ]\nFROM table1 [, table2 ]\n[WHERE condition]\n\nEXCEPT\n\nSELECT column1 [, column2 ]\nFROM table1 [, table2 ]\n[WHERE condition]\n"
},
{
"code": null,
"e": 3126,
"s": 3043,
"text": "Here, the given condition could be any given expression based on your requirement."
},
{
"code": null,
"e": 3161,
"s": 3126,
"text": "Consider the following two tables."
},
{
"code": null,
"e": 3202,
"s": 3161,
"text": "Table 1 − CUSTOMERS Table is as follows."
},
{
"code": null,
"e": 3719,
"s": 3202,
"text": "+----+----------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+----------+\n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |\n| 2 | Khilan | 25 | Delhi | 1500.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 6 | Komal | 22 | MP | 4500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+----------+-----+-----------+----------+"
},
{
"code": null,
"e": 3757,
"s": 3719,
"text": "Table 2 − ORDERS table is as follows."
},
{
"code": null,
"e": 4181,
"s": 3757,
"text": "+-----+---------------------+-------------+--------+\n|OID | DATE | CUSTOMER_ID | AMOUNT |\n+-----+---------------------+-------------+--------+\n| 102 | 2009-10-08 00:00:00 | 3 | 3000 |\n| 100 | 2009-10-08 00:00:00 | 3 | 1500 |\n| 101 | 2009-11-20 00:00:00 | 2 | 1560 |\n| 103 | 2008-05-20 00:00:00 | 4 | 2060 |\n+-----+---------------------+-------------+--------+"
},
{
"code": null,
"e": 4255,
"s": 4181,
"text": "Now, let us join these two tables in our SELECT statement as shown below."
},
{
"code": null,
"e": 4490,
"s": 4255,
"text": "SQL> SELECT ID, NAME, AMOUNT, DATE\n FROM CUSTOMERS\n LEFT JOIN ORDERS\n ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID\nEXCEPT\n SELECT ID, NAME, AMOUNT, DATE\n FROM CUSTOMERS\n RIGHT JOIN ORDERS\n ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;"
},
{
"code": null,
"e": 4531,
"s": 4490,
"text": "This would produce the following result."
},
{
"code": null,
"e": 4916,
"s": 4531,
"text": "+----+---------+--------+---------------------+\n| ID | NAME | AMOUNT | DATE |\n+----+---------+--------+---------------------+\n| 1 | Ramesh | NULL | NULL |\n| 5 | Hardik | NULL | NULL |\n| 6 | Komal | NULL | NULL |\n| 7 | Muffy | NULL | NULL |\n+----+---------+--------+---------------------+\n"
},
{
"code": null,
"e": 4949,
"s": 4916,
"text": "\n 42 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 4963,
"s": 4949,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 4996,
"s": 4963,
"text": "\n 14 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 5010,
"s": 4996,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 5045,
"s": 5010,
"text": "\n 44 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 5059,
"s": 5045,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 5092,
"s": 5059,
"text": "\n 94 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 5114,
"s": 5092,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 5149,
"s": 5114,
"text": "\n 80 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 5203,
"s": 5149,
"text": " Oracle Master Training | 150,000+ Students Worldwide"
},
{
"code": null,
"e": 5236,
"s": 5203,
"text": "\n 31 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 5264,
"s": 5236,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 5271,
"s": 5264,
"text": " Print"
},
{
"code": null,
"e": 5282,
"s": 5271,
"text": " Add Notes"
}
] |
Largest perfect cube number in an Array - GeeksforGeeks | 15 Apr, 2021
Given an array of N integers. The task is to find the largest number which is a perfect cube. Print -1 if there is no number that is perfect cube.Examples:
Input : arr[] = {16, 8, 25, 2, 3, 10}
Output : 25
Explanation: 25 is the largest number
that is a perfect cube.
Input : arr[] = {36, 64, 10, 16, 29, 25|
Output : 64
A Simple Solution is to sort the elements and sort the N numbers and start checking from back for a perfect cube number using cbrt() function. The first number from the end which is a perfect cube number is our answer. The complexity of sorting is O(n log n) and of cbrt() function is log n, so at the worst case the complexity is O(n log n).An Efficient Solution is to iterate for all the elements in O(n) and compare every time with the maximum element, and store the maximum of all perfect cubes.Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// CPP program to find the largest perfect// cube number among n numbers #include <bits/stdc++.h>using namespace std; // Function to check if a number// is perfect cube number or notbool checkPerfectcube(int n){ // takes the sqrt of the number int d = cbrt(n); // checks if it is a perfect // cube number if (d * d * d == n) return true; return false;} // Function to find the largest perfect// cube number in the arrayint largestPerfectcubeNumber(int a[], int n){ // stores the maximum of all // perfect cube numbers int maxi = -1; // Traverse all elements in the array for (int i = 0; i < n; i++) { // store the maximum if current // element is a perfect cube if (checkPerfectcube(a[i])) maxi = max(a[i], maxi); } return maxi;} // Driver Codeint main(){ int a[] = { 16, 64, 25, 2, 3, 10 }; int n = sizeof(a) / sizeof(a[0]); cout << largestPerfectcubeNumber(a, n); return 0;}
// Java program to find the largest perfect// cube number among n numbersclass Solution{ // Function to check if a number// is perfect cube number or notstatic boolean checkPerfectcube(int n){ // takes the sqrt of the number int d =(int) Math.cbrt(n); // checks if it is a perfect // cube number if (d * d * d == n) return true; return false;} // Function to find the largest perfect// cube number in the arraystatic int largestPerfectcubeNumber(int a[], int n){ // stores the maximum of all // perfect cube numbers int maxi = -1; // Traverse all elements in the array for (int i = 0; i < n; i++) { // store the maximum if current // element is a perfect cube if (checkPerfectcube(a[i])) maxi = Math.max(a[i], maxi); } return maxi;} // Driver Codepublic static void main(String args[]){ int a[] = { 16, 64, 25, 2, 3, 10 }; int n =a.length; System.out.print(largestPerfectcubeNumber(a, n)); }} //contributed by Arnab Kundu
# Python 3 program to find the largest# perfect cube number among n numbersimport math # Function to check if a number# is perfect cube number or notdef checkPerfectcube(n): # checks if it is a perfect # cube number cube_root = n**(1./3.) if round(cube_root) ** 3 == n: return True else: return False # Function to find the largest perfect# cube number in the arraydef largestPerfectcubeNumber(a, n): # stores the maximum of all # perfect cube numbers maxi = -1 # Traverse all elements in the array for i in range(0, n, 1): # store the maximum if current # element is a perfect cube if (checkPerfectcube(a[i])): maxi = max(a[i], maxi) return maxi; # Driver Codeif __name__ == '__main__': a = [16, 64, 25, 2, 3, 10] n = len(a) print(largestPerfectcubeNumber(a, n)) # This code is contributed by# Surendra_Gangwar
//C# program to find the largest perfect// cube number among n numbersusing System; public class Solution{ // Function to check if a number // is perfect cube number or not static bool checkPerfectcube(int n) { // takes the sqrt of the number int d = (int)Math.Ceiling(Math.Pow(n, (double)1 / 3)); // checks if it is a perfect // cube number if (d * d * d == n) return true; return false; } // Function to find the largest perfect // cube number in the array static int largestPerfectcubeNumber(int []a, int n) { // stores the maximum of all // perfect cube numbers int maxi = -1; // Traverse all elements in the array for (int i = 0; i < n; i++) { // store the maximum if current // element is a perfect cube if (checkPerfectcube(a[i])) maxi = Math.Max(a[i], maxi); } return maxi; } // Driver Code public static void Main() { int []a = { 16, 64, 25, 2, 3, 10 }; int n =a.Length; Console.WriteLine(largestPerfectcubeNumber(a, n)); }} /*This code is contributed by PrinciRaj1992*/
<?php// PHP program to find the largest perfect// cube number among n numbers // Function to check if a number// is perfect cube number or notfunction checkPerfectcube($n){ // takes the sqrt of the number $d = pow($n, (1 / 3)); $d = round($d); // checks if it is a perfect // cube number if ($d * $d * $d == $n) return true; return false;} // Function to find the largest perfect// cube number in the arrayfunction largestPerfectcubeNumber(&$a, $n){ // stores the maximum of all // perfect cube numbers $maxi = -1; // Traverse all elements in the array for ($i = 0; $i < $n; $i++) { // store the maximum if current // element is a perfect cube if (checkPerfectcube($a[$i])) $maxi = max($a[$i], $maxi); } return $maxi;} // Driver Code$a = array( 16, 64, 25, 2, 3, 10 );$n = sizeof($a);echo largestPerfectcubeNumber($a, $n); // This code is contributed by ita_c?>
<script> // Javascript program to find the largest perfect// cube number among n numbers // Function to check if a number// is perfect cube number or notfunction checkPerfectcube(n){ // takes the sqrt of the number let d = parseInt(Math.cbrt(n)); // checks if it is a perfect // cube number if (d * d * d == n) return true; return false;} // Function to find the largest perfect// cube number in the arrayfunction largestPerfectcubeNumber(a, n){ // stores the maximum of all // perfect cube numbers let maxi = -1; // Traverse all elements in the array for (let i = 0; i < n; i++) { // store the maximum if current // element is a perfect cube if (checkPerfectcube(a[i])) maxi = Math.max(a[i], maxi); } return maxi;} // Driver Codelet a = [ 16, 64, 25, 2, 3, 10 ]; let n = a.length; document.write(largestPerfectcubeNumber(a, n)); </script>
64
andrew1234
princiraj1992
SURENDRA_GANGWAR
ukasp
subham348
maths-cube
Technical Scripter 2018
Arrays
Technical Scripter
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Window Sliding Technique
Building Heap from Array
Trapping Rain Water
Reversal algorithm for array rotation
Program to find sum of elements in a given array
Move all negative numbers to beginning and positive to end with constant extra space
Find duplicates in O(n) time and O(1) extra space | Set 1
Count pairs with given sum
Next Greater Element
Remove duplicates from sorted array | [
{
"code": null,
"e": 24821,
"s": 24793,
"text": "\n15 Apr, 2021"
},
{
"code": null,
"e": 24979,
"s": 24821,
"text": "Given an array of N integers. The task is to find the largest number which is a perfect cube. Print -1 if there is no number that is perfect cube.Examples: "
},
{
"code": null,
"e": 25149,
"s": 24979,
"text": "Input : arr[] = {16, 8, 25, 2, 3, 10} \nOutput : 25\nExplanation: 25 is the largest number \nthat is a perfect cube. \n\nInput : arr[] = {36, 64, 10, 16, 29, 25| \nOutput : 64"
},
{
"code": null,
"e": 25703,
"s": 25151,
"text": "A Simple Solution is to sort the elements and sort the N numbers and start checking from back for a perfect cube number using cbrt() function. The first number from the end which is a perfect cube number is our answer. The complexity of sorting is O(n log n) and of cbrt() function is log n, so at the worst case the complexity is O(n log n).An Efficient Solution is to iterate for all the elements in O(n) and compare every time with the maximum element, and store the maximum of all perfect cubes.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 25707,
"s": 25703,
"text": "C++"
},
{
"code": null,
"e": 25712,
"s": 25707,
"text": "Java"
},
{
"code": null,
"e": 25720,
"s": 25712,
"text": "Python3"
},
{
"code": null,
"e": 25723,
"s": 25720,
"text": "C#"
},
{
"code": null,
"e": 25727,
"s": 25723,
"text": "PHP"
},
{
"code": null,
"e": 25738,
"s": 25727,
"text": "Javascript"
},
{
"code": "// CPP program to find the largest perfect// cube number among n numbers #include <bits/stdc++.h>using namespace std; // Function to check if a number// is perfect cube number or notbool checkPerfectcube(int n){ // takes the sqrt of the number int d = cbrt(n); // checks if it is a perfect // cube number if (d * d * d == n) return true; return false;} // Function to find the largest perfect// cube number in the arrayint largestPerfectcubeNumber(int a[], int n){ // stores the maximum of all // perfect cube numbers int maxi = -1; // Traverse all elements in the array for (int i = 0; i < n; i++) { // store the maximum if current // element is a perfect cube if (checkPerfectcube(a[i])) maxi = max(a[i], maxi); } return maxi;} // Driver Codeint main(){ int a[] = { 16, 64, 25, 2, 3, 10 }; int n = sizeof(a) / sizeof(a[0]); cout << largestPerfectcubeNumber(a, n); return 0;}",
"e": 26713,
"s": 25738,
"text": null
},
{
"code": "// Java program to find the largest perfect// cube number among n numbersclass Solution{ // Function to check if a number// is perfect cube number or notstatic boolean checkPerfectcube(int n){ // takes the sqrt of the number int d =(int) Math.cbrt(n); // checks if it is a perfect // cube number if (d * d * d == n) return true; return false;} // Function to find the largest perfect// cube number in the arraystatic int largestPerfectcubeNumber(int a[], int n){ // stores the maximum of all // perfect cube numbers int maxi = -1; // Traverse all elements in the array for (int i = 0; i < n; i++) { // store the maximum if current // element is a perfect cube if (checkPerfectcube(a[i])) maxi = Math.max(a[i], maxi); } return maxi;} // Driver Codepublic static void main(String args[]){ int a[] = { 16, 64, 25, 2, 3, 10 }; int n =a.length; System.out.print(largestPerfectcubeNumber(a, n)); }} //contributed by Arnab Kundu",
"e": 27729,
"s": 26713,
"text": null
},
{
"code": "# Python 3 program to find the largest# perfect cube number among n numbersimport math # Function to check if a number# is perfect cube number or notdef checkPerfectcube(n): # checks if it is a perfect # cube number cube_root = n**(1./3.) if round(cube_root) ** 3 == n: return True else: return False # Function to find the largest perfect# cube number in the arraydef largestPerfectcubeNumber(a, n): # stores the maximum of all # perfect cube numbers maxi = -1 # Traverse all elements in the array for i in range(0, n, 1): # store the maximum if current # element is a perfect cube if (checkPerfectcube(a[i])): maxi = max(a[i], maxi) return maxi; # Driver Codeif __name__ == '__main__': a = [16, 64, 25, 2, 3, 10] n = len(a) print(largestPerfectcubeNumber(a, n)) # This code is contributed by# Surendra_Gangwar",
"e": 28661,
"s": 27729,
"text": null
},
{
"code": "//C# program to find the largest perfect// cube number among n numbersusing System; public class Solution{ // Function to check if a number // is perfect cube number or not static bool checkPerfectcube(int n) { // takes the sqrt of the number int d = (int)Math.Ceiling(Math.Pow(n, (double)1 / 3)); // checks if it is a perfect // cube number if (d * d * d == n) return true; return false; } // Function to find the largest perfect // cube number in the array static int largestPerfectcubeNumber(int []a, int n) { // stores the maximum of all // perfect cube numbers int maxi = -1; // Traverse all elements in the array for (int i = 0; i < n; i++) { // store the maximum if current // element is a perfect cube if (checkPerfectcube(a[i])) maxi = Math.Max(a[i], maxi); } return maxi; } // Driver Code public static void Main() { int []a = { 16, 64, 25, 2, 3, 10 }; int n =a.Length; Console.WriteLine(largestPerfectcubeNumber(a, n)); }} /*This code is contributed by PrinciRaj1992*/",
"e": 29864,
"s": 28661,
"text": null
},
{
"code": "<?php// PHP program to find the largest perfect// cube number among n numbers // Function to check if a number// is perfect cube number or notfunction checkPerfectcube($n){ // takes the sqrt of the number $d = pow($n, (1 / 3)); $d = round($d); // checks if it is a perfect // cube number if ($d * $d * $d == $n) return true; return false;} // Function to find the largest perfect// cube number in the arrayfunction largestPerfectcubeNumber(&$a, $n){ // stores the maximum of all // perfect cube numbers $maxi = -1; // Traverse all elements in the array for ($i = 0; $i < $n; $i++) { // store the maximum if current // element is a perfect cube if (checkPerfectcube($a[$i])) $maxi = max($a[$i], $maxi); } return $maxi;} // Driver Code$a = array( 16, 64, 25, 2, 3, 10 );$n = sizeof($a);echo largestPerfectcubeNumber($a, $n); // This code is contributed by ita_c?>",
"e": 30815,
"s": 29864,
"text": null
},
{
"code": "<script> // Javascript program to find the largest perfect// cube number among n numbers // Function to check if a number// is perfect cube number or notfunction checkPerfectcube(n){ // takes the sqrt of the number let d = parseInt(Math.cbrt(n)); // checks if it is a perfect // cube number if (d * d * d == n) return true; return false;} // Function to find the largest perfect// cube number in the arrayfunction largestPerfectcubeNumber(a, n){ // stores the maximum of all // perfect cube numbers let maxi = -1; // Traverse all elements in the array for (let i = 0; i < n; i++) { // store the maximum if current // element is a perfect cube if (checkPerfectcube(a[i])) maxi = Math.max(a[i], maxi); } return maxi;} // Driver Codelet a = [ 16, 64, 25, 2, 3, 10 ]; let n = a.length; document.write(largestPerfectcubeNumber(a, n)); </script>",
"e": 31738,
"s": 30815,
"text": null
},
{
"code": null,
"e": 31741,
"s": 31738,
"text": "64"
},
{
"code": null,
"e": 31754,
"s": 31743,
"text": "andrew1234"
},
{
"code": null,
"e": 31768,
"s": 31754,
"text": "princiraj1992"
},
{
"code": null,
"e": 31785,
"s": 31768,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 31791,
"s": 31785,
"text": "ukasp"
},
{
"code": null,
"e": 31801,
"s": 31791,
"text": "subham348"
},
{
"code": null,
"e": 31812,
"s": 31801,
"text": "maths-cube"
},
{
"code": null,
"e": 31836,
"s": 31812,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 31843,
"s": 31836,
"text": "Arrays"
},
{
"code": null,
"e": 31862,
"s": 31843,
"text": "Technical Scripter"
},
{
"code": null,
"e": 31869,
"s": 31862,
"text": "Arrays"
},
{
"code": null,
"e": 31967,
"s": 31869,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31992,
"s": 31967,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 32017,
"s": 31992,
"text": "Building Heap from Array"
},
{
"code": null,
"e": 32037,
"s": 32017,
"text": "Trapping Rain Water"
},
{
"code": null,
"e": 32075,
"s": 32037,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 32124,
"s": 32075,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 32209,
"s": 32124,
"text": "Move all negative numbers to beginning and positive to end with constant extra space"
},
{
"code": null,
"e": 32267,
"s": 32209,
"text": "Find duplicates in O(n) time and O(1) extra space | Set 1"
},
{
"code": null,
"e": 32294,
"s": 32267,
"text": "Count pairs with given sum"
},
{
"code": null,
"e": 32315,
"s": 32294,
"text": "Next Greater Element"
}
] |
C Program for Breadth First Search or BFS for a Graph - GeeksforGeeks | 20 Dec, 2021
Breadth First Traversal (or Search) for a graph is similar to Breadth First Traversal of a tree (See method 2 of this post). The only catch here is, unlike trees, graphs may contain cycles, so we may come to the same node again. To avoid processing a node more than once, we use a boolean visited array. For simplicity, it is assumed that all vertices are reachable from the starting vertex.For example, in the following graph, we start traversal from vertex 2. When we come to vertex 0, we look for all adjacent vertices of it. 2 is also an adjacent vertex of 0. If we don’t mark visited vertices, then 2 will be processed again and it will become a non-terminating process. A Breadth First Traversal of the following graph is 2, 0, 3, 1.
Following are the implementations of simple Breadth First Traversal from a given source.
The implementation uses adjacency list representation of graphs. STL\’s list container is used to store lists of adjacent nodes and queue of nodes needed for BFS traversal.
C++
// Program to print BFS traversal from a given// source vertex. BFS(int s) traverses vertices // reachable from s.#include<iostream>#include <list> using namespace std; // This class represents a directed graph using// adjacency list representationclass Graph{ int V; // No. of vertices // Pointer to an array containing adjacency // lists list<int> *adj; public: Graph(int V); // Constructor // function to add an edge to graph void addEdge(int v, int w); // prints BFS traversal from a given source s void BFS(int s); }; Graph::Graph(int V){ this->V = V; adj = new list<int>[V];} void Graph::addEdge(int v, int w){ adj[v].push_back(w); // Add w to v’s list.} void Graph::BFS(int s){ // Mark all the vertices as not visited bool *visited = new bool[V]; for(int i = 0; i < V; i++) visited[i] = false; // Create a queue for BFS list<int> queue; // Mark the current node as visited and enqueue it visited[s] = true; queue.push_back(s); // \'i\' will be used to get all adjacent // vertices of a vertex list<int>::iterator i; while(!queue.empty()) { // Dequeue a vertex from queue and print it s = queue.front(); cout << s << " "; queue.pop_front(); // Get all adjacent vertices of the dequeued // vertex s. If a adjacent has not been visited, // then mark it visited and enqueue it for (i = adj[s].begin(); i != adj[s].end(); ++i) { if (!visited[*i]) { visited[*i] = true; queue.push_back(*i); } } }} // Driver program to test methods of graph classint main(){ // Create a graph given in the above diagram Graph g(4); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 2); g.addEdge(2, 0); g.addEdge(2, 3); g.addEdge(3, 3); cout << "Following is Breadth First Traversal " << "(starting from vertex 2) \n"; g.BFS(2); return 0;}
Please refer complete article on Breadth First Search or BFS for a Graph for more details!
C Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C Program to read contents of Whole File
Producer Consumer Problem in C
C program to find the length of a string
Exit codes in C/C++ with Examples
Regular expressions in C
C / C++ Program for Dijkstra's shortest path algorithm | Greedy Algo-7
Hamming code Implementation in C/C++
Handling multiple clients on server with multithreading using Socket Programming in C/C++
C Hello World Program
Difference between break and continue statement in C | [
{
"code": null,
"e": 24930,
"s": 24902,
"text": "\n20 Dec, 2021"
},
{
"code": null,
"e": 25670,
"s": 24930,
"text": "Breadth First Traversal (or Search) for a graph is similar to Breadth First Traversal of a tree (See method 2 of this post). The only catch here is, unlike trees, graphs may contain cycles, so we may come to the same node again. To avoid processing a node more than once, we use a boolean visited array. For simplicity, it is assumed that all vertices are reachable from the starting vertex.For example, in the following graph, we start traversal from vertex 2. When we come to vertex 0, we look for all adjacent vertices of it. 2 is also an adjacent vertex of 0. If we don’t mark visited vertices, then 2 will be processed again and it will become a non-terminating process. A Breadth First Traversal of the following graph is 2, 0, 3, 1."
},
{
"code": null,
"e": 25759,
"s": 25670,
"text": "Following are the implementations of simple Breadth First Traversal from a given source."
},
{
"code": null,
"e": 25932,
"s": 25759,
"text": "The implementation uses adjacency list representation of graphs. STL\\’s list container is used to store lists of adjacent nodes and queue of nodes needed for BFS traversal."
},
{
"code": null,
"e": 25936,
"s": 25932,
"text": "C++"
},
{
"code": "// Program to print BFS traversal from a given// source vertex. BFS(int s) traverses vertices // reachable from s.#include<iostream>#include <list> using namespace std; // This class represents a directed graph using// adjacency list representationclass Graph{ int V; // No. of vertices // Pointer to an array containing adjacency // lists list<int> *adj; public: Graph(int V); // Constructor // function to add an edge to graph void addEdge(int v, int w); // prints BFS traversal from a given source s void BFS(int s); }; Graph::Graph(int V){ this->V = V; adj = new list<int>[V];} void Graph::addEdge(int v, int w){ adj[v].push_back(w); // Add w to v’s list.} void Graph::BFS(int s){ // Mark all the vertices as not visited bool *visited = new bool[V]; for(int i = 0; i < V; i++) visited[i] = false; // Create a queue for BFS list<int> queue; // Mark the current node as visited and enqueue it visited[s] = true; queue.push_back(s); // \\'i\\' will be used to get all adjacent // vertices of a vertex list<int>::iterator i; while(!queue.empty()) { // Dequeue a vertex from queue and print it s = queue.front(); cout << s << \" \"; queue.pop_front(); // Get all adjacent vertices of the dequeued // vertex s. If a adjacent has not been visited, // then mark it visited and enqueue it for (i = adj[s].begin(); i != adj[s].end(); ++i) { if (!visited[*i]) { visited[*i] = true; queue.push_back(*i); } } }} // Driver program to test methods of graph classint main(){ // Create a graph given in the above diagram Graph g(4); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 2); g.addEdge(2, 0); g.addEdge(2, 3); g.addEdge(3, 3); cout << \"Following is Breadth First Traversal \" << \"(starting from vertex 2) \\n\"; g.BFS(2); return 0;}",
"e": 27951,
"s": 25936,
"text": null
},
{
"code": null,
"e": 28042,
"s": 27951,
"text": "Please refer complete article on Breadth First Search or BFS for a Graph for more details!"
},
{
"code": null,
"e": 28053,
"s": 28042,
"text": "C Programs"
},
{
"code": null,
"e": 28151,
"s": 28053,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28192,
"s": 28151,
"text": "C Program to read contents of Whole File"
},
{
"code": null,
"e": 28223,
"s": 28192,
"text": "Producer Consumer Problem in C"
},
{
"code": null,
"e": 28264,
"s": 28223,
"text": "C program to find the length of a string"
},
{
"code": null,
"e": 28298,
"s": 28264,
"text": "Exit codes in C/C++ with Examples"
},
{
"code": null,
"e": 28323,
"s": 28298,
"text": "Regular expressions in C"
},
{
"code": null,
"e": 28394,
"s": 28323,
"text": "C / C++ Program for Dijkstra's shortest path algorithm | Greedy Algo-7"
},
{
"code": null,
"e": 28431,
"s": 28394,
"text": "Hamming code Implementation in C/C++"
},
{
"code": null,
"e": 28521,
"s": 28431,
"text": "Handling multiple clients on server with multithreading using Socket Programming in C/C++"
},
{
"code": null,
"e": 28543,
"s": 28521,
"text": "C Hello World Program"
}
] |
Tryit Editor v3.7 | Tryit: Images without object-fit | [] |
CSS - Cursors | The cursor property of CSS allows you to specify the type of cursor that should be displayed to the user.
One good usage of this property is in using images for submit buttons on forms. By default, when a cursor hovers over a link, the cursor changes from a pointer to a hand. However, it does not change form for a submit button on a form. Therefore, whenever someone hovers over an image that is a submit button, it provides a visual clue that the image is clickable.
The following table shows the possible values for the cursor property −
auto
Shape of the cursor depends on the context area it is over. For example an I over text, a hand over a link, and so on...
crosshair
A crosshair or plus sign
default
An arrow
pointer
A pointing hand (in IE 4 this value is hand)
move
The I bar
e-resize
The cursor indicates that an edge of a box is to be moved right (east)
ne-resize
The cursor indicates that an edge of a box is to be moved up and right (north/east)
nw-resize
The cursor indicates that an edge of a box is to be moved up and left (north/west)
n-resize
The cursor indicates that an edge of a box is to be moved up (north)
se-resize
The cursor indicates that an edge of a box is to be moved down and right (south/east)
sw-resize
The cursor indicates that an edge of a box is to be moved down and left (south/west)
s-resize
The cursor indicates that an edge of a box is to be moved down (south)
w-resize
The cursor indicates that an edge of a box is to be moved left (west)
text
The I bar
wait
An hour glass
help
A question mark or balloon, ideal for use over help buttons
<url>
The source of a cursor image file
NOTE − You should try to use only these values to add helpful information for users, and in places, they would expect to see that cursor. For example, using the crosshair when someone hovers over a link can confuse visitors.
Here is an example −
<html>
<head>
</head>
<body>
<p>Move the mouse over the words to see the cursor change:</p>
<div style = "cursor:auto">Auto</div>
<div style = "cursor:crosshair">Crosshair</div>
<div style = "cursor:default">Default</div>
<div style = "cursor:pointer">Pointer</div>
<div style = "cursor:move">Move</div>
<div style = "cursor:e-resize">e-resize</div>
<div style = "cursor:ne-resize">ne-resize</div>
<div style = "cursor:nw-resize">nw-resize</div>
<div style = "cursor:n-resize">n-resize</div>
<div style = "cursor:se-resize">se-resize</div>
<div style = "cursor:sw-resize">sw-resize</div>
<div style = "cursor:s-resize">s-resize</div>
<div style = "cursor:w-resize">w-resize</div>
<div style = "cursor:text">text</div>
<div style = "cursor:wait">wait</div>
<div style = "cursor:help">help</div>
</body>
</html>
It will produce the following result −
Move the mouse over the words to see the cursor change:
33 Lectures
2.5 hours
Anadi Sharma
26 Lectures
2.5 hours
Frahaan Hussain
44 Lectures
4.5 hours
DigiFisk (Programming Is Fun)
21 Lectures
2.5 hours
DigiFisk (Programming Is Fun)
51 Lectures
7.5 hours
DigiFisk (Programming Is Fun)
52 Lectures
4 hours
DigiFisk (Programming Is Fun)
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2732,
"s": 2626,
"text": "The cursor property of CSS allows you to specify the type of cursor that should be displayed to the user."
},
{
"code": null,
"e": 3096,
"s": 2732,
"text": "One good usage of this property is in using images for submit buttons on forms. By default, when a cursor hovers over a link, the cursor changes from a pointer to a hand. However, it does not change form for a submit button on a form. Therefore, whenever someone hovers over an image that is a submit button, it provides a visual clue that the image is clickable."
},
{
"code": null,
"e": 3168,
"s": 3096,
"text": "The following table shows the possible values for the cursor property −"
},
{
"code": null,
"e": 3173,
"s": 3168,
"text": "auto"
},
{
"code": null,
"e": 3294,
"s": 3173,
"text": "Shape of the cursor depends on the context area it is over. For example an I over text, a hand over a link, and so on..."
},
{
"code": null,
"e": 3304,
"s": 3294,
"text": "crosshair"
},
{
"code": null,
"e": 3329,
"s": 3304,
"text": "A crosshair or plus sign"
},
{
"code": null,
"e": 3337,
"s": 3329,
"text": "default"
},
{
"code": null,
"e": 3346,
"s": 3337,
"text": "An arrow"
},
{
"code": null,
"e": 3354,
"s": 3346,
"text": "pointer"
},
{
"code": null,
"e": 3399,
"s": 3354,
"text": "A pointing hand (in IE 4 this value is hand)"
},
{
"code": null,
"e": 3404,
"s": 3399,
"text": "move"
},
{
"code": null,
"e": 3414,
"s": 3404,
"text": "The I bar"
},
{
"code": null,
"e": 3423,
"s": 3414,
"text": "e-resize"
},
{
"code": null,
"e": 3494,
"s": 3423,
"text": "The cursor indicates that an edge of a box is to be moved right (east)"
},
{
"code": null,
"e": 3504,
"s": 3494,
"text": "ne-resize"
},
{
"code": null,
"e": 3588,
"s": 3504,
"text": "The cursor indicates that an edge of a box is to be moved up and right (north/east)"
},
{
"code": null,
"e": 3598,
"s": 3588,
"text": "nw-resize"
},
{
"code": null,
"e": 3681,
"s": 3598,
"text": "The cursor indicates that an edge of a box is to be moved up and left (north/west)"
},
{
"code": null,
"e": 3690,
"s": 3681,
"text": "n-resize"
},
{
"code": null,
"e": 3759,
"s": 3690,
"text": "The cursor indicates that an edge of a box is to be moved up (north)"
},
{
"code": null,
"e": 3769,
"s": 3759,
"text": "se-resize"
},
{
"code": null,
"e": 3855,
"s": 3769,
"text": "The cursor indicates that an edge of a box is to be moved down and right (south/east)"
},
{
"code": null,
"e": 3865,
"s": 3855,
"text": "sw-resize"
},
{
"code": null,
"e": 3950,
"s": 3865,
"text": "The cursor indicates that an edge of a box is to be moved down and left (south/west)"
},
{
"code": null,
"e": 3959,
"s": 3950,
"text": "s-resize"
},
{
"code": null,
"e": 4030,
"s": 3959,
"text": "The cursor indicates that an edge of a box is to be moved down (south)"
},
{
"code": null,
"e": 4039,
"s": 4030,
"text": "w-resize"
},
{
"code": null,
"e": 4109,
"s": 4039,
"text": "The cursor indicates that an edge of a box is to be moved left (west)"
},
{
"code": null,
"e": 4114,
"s": 4109,
"text": "text"
},
{
"code": null,
"e": 4124,
"s": 4114,
"text": "The I bar"
},
{
"code": null,
"e": 4129,
"s": 4124,
"text": "wait"
},
{
"code": null,
"e": 4143,
"s": 4129,
"text": "An hour glass"
},
{
"code": null,
"e": 4148,
"s": 4143,
"text": "help"
},
{
"code": null,
"e": 4208,
"s": 4148,
"text": "A question mark or balloon, ideal for use over help buttons"
},
{
"code": null,
"e": 4214,
"s": 4208,
"text": "<url>"
},
{
"code": null,
"e": 4248,
"s": 4214,
"text": "The source of a cursor image file"
},
{
"code": null,
"e": 4473,
"s": 4248,
"text": "NOTE − You should try to use only these values to add helpful information for users, and in places, they would expect to see that cursor. For example, using the crosshair when someone hovers over a link can confuse visitors."
},
{
"code": null,
"e": 4494,
"s": 4473,
"text": "Here is an example −"
},
{
"code": null,
"e": 5451,
"s": 4494,
"text": "<html>\n <head>\n </head>\n \n <body>\n <p>Move the mouse over the words to see the cursor change:</p>\n \n <div style = \"cursor:auto\">Auto</div>\n <div style = \"cursor:crosshair\">Crosshair</div>\n <div style = \"cursor:default\">Default</div>\n \n <div style = \"cursor:pointer\">Pointer</div>\n <div style = \"cursor:move\">Move</div>\n <div style = \"cursor:e-resize\">e-resize</div>\n <div style = \"cursor:ne-resize\">ne-resize</div>\n <div style = \"cursor:nw-resize\">nw-resize</div>\n \n <div style = \"cursor:n-resize\">n-resize</div>\n <div style = \"cursor:se-resize\">se-resize</div>\n <div style = \"cursor:sw-resize\">sw-resize</div>\n <div style = \"cursor:s-resize\">s-resize</div>\n <div style = \"cursor:w-resize\">w-resize</div>\n \n <div style = \"cursor:text\">text</div>\n <div style = \"cursor:wait\">wait</div>\n <div style = \"cursor:help\">help</div>\n </body>\n</html> "
},
{
"code": null,
"e": 5490,
"s": 5451,
"text": "It will produce the following result −"
},
{
"code": null,
"e": 5546,
"s": 5490,
"text": "Move the mouse over the words to see the cursor change:"
},
{
"code": null,
"e": 5581,
"s": 5546,
"text": "\n 33 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5595,
"s": 5581,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 5630,
"s": 5595,
"text": "\n 26 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5647,
"s": 5630,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 5682,
"s": 5647,
"text": "\n 44 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 5713,
"s": 5682,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 5748,
"s": 5713,
"text": "\n 21 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5779,
"s": 5748,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 5814,
"s": 5779,
"text": "\n 51 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 5845,
"s": 5814,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 5878,
"s": 5845,
"text": "\n 52 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 5909,
"s": 5878,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 5916,
"s": 5909,
"text": " Print"
},
{
"code": null,
"e": 5927,
"s": 5916,
"text": " Add Notes"
}
] |
Convert integer array to string array in JavaScript? | To convert integer array to string array, use the map(String) in JavaScript. Let’s say the following is our integer array −
var integerValues = [101,50,70,90,110,90,94,68];
Convert integer array to string array −
integerValues.map(String);
Following is the code −
var integerValues = [101,50,70,90,110,90,94,68];
console.log("The integer array value=");
console.log(integerValues);
integerValues.map(String);
console.log("The string array value=");
console.log(integerValues)
To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo212.js.
The output is as follows in console −
PS C:\Users\Amit\JavaScript-code> node demo212.js
The integer array value=
[
101, 50, 70, 90,
110, 90, 94, 68
]
The string array value=
[
101, 50, 70, 90,
110, 90, 94, 68
] | [
{
"code": null,
"e": 1186,
"s": 1062,
"text": "To convert integer array to string array, use the map(String) in JavaScript. Let’s say the following is our integer array −"
},
{
"code": null,
"e": 1235,
"s": 1186,
"text": "var integerValues = [101,50,70,90,110,90,94,68];"
},
{
"code": null,
"e": 1275,
"s": 1235,
"text": "Convert integer array to string array −"
},
{
"code": null,
"e": 1302,
"s": 1275,
"text": "integerValues.map(String);"
},
{
"code": null,
"e": 1326,
"s": 1302,
"text": "Following is the code −"
},
{
"code": null,
"e": 1538,
"s": 1326,
"text": "var integerValues = [101,50,70,90,110,90,94,68];\nconsole.log(\"The integer array value=\");\nconsole.log(integerValues);\nintegerValues.map(String);\nconsole.log(\"The string array value=\");\nconsole.log(integerValues)"
},
{
"code": null,
"e": 1604,
"s": 1538,
"text": "To run the above program, you need to use the following command −"
},
{
"code": null,
"e": 1622,
"s": 1604,
"text": "node fileName.js."
},
{
"code": null,
"e": 1656,
"s": 1622,
"text": "Here, my file name is demo212.js."
},
{
"code": null,
"e": 1694,
"s": 1656,
"text": "The output is as follows in console −"
},
{
"code": null,
"e": 1879,
"s": 1694,
"text": "PS C:\\Users\\Amit\\JavaScript-code> node demo212.js\nThe integer array value=\n[\n 101, 50, 70, 90,\n 110, 90, 94, 68\n]\nThe string array value=\n[\n 101, 50, 70, 90,\n 110, 90, 94, 68\n]"
}
] |
Convert a Tensorflow2 model to OpenVINO® | by Filippo Valle | Towards Data Science | Application of machine learning are, nowadays, endless. There are models out there already trained and data that need nothing but to be fitted.
When one deals with Machine Learning applications it often tricky deciding on which hardware train the model and offload the inference.
Intel® has introduced openVINO® that help deploy models (mostly related to computer vision) to any Intel® device, no matter if they are CPUs, GPUs, FPGAs or a Neural Compute Stick with a MYRIAD chip.
software.intel.com
One of the common usages of this technology is using openVINO to make a fast inference (i.e. predicting objects live in a video from a webcam). Some models require a powerful hardware to be trained, but it would be sufficient a smaller and less expensive one to performing inference. For example one can use a complex pretrained model and then run it on light hardware like a RaspberryPi.
OpenVINO is a powerful tool, but it requires some passages in order to work properly. We will go trough the process of converting a model, load it into an Inference engine plugin and perform an inference.
The Intel framework has a collection of pretrained and optimised models one could use. But what if you want to train a custom model?
We will considered model trained using Tensorflow, even if openVINO supports many other frameworks. The steps are mostly similar.
I will use Google Colab to describe all of this, it should be easily reproducible.
First of all, we need to download openVINO repository and install prerequisites for Tensorflow.
!git clone https://github.com/openvinotoolkit/openvino!cd openvino/model-optimizer/install_prerequisites/ && ./install_prerequisites.sh tf2
In this step you can do whatever you want. Create a custom keras model, with custom layers. Compile it. Train it on any dataset and so on.
When you are satisfied with your training, you can prepare the model to be loaded into Inference Engine plugin. Then the model can be used for inference on any kind of devices.
The first step is to save the model into a .h5 file. This is easily done with the keras API.
model = tf.keras.models.load_model(“/content/model.h5”)tf.saved_model.save(model,’model’)
Models need to be converted into a representation that the Inference Engine can load into devices for inference. This step can be done using the so-called model optimiser as shown below.
Model optimiser requires some parameters in input, like the input_shape.
python3 openvino/model-optimizer/mo_tf.py --saved_model_dir model/ --input_shape=\[1,28,28\]
At this point you should have two files model.xml and model.bin which contain all the required information to perform inference on your custom model.
An example of this conversion steps is available in the following notebook:
colab.research.google.com
When the converted model is ready, the next step is to use it for inference. This can be done on any kind of supported device. There is no need to use the same on which you performed training.
In order to run the inference it is necessary to install the openVINO framework. This can be easily done trough pip.
!pip install --upgrade pip!pip install openvino
We need to load the model to a device for the inference.
The Inference Engine Core object has the capabilities to read the .xml and .bin into a network object.
This network can be loaded into any device being it a CPU, GPU or MYRIAD. This is one of the powerful aspects of this API it runs transparently on any kind of device without efforts.
from openvino.inference_engine import IECore, IENetworkie = IECore()net = ie.read_network(model=model_xml, weights=model_bin)exec_net = ie.load_network(network=net, device_name="MYRIAD")
We can inspect the network topology. This API supports only a single input, anyway if you are running this on a video, you need to perform inference on a single frame a time, so this is not a big deal.
Moreover we can inspect the input or the output shape, which is particularly useful on models trained by someone else. We need to be sure to have the data in the right shape.
assert len(net.input_info.keys()) == 1, "Sample supports only single input topologies"assert len(net.outputs) == 1, "Sample supports only single output topologies"input_blob = next(iter(net.input_info.keys()))out_blob = next(iter(net.outputs))net.batch_size = len([0])net.input_info[input_blob].input_data.shape
And finally, it is time for the inference. Given an object X_test[0] we are ready to infer it using the infer method on the network.
res = exec_net.infer(inputs={input_blob: X_test[0]})res[out_blob].reshape(1,10)
We trained a custom model.
Using the openVINO model optimiser we converted it into a new representation required to load the model to the Inference Engine module.
When the trained model was ready using Inference Engine to infer an input data it is almost trivial. And as a bonus this can be done on any kind of device. | [
{
"code": null,
"e": 315,
"s": 171,
"text": "Application of machine learning are, nowadays, endless. There are models out there already trained and data that need nothing but to be fitted."
},
{
"code": null,
"e": 451,
"s": 315,
"text": "When one deals with Machine Learning applications it often tricky deciding on which hardware train the model and offload the inference."
},
{
"code": null,
"e": 651,
"s": 451,
"text": "Intel® has introduced openVINO® that help deploy models (mostly related to computer vision) to any Intel® device, no matter if they are CPUs, GPUs, FPGAs or a Neural Compute Stick with a MYRIAD chip."
},
{
"code": null,
"e": 670,
"s": 651,
"text": "software.intel.com"
},
{
"code": null,
"e": 1059,
"s": 670,
"text": "One of the common usages of this technology is using openVINO to make a fast inference (i.e. predicting objects live in a video from a webcam). Some models require a powerful hardware to be trained, but it would be sufficient a smaller and less expensive one to performing inference. For example one can use a complex pretrained model and then run it on light hardware like a RaspberryPi."
},
{
"code": null,
"e": 1264,
"s": 1059,
"text": "OpenVINO is a powerful tool, but it requires some passages in order to work properly. We will go trough the process of converting a model, load it into an Inference engine plugin and perform an inference."
},
{
"code": null,
"e": 1397,
"s": 1264,
"text": "The Intel framework has a collection of pretrained and optimised models one could use. But what if you want to train a custom model?"
},
{
"code": null,
"e": 1527,
"s": 1397,
"text": "We will considered model trained using Tensorflow, even if openVINO supports many other frameworks. The steps are mostly similar."
},
{
"code": null,
"e": 1610,
"s": 1527,
"text": "I will use Google Colab to describe all of this, it should be easily reproducible."
},
{
"code": null,
"e": 1706,
"s": 1610,
"text": "First of all, we need to download openVINO repository and install prerequisites for Tensorflow."
},
{
"code": null,
"e": 1846,
"s": 1706,
"text": "!git clone https://github.com/openvinotoolkit/openvino!cd openvino/model-optimizer/install_prerequisites/ && ./install_prerequisites.sh tf2"
},
{
"code": null,
"e": 1985,
"s": 1846,
"text": "In this step you can do whatever you want. Create a custom keras model, with custom layers. Compile it. Train it on any dataset and so on."
},
{
"code": null,
"e": 2162,
"s": 1985,
"text": "When you are satisfied with your training, you can prepare the model to be loaded into Inference Engine plugin. Then the model can be used for inference on any kind of devices."
},
{
"code": null,
"e": 2255,
"s": 2162,
"text": "The first step is to save the model into a .h5 file. This is easily done with the keras API."
},
{
"code": null,
"e": 2345,
"s": 2255,
"text": "model = tf.keras.models.load_model(“/content/model.h5”)tf.saved_model.save(model,’model’)"
},
{
"code": null,
"e": 2532,
"s": 2345,
"text": "Models need to be converted into a representation that the Inference Engine can load into devices for inference. This step can be done using the so-called model optimiser as shown below."
},
{
"code": null,
"e": 2605,
"s": 2532,
"text": "Model optimiser requires some parameters in input, like the input_shape."
},
{
"code": null,
"e": 2698,
"s": 2605,
"text": "python3 openvino/model-optimizer/mo_tf.py --saved_model_dir model/ --input_shape=\\[1,28,28\\]"
},
{
"code": null,
"e": 2848,
"s": 2698,
"text": "At this point you should have two files model.xml and model.bin which contain all the required information to perform inference on your custom model."
},
{
"code": null,
"e": 2924,
"s": 2848,
"text": "An example of this conversion steps is available in the following notebook:"
},
{
"code": null,
"e": 2950,
"s": 2924,
"text": "colab.research.google.com"
},
{
"code": null,
"e": 3143,
"s": 2950,
"text": "When the converted model is ready, the next step is to use it for inference. This can be done on any kind of supported device. There is no need to use the same on which you performed training."
},
{
"code": null,
"e": 3260,
"s": 3143,
"text": "In order to run the inference it is necessary to install the openVINO framework. This can be easily done trough pip."
},
{
"code": null,
"e": 3308,
"s": 3260,
"text": "!pip install --upgrade pip!pip install openvino"
},
{
"code": null,
"e": 3365,
"s": 3308,
"text": "We need to load the model to a device for the inference."
},
{
"code": null,
"e": 3468,
"s": 3365,
"text": "The Inference Engine Core object has the capabilities to read the .xml and .bin into a network object."
},
{
"code": null,
"e": 3651,
"s": 3468,
"text": "This network can be loaded into any device being it a CPU, GPU or MYRIAD. This is one of the powerful aspects of this API it runs transparently on any kind of device without efforts."
},
{
"code": null,
"e": 3840,
"s": 3651,
"text": "from openvino.inference_engine import IECore, IENetworkie = IECore()net = ie.read_network(model=model_xml, weights=model_bin)exec_net = ie.load_network(network=net, device_name=\"MYRIAD\")"
},
{
"code": null,
"e": 4042,
"s": 3840,
"text": "We can inspect the network topology. This API supports only a single input, anyway if you are running this on a video, you need to perform inference on a single frame a time, so this is not a big deal."
},
{
"code": null,
"e": 4217,
"s": 4042,
"text": "Moreover we can inspect the input or the output shape, which is particularly useful on models trained by someone else. We need to be sure to have the data in the right shape."
},
{
"code": null,
"e": 4529,
"s": 4217,
"text": "assert len(net.input_info.keys()) == 1, \"Sample supports only single input topologies\"assert len(net.outputs) == 1, \"Sample supports only single output topologies\"input_blob = next(iter(net.input_info.keys()))out_blob = next(iter(net.outputs))net.batch_size = len([0])net.input_info[input_blob].input_data.shape"
},
{
"code": null,
"e": 4662,
"s": 4529,
"text": "And finally, it is time for the inference. Given an object X_test[0] we are ready to infer it using the infer method on the network."
},
{
"code": null,
"e": 4742,
"s": 4662,
"text": "res = exec_net.infer(inputs={input_blob: X_test[0]})res[out_blob].reshape(1,10)"
},
{
"code": null,
"e": 4769,
"s": 4742,
"text": "We trained a custom model."
},
{
"code": null,
"e": 4905,
"s": 4769,
"text": "Using the openVINO model optimiser we converted it into a new representation required to load the model to the Inference Engine module."
}
] |
Representation Learning on RDF* and LPG Knowledge Graphs | by Michael Galkin | Towards Data Science | Knowledge graphs (KGs) are a cornerstone of modern NLP and AI applications — recent works include Question Answering, Entity & Relation Linking, Language Modeling, Information Extraction, and even playing text RPGs with Reinforcement Learning. Furthermore, KGs are already widely adopted in the industry, e.g., a line-up of works from the recent Knowledge Graph Conference (KGC)
Traditionally, KGs are encoded as <subject, predicate, object> (RDF) triples, and many publicly available KGs like DBpedia and YAGO initially followed this paradigm backed by expressive logical formalisms (remember the times when DL referred to Description Logics ? 👵) and standards like RDF and OWL.
Using triples, the above example describing which universities Albert Einstein attended can be encoded as two triples:
Albert Einstein, educated at, ETH ZurichAlbert Einstein, educated at, University of Zurich
Well, it looks okayish for simple applications but turns out our world is a bit more complex to fit everything into triples. For instance, do the two triples imply that Albert Einstein was educated at the two places simultaneously? Or they awarded him with the same degree?
In fact, Einstein received a Bachelor’s degree at ETH Zurich with a major in mathematics, whereas at the University of Zurich he obtained a doctoral degree with a major in physics.
Can we have a mechanism to express facts in more detail?
Yes! In the KG world, there are at least two ways to do that — RDF* Graphs and Labeled Property Graphs (LPG). Both of them allow instantiating each fact further by attaching auxiliary key-value (relation-entity) pairs to edges in a KG. And both of them are already supported by major vendors on the graph databases market 👍.
In the LPG world, both nodes and edges can naturally have key-value attributes. Neo4j is probably the biggest name in the LPG family. You can query LPGs with (Open)Cypher. A recent COVID-19 KG is available as a Neo4j dump.
RDF* originally proposed by Olaf Hartig (his blog is a good starting source to get into RDF* and related tech) aims to alleviate many issues of the infamous RDF reification mechanism (check out this survey by Frey et al for a comprehensive overview of reification) while retaining reasoning capabilities pertaining to RDF graphs. Backed by solid theoretical foundations, RDF* provides a handful of ways to enrich triples with more details. You can query RDF* graphs with SPARQL* (an extension of SPARQL for working with RDF*). Apache Jena, RDF4J, N3.js, Blazegraph, AnzoGraph, Stardog, and GraphDB support RDF* and SPARQL*
Our example in the RDF* syntax can look like this:
<< Albert_Einstein educated_at ETH_Zurich >> academic_degree Bachelor ; academic_major Maths .<< Albert_Einstein educated_at University_of_Zurich >> academic_degree Doctorate ; academic_major Physics.
What is a suitable term for such KGs? There was a small vocabulary gap until Rosso et al in their recent WWW’20 work suggested using “hyper-relational graph”. Still, there is a common misuse of the term “hypergraph”. We’d like to advocate for “hyper-relational” graphs as well. 🤝
The main difference is in the representation of a fact. Hypergraphs assume there is one (named) hyper-edge unifying several entities:
education(Albert Einstein, ETH Zurich, Bachelor, Mathematics)education(Albert Einstein, University of Zurich, Doctorate, Physics)
Looks like an n-ary relation, right? 🤨 We have several problems here:
We lose the typed relations academic_degree and academic_major associated with Bachelor/Doctorate and Mathematics/Physics, respectively. Instead, the type of a hyperedge is an abstraction (or a rather weird semantic mixture 🤯) of educated_at, academic_degree and academic_major. What if one fact also contains an auxiliary predicate academic_supervisor? We’ll need to define a new hyper-edge, say, education1(), mixing 4 those relations which explodes exponentially with the amount of predicates and qualifiers. 📈
We lose the typed relations academic_degree and academic_major associated with Bachelor/Doctorate and Mathematics/Physics, respectively. Instead, the type of a hyperedge is an abstraction (or a rather weird semantic mixture 🤯) of educated_at, academic_degree and academic_major. What if one fact also contains an auxiliary predicate academic_supervisor? We’ll need to define a new hyper-edge, say, education1(), mixing 4 those relations which explodes exponentially with the amount of predicates and qualifiers. 📈
2. Moreover, we also lose the auxiliary character of degrees and majors, i.e., they are intended to describe their main triples. For example, Bachelor and Mathematics are auxiliary wrt Albert Einstein and ETH Zurich and, hence, should be treated in this manner. A tuple of entities in a hyper-edge assumes equal importance of its elements.
That said, in the following parts we’ll adhere to hyper-relational approaches.
In 2020, most of the open-domain KGs widely use hyper-relational facts. Wikidata and its Wikidata Statements model is a good example of a hyper-relational KG. Each fact in Wikidata is a Statement with the main triple and a set of auxiliary qualifiers — entity-relation pairs. With Wikidata statements our Albert Einstein example can be modeled as easy as following:
In those statements, (academic_degree, Bachelor) and (academic_major, Mathematics) are qualifiers for the triple <Albert Einstein, educated_at, ETH Zurich>.
It’s important to notice that Wikidata (and generally the hyper-relational paradigm) does not separate between entities and predicates used exclusively in the main triples or qualifiers, i.e.,
all predicates and entities can be used either in triple terms or qualifiers
(albeit there can be some entities and relations seen only in qualifiers in the current Wikidata version). We will use this property in the following sections.
As to other KGs, starting from 2018, new releases of DBpedia contain reified statements similar to those in Wikidata. YAGO 4 adopted RDF* encoding of the facts as well. 🙌
What about Freebase? 🤔 Well, in 2020 you should probably not practice necromancy 🧟♂️ as Freebase is no longer supported nor updated. However, Compound Value Types (CVT) nodes in Freebase do resemble reification of triples [but look more like n-ary relations]
Our task here is to learn representations of hyper-relational graphs.
By representations we refer to entity (node) and relation (typed edge) embeddings. The embeddings can then be used in downstream tasks like link prediction, node classification, entity alignment, and many more that can be used in NLP, CV, and other AI areas. 🍀
The field of graph representation learning (GRL) is one of the fastest-growing 🚀 areas of machine learning, there is a handful of articles (a series of posts by Michael Bronstein, reviews (mine, Sergey’s) from ICLR’20 and NeurIPS’19 papers), books (by William Hamilton, by Ma and Tang), courses (CS224W, COMP 766, ESE 680), and even a GraphML Telegram channel (subscribe 😉) covering basic and advanced topics.
In the encoder-decoder paradigm, an encoder is usually a GNN (graph neural net), and a decoder is a function of embeddings that returns a value or a vector pertaining to a certain downstream task, e.g., a probability of an entity being an object of a given <subject, predicate> pair.
Quite a lot! 😍
Encoders: a family of multi-relational GNN encoders like R-GCN (Schlichtkrull et al, ESWC 2018) and CompGCN (Vashishth et al, ICLR 2020) that extend the original Graph Convolutional Network (GCN) algorithm within a message passing framework.
Decoders: actually, traditional KG embedding algorithms like TransE, ConvE, RotatE, etc are good examples of decoders for the link prediction task. Originally, they can also be trained as decoder-only models optimized end-to-end directly 👉 on link prediction tasks.
Hmm, not that much 🤔 (as of Fall 2020)
Encoders: ???
Decoders: HINGE proposed by Rosso et al is an end-to-end CNN-based model for link prediction on hyper-relational graphs.
Well, we couldn’t cope with such a glaring abyss 🕳 in the GNN encoders part and proposed ⭐️ StarE ⭐️ in our recent EMNLP’20 paper “Message Passing for Hyper-Relational Knowledge Graphs” written together with Priyansh Trivedi, Gaurav Maheshwari, Ricardo Usbeck, and Jens Lehmann.
StarE is a multi-relational GNN encoder that extends CompGCN for hyper-relational KGs.
The name is inspired by RDF* 😊 StarE is designed with the following features in mind:
Explicit modeling of relations, including qualifying relations;
Separation of auxiliary entities and relations in qualifiers from entities and relations in main triples;
Still, any entity and any relation can still be used in main triples as well qualifiers;
Permutation invariance to the order of qualifiers — they do not exhibit any particular order and can be freely re-arranged. That is, it does not matter for the main triple <<Albert Einstein, educated at, ETH Zurich>> whether (academic degree, Bachelor) comes before (academic major, Physics) or after.
Let’s trace the evolution of relation-aware GNN encoders in their neighborhood aggregation schemes:
In StarE, a main triple relation h_r appearing between nodes u and v is augmented with an aggregated vector of qualifiers h_q via a function gamma() which can be a weighted sum, multiplication, concat, or any other binary function (we went for the weighted sum).
We obtain the vector h_qvia:
That is, we first pool qualifier relation and entity embeddings h_{qr} and h_{qv}, respectively, in a single vector through a composition function phi_q() which could be a scoring function from the KG embedding family, e.g., RotatE. We then apply a permutation invariant aggregation function (sum, although we also probed multiplication) to pool an arbitrary number of qualifiers into a single vector and finally project it through a transformation matrix W_q.
Since all entities and relations can be generally seen in main triples as well as qualifiers, W_q is intended to learn qualifier-specific representations of entities and relations.
We still retain CompGCN components: phi_() is a composition function similar to phi_q(), but now it merges a node with an enriched edge representation. W_{\lambda} is a weight parameter for incoming, outgoing, and self-looping relations.
GNNs operate on sparse matrices for efficiency reasons. For multi-relational triple-based KGs the following example triples
Q937, P69, Q11942Q937, P69, Q206702
Can be presented in the COO format as a [2, num_edges] tensor with an additional row for edge types
[Q937, Q937][Q11942, Q206702][P69, P69]
Hyper-relational facts with qualifiers can be written as follows:
Q937, P69, Q206702, P812, Q413, P512, Q849697s, r, o, qr1, qv1, qr2, qv2, ..., qrN, qvN
Where the first three entries always denote the “main” triple and the subsequent pairs are qualifiers in no particular order (remember the order invariance in Wikidata)
What can be a sparse representation of hyper-relational KGs where each “column” of the COO matrix might have an arbitrary number of qualifiers? In the paper, we propose the following encoding:
That is, we have two COO matrices:
A normal “triple” COO with an implicit column index kA “qualifier” COO of the shape [3, num_qualifiers] where the first row contains indices of the columns in the “triple” COO, the second contains qualifier relations, and the third — qualifier entities. The index row connects a column of qualifiers to the main triple. That said, the columns in the “qualifier” COO that share the same index k belong to the same k-th triple in the “triple” COO matrix. This allows us to be O(q) in memory wrt to the number of qualifiers in the KG, and the overall memory is O(|edges|+|qualifiers|) ⚖.️
A normal “triple” COO with an implicit column index k
A “qualifier” COO of the shape [3, num_qualifiers] where the first row contains indices of the columns in the “triple” COO, the second contains qualifier relations, and the third — qualifier entities. The index row connects a column of qualifiers to the main triple. That said, the columns in the “qualifier” COO that share the same index k belong to the same k-th triple in the “triple” COO matrix. This allows us to be O(q) in memory wrt to the number of qualifiers in the KG, and the overall memory is O(|edges|+|qualifiers|) ⚖.️
We briefly touched upon encoding hyper-relational facts as a sequence of entities and relations. But are there already reliable datasets for experimenting on such KGs? Traditionally, KG embeddings were evaluated on the link prediction task, while Graph ML tasks include node classification, graph classification, entity matching, and many more.
So far there exist only two link prediction datasets: WikiPeople proposed by Guan et al — it’s a dump of Wikidata describing, well, people, and JF17K— an export from Freebase 🧟♂️. However, we identified major drawbacks 😞 with those two:
WikiPeople has too many qualifiers with literals (years). It is not advisable to treat literals as another sort of entities, as the numbers are continuous values and should be treated in this way (well, it is a general problem with literals in the KG embedding literature 🤔). That said, in most cases, such qualifiers are simply dropped. This results in a dataset where only 2% of facts have qualifiers, and 80% of those facts have only one qualifier pair :/
JF17K has test set leakages. In fact, the authors themselves identified ‘significantly many redundant triples’ and do not recommend using it in the experiments. Being originally more of an n-ary dataset, HINGE transformed it into a hyper-relational format with auxiliary predicates. We conducted a further study and found that more than 40% of the test statements share the same (s,r,o) main triple as in the train set. That is, in the subject/object prediction task, a simple triple-only heuristic can outperform 🏆 all previous hyper-relational approaches which we show in the paper.
As both two datasets are not that suitable for evaluating hyper-relational approaches, we sampled WD50K from Wikidata with the following guidelines:
Retain Wikidata-like distribution of qualifiers. In the vanilla WD50K, about 13% of statements have qualifiers (close to 17% of total statements in Wikidata)
All qualifiers are entity-relation pairs, no literals
Entities and relations can be seen in main triples and qualifiers
99% of statements have at most 6 qualifier pairs
For further experiments, we sampled 3 additional datasets:
WD50K (33) — about 33% of statements have qualifiers
WD50K (66) — about 66% of statements have qualifiers
WD50K (100) — all statements have qualifiers
Naturally, those datasets are smaller than the original WD50K with more qualifier-unique entities and relations.
At this step, we finally have a StarE encoder and suitable link prediction datasets for the experiments. Our main research question:
Do qualifiers help to predict subjects and objects of hyper-relational facts?
That is, given subject, predicate, and all qualifiers we predict the object or vice versa for a subject. For that, we linearize a given fact into a sequence as shown in the illustration and use a 2-layer Transformer with avg pooling and a final FC layer as a decoder.
The Transformer also allows us to feed sequences of different lengths using padding tokens which are masked 👺 from the self-attention computations.
For comparison, we applied decoder-only HINGE and 2-layer Transformer on the same task to measure if the StarE encoder brings any benefits there.
Well, turns out it does! 🎆
What we observe 🕵 :
StarE drastically increases the link prediction performance compared to decoder-only approaches;
StarE is even more effective (the performance gap is larger) when there are more qualifiers in the dataset;
Hyper-relational approaches do help to better predict subjects and objects given qualifiers that triple-only baselines.
How many qualifiers do you need to see the quality improve? Just 2 are enough 😉
Our experimental program with particular numbers and interactive charts is reported with Weights & Biases here 📈
So the takeaways 🔖 to the KG community:
Seek to assign descriptive qualifiers to more triple facts in the graph — the more the betterIf you do assign qualifiers — add 2 or more!
Seek to assign descriptive qualifiers to more triple facts in the graph — the more the better
If you do assign qualifiers — add 2 or more!
Hyper-relational graphs are closer to reality and describe facts in more detail than plain triples
RDF* and LPG provide means to build hyper-relational KGs
A hyper-relational graph is different from a hypergraph
Hyper-relational KGs are already in use — both in open-domain KGs and industry
RDF* motivated StarE — a GNN encoder for hyper-relational KGs that can be paired with a decoder for downstream tasks
StarE improves link prediction compared to decoder-only approaches
The WD50K datasets family better captures the challenges of link prediction on hyper-relational KGs
You can find more information in:
Our EMNLP’20 paper: Message Passing for Hyper-Relational Knowledge Graphs (arxiv pre-print)Code: Github RepoDataset: Zenodo pageWeights & Biases Report: here | [
{
"code": null,
"e": 551,
"s": 172,
"text": "Knowledge graphs (KGs) are a cornerstone of modern NLP and AI applications — recent works include Question Answering, Entity & Relation Linking, Language Modeling, Information Extraction, and even playing text RPGs with Reinforcement Learning. Furthermore, KGs are already widely adopted in the industry, e.g., a line-up of works from the recent Knowledge Graph Conference (KGC)"
},
{
"code": null,
"e": 852,
"s": 551,
"text": "Traditionally, KGs are encoded as <subject, predicate, object> (RDF) triples, and many publicly available KGs like DBpedia and YAGO initially followed this paradigm backed by expressive logical formalisms (remember the times when DL referred to Description Logics ? 👵) and standards like RDF and OWL."
},
{
"code": null,
"e": 971,
"s": 852,
"text": "Using triples, the above example describing which universities Albert Einstein attended can be encoded as two triples:"
},
{
"code": null,
"e": 1062,
"s": 971,
"text": "Albert Einstein, educated at, ETH ZurichAlbert Einstein, educated at, University of Zurich"
},
{
"code": null,
"e": 1336,
"s": 1062,
"text": "Well, it looks okayish for simple applications but turns out our world is a bit more complex to fit everything into triples. For instance, do the two triples imply that Albert Einstein was educated at the two places simultaneously? Or they awarded him with the same degree?"
},
{
"code": null,
"e": 1517,
"s": 1336,
"text": "In fact, Einstein received a Bachelor’s degree at ETH Zurich with a major in mathematics, whereas at the University of Zurich he obtained a doctoral degree with a major in physics."
},
{
"code": null,
"e": 1574,
"s": 1517,
"text": "Can we have a mechanism to express facts in more detail?"
},
{
"code": null,
"e": 1899,
"s": 1574,
"text": "Yes! In the KG world, there are at least two ways to do that — RDF* Graphs and Labeled Property Graphs (LPG). Both of them allow instantiating each fact further by attaching auxiliary key-value (relation-entity) pairs to edges in a KG. And both of them are already supported by major vendors on the graph databases market 👍."
},
{
"code": null,
"e": 2122,
"s": 1899,
"text": "In the LPG world, both nodes and edges can naturally have key-value attributes. Neo4j is probably the biggest name in the LPG family. You can query LPGs with (Open)Cypher. A recent COVID-19 KG is available as a Neo4j dump."
},
{
"code": null,
"e": 2745,
"s": 2122,
"text": "RDF* originally proposed by Olaf Hartig (his blog is a good starting source to get into RDF* and related tech) aims to alleviate many issues of the infamous RDF reification mechanism (check out this survey by Frey et al for a comprehensive overview of reification) while retaining reasoning capabilities pertaining to RDF graphs. Backed by solid theoretical foundations, RDF* provides a handful of ways to enrich triples with more details. You can query RDF* graphs with SPARQL* (an extension of SPARQL for working with RDF*). Apache Jena, RDF4J, N3.js, Blazegraph, AnzoGraph, Stardog, and GraphDB support RDF* and SPARQL*"
},
{
"code": null,
"e": 2796,
"s": 2745,
"text": "Our example in the RDF* syntax can look like this:"
},
{
"code": null,
"e": 3018,
"s": 2796,
"text": "<< Albert_Einstein educated_at ETH_Zurich >> academic_degree Bachelor ; academic_major Maths .<< Albert_Einstein educated_at University_of_Zurich >> academic_degree Doctorate ; academic_major Physics."
},
{
"code": null,
"e": 3298,
"s": 3018,
"text": "What is a suitable term for such KGs? There was a small vocabulary gap until Rosso et al in their recent WWW’20 work suggested using “hyper-relational graph”. Still, there is a common misuse of the term “hypergraph”. We’d like to advocate for “hyper-relational” graphs as well. 🤝"
},
{
"code": null,
"e": 3432,
"s": 3298,
"text": "The main difference is in the representation of a fact. Hypergraphs assume there is one (named) hyper-edge unifying several entities:"
},
{
"code": null,
"e": 3562,
"s": 3432,
"text": "education(Albert Einstein, ETH Zurich, Bachelor, Mathematics)education(Albert Einstein, University of Zurich, Doctorate, Physics)"
},
{
"code": null,
"e": 3632,
"s": 3562,
"text": "Looks like an n-ary relation, right? 🤨 We have several problems here:"
},
{
"code": null,
"e": 4146,
"s": 3632,
"text": "We lose the typed relations academic_degree and academic_major associated with Bachelor/Doctorate and Mathematics/Physics, respectively. Instead, the type of a hyperedge is an abstraction (or a rather weird semantic mixture 🤯) of educated_at, academic_degree and academic_major. What if one fact also contains an auxiliary predicate academic_supervisor? We’ll need to define a new hyper-edge, say, education1(), mixing 4 those relations which explodes exponentially with the amount of predicates and qualifiers. 📈"
},
{
"code": null,
"e": 4660,
"s": 4146,
"text": "We lose the typed relations academic_degree and academic_major associated with Bachelor/Doctorate and Mathematics/Physics, respectively. Instead, the type of a hyperedge is an abstraction (or a rather weird semantic mixture 🤯) of educated_at, academic_degree and academic_major. What if one fact also contains an auxiliary predicate academic_supervisor? We’ll need to define a new hyper-edge, say, education1(), mixing 4 those relations which explodes exponentially with the amount of predicates and qualifiers. 📈"
},
{
"code": null,
"e": 5000,
"s": 4660,
"text": "2. Moreover, we also lose the auxiliary character of degrees and majors, i.e., they are intended to describe their main triples. For example, Bachelor and Mathematics are auxiliary wrt Albert Einstein and ETH Zurich and, hence, should be treated in this manner. A tuple of entities in a hyper-edge assumes equal importance of its elements."
},
{
"code": null,
"e": 5079,
"s": 5000,
"text": "That said, in the following parts we’ll adhere to hyper-relational approaches."
},
{
"code": null,
"e": 5445,
"s": 5079,
"text": "In 2020, most of the open-domain KGs widely use hyper-relational facts. Wikidata and its Wikidata Statements model is a good example of a hyper-relational KG. Each fact in Wikidata is a Statement with the main triple and a set of auxiliary qualifiers — entity-relation pairs. With Wikidata statements our Albert Einstein example can be modeled as easy as following:"
},
{
"code": null,
"e": 5602,
"s": 5445,
"text": "In those statements, (academic_degree, Bachelor) and (academic_major, Mathematics) are qualifiers for the triple <Albert Einstein, educated_at, ETH Zurich>."
},
{
"code": null,
"e": 5795,
"s": 5602,
"text": "It’s important to notice that Wikidata (and generally the hyper-relational paradigm) does not separate between entities and predicates used exclusively in the main triples or qualifiers, i.e.,"
},
{
"code": null,
"e": 5872,
"s": 5795,
"text": "all predicates and entities can be used either in triple terms or qualifiers"
},
{
"code": null,
"e": 6032,
"s": 5872,
"text": "(albeit there can be some entities and relations seen only in qualifiers in the current Wikidata version). We will use this property in the following sections."
},
{
"code": null,
"e": 6203,
"s": 6032,
"text": "As to other KGs, starting from 2018, new releases of DBpedia contain reified statements similar to those in Wikidata. YAGO 4 adopted RDF* encoding of the facts as well. 🙌"
},
{
"code": null,
"e": 6463,
"s": 6203,
"text": "What about Freebase? 🤔 Well, in 2020 you should probably not practice necromancy 🧟♂️ as Freebase is no longer supported nor updated. However, Compound Value Types (CVT) nodes in Freebase do resemble reification of triples [but look more like n-ary relations]"
},
{
"code": null,
"e": 6533,
"s": 6463,
"text": "Our task here is to learn representations of hyper-relational graphs."
},
{
"code": null,
"e": 6794,
"s": 6533,
"text": "By representations we refer to entity (node) and relation (typed edge) embeddings. The embeddings can then be used in downstream tasks like link prediction, node classification, entity alignment, and many more that can be used in NLP, CV, and other AI areas. 🍀"
},
{
"code": null,
"e": 7204,
"s": 6794,
"text": "The field of graph representation learning (GRL) is one of the fastest-growing 🚀 areas of machine learning, there is a handful of articles (a series of posts by Michael Bronstein, reviews (mine, Sergey’s) from ICLR’20 and NeurIPS’19 papers), books (by William Hamilton, by Ma and Tang), courses (CS224W, COMP 766, ESE 680), and even a GraphML Telegram channel (subscribe 😉) covering basic and advanced topics."
},
{
"code": null,
"e": 7488,
"s": 7204,
"text": "In the encoder-decoder paradigm, an encoder is usually a GNN (graph neural net), and a decoder is a function of embeddings that returns a value or a vector pertaining to a certain downstream task, e.g., a probability of an entity being an object of a given <subject, predicate> pair."
},
{
"code": null,
"e": 7503,
"s": 7488,
"text": "Quite a lot! 😍"
},
{
"code": null,
"e": 7745,
"s": 7503,
"text": "Encoders: a family of multi-relational GNN encoders like R-GCN (Schlichtkrull et al, ESWC 2018) and CompGCN (Vashishth et al, ICLR 2020) that extend the original Graph Convolutional Network (GCN) algorithm within a message passing framework."
},
{
"code": null,
"e": 8011,
"s": 7745,
"text": "Decoders: actually, traditional KG embedding algorithms like TransE, ConvE, RotatE, etc are good examples of decoders for the link prediction task. Originally, they can also be trained as decoder-only models optimized end-to-end directly 👉 on link prediction tasks."
},
{
"code": null,
"e": 8050,
"s": 8011,
"text": "Hmm, not that much 🤔 (as of Fall 2020)"
},
{
"code": null,
"e": 8064,
"s": 8050,
"text": "Encoders: ???"
},
{
"code": null,
"e": 8185,
"s": 8064,
"text": "Decoders: HINGE proposed by Rosso et al is an end-to-end CNN-based model for link prediction on hyper-relational graphs."
},
{
"code": null,
"e": 8464,
"s": 8185,
"text": "Well, we couldn’t cope with such a glaring abyss 🕳 in the GNN encoders part and proposed ⭐️ StarE ⭐️ in our recent EMNLP’20 paper “Message Passing for Hyper-Relational Knowledge Graphs” written together with Priyansh Trivedi, Gaurav Maheshwari, Ricardo Usbeck, and Jens Lehmann."
},
{
"code": null,
"e": 8551,
"s": 8464,
"text": "StarE is a multi-relational GNN encoder that extends CompGCN for hyper-relational KGs."
},
{
"code": null,
"e": 8637,
"s": 8551,
"text": "The name is inspired by RDF* 😊 StarE is designed with the following features in mind:"
},
{
"code": null,
"e": 8701,
"s": 8637,
"text": "Explicit modeling of relations, including qualifying relations;"
},
{
"code": null,
"e": 8807,
"s": 8701,
"text": "Separation of auxiliary entities and relations in qualifiers from entities and relations in main triples;"
},
{
"code": null,
"e": 8896,
"s": 8807,
"text": "Still, any entity and any relation can still be used in main triples as well qualifiers;"
},
{
"code": null,
"e": 9198,
"s": 8896,
"text": "Permutation invariance to the order of qualifiers — they do not exhibit any particular order and can be freely re-arranged. That is, it does not matter for the main triple <<Albert Einstein, educated at, ETH Zurich>> whether (academic degree, Bachelor) comes before (academic major, Physics) or after."
},
{
"code": null,
"e": 9298,
"s": 9198,
"text": "Let’s trace the evolution of relation-aware GNN encoders in their neighborhood aggregation schemes:"
},
{
"code": null,
"e": 9561,
"s": 9298,
"text": "In StarE, a main triple relation h_r appearing between nodes u and v is augmented with an aggregated vector of qualifiers h_q via a function gamma() which can be a weighted sum, multiplication, concat, or any other binary function (we went for the weighted sum)."
},
{
"code": null,
"e": 9590,
"s": 9561,
"text": "We obtain the vector h_qvia:"
},
{
"code": null,
"e": 10051,
"s": 9590,
"text": "That is, we first pool qualifier relation and entity embeddings h_{qr} and h_{qv}, respectively, in a single vector through a composition function phi_q() which could be a scoring function from the KG embedding family, e.g., RotatE. We then apply a permutation invariant aggregation function (sum, although we also probed multiplication) to pool an arbitrary number of qualifiers into a single vector and finally project it through a transformation matrix W_q."
},
{
"code": null,
"e": 10232,
"s": 10051,
"text": "Since all entities and relations can be generally seen in main triples as well as qualifiers, W_q is intended to learn qualifier-specific representations of entities and relations."
},
{
"code": null,
"e": 10470,
"s": 10232,
"text": "We still retain CompGCN components: phi_() is a composition function similar to phi_q(), but now it merges a node with an enriched edge representation. W_{\\lambda} is a weight parameter for incoming, outgoing, and self-looping relations."
},
{
"code": null,
"e": 10594,
"s": 10470,
"text": "GNNs operate on sparse matrices for efficiency reasons. For multi-relational triple-based KGs the following example triples"
},
{
"code": null,
"e": 10630,
"s": 10594,
"text": "Q937, P69, Q11942Q937, P69, Q206702"
},
{
"code": null,
"e": 10730,
"s": 10630,
"text": "Can be presented in the COO format as a [2, num_edges] tensor with an additional row for edge types"
},
{
"code": null,
"e": 10770,
"s": 10730,
"text": "[Q937, Q937][Q11942, Q206702][P69, P69]"
},
{
"code": null,
"e": 10836,
"s": 10770,
"text": "Hyper-relational facts with qualifiers can be written as follows:"
},
{
"code": null,
"e": 10924,
"s": 10836,
"text": "Q937, P69, Q206702, P812, Q413, P512, Q849697s, r, o, qr1, qv1, qr2, qv2, ..., qrN, qvN"
},
{
"code": null,
"e": 11093,
"s": 10924,
"text": "Where the first three entries always denote the “main” triple and the subsequent pairs are qualifiers in no particular order (remember the order invariance in Wikidata)"
},
{
"code": null,
"e": 11286,
"s": 11093,
"text": "What can be a sparse representation of hyper-relational KGs where each “column” of the COO matrix might have an arbitrary number of qualifiers? In the paper, we propose the following encoding:"
},
{
"code": null,
"e": 11321,
"s": 11286,
"text": "That is, we have two COO matrices:"
},
{
"code": null,
"e": 11907,
"s": 11321,
"text": "A normal “triple” COO with an implicit column index kA “qualifier” COO of the shape [3, num_qualifiers] where the first row contains indices of the columns in the “triple” COO, the second contains qualifier relations, and the third — qualifier entities. The index row connects a column of qualifiers to the main triple. That said, the columns in the “qualifier” COO that share the same index k belong to the same k-th triple in the “triple” COO matrix. This allows us to be O(q) in memory wrt to the number of qualifiers in the KG, and the overall memory is O(|edges|+|qualifiers|) ⚖.️"
},
{
"code": null,
"e": 11961,
"s": 11907,
"text": "A normal “triple” COO with an implicit column index k"
},
{
"code": null,
"e": 12494,
"s": 11961,
"text": "A “qualifier” COO of the shape [3, num_qualifiers] where the first row contains indices of the columns in the “triple” COO, the second contains qualifier relations, and the third — qualifier entities. The index row connects a column of qualifiers to the main triple. That said, the columns in the “qualifier” COO that share the same index k belong to the same k-th triple in the “triple” COO matrix. This allows us to be O(q) in memory wrt to the number of qualifiers in the KG, and the overall memory is O(|edges|+|qualifiers|) ⚖.️"
},
{
"code": null,
"e": 12839,
"s": 12494,
"text": "We briefly touched upon encoding hyper-relational facts as a sequence of entities and relations. But are there already reliable datasets for experimenting on such KGs? Traditionally, KG embeddings were evaluated on the link prediction task, while Graph ML tasks include node classification, graph classification, entity matching, and many more."
},
{
"code": null,
"e": 13077,
"s": 12839,
"text": "So far there exist only two link prediction datasets: WikiPeople proposed by Guan et al — it’s a dump of Wikidata describing, well, people, and JF17K— an export from Freebase 🧟♂️. However, we identified major drawbacks 😞 with those two:"
},
{
"code": null,
"e": 13536,
"s": 13077,
"text": "WikiPeople has too many qualifiers with literals (years). It is not advisable to treat literals as another sort of entities, as the numbers are continuous values and should be treated in this way (well, it is a general problem with literals in the KG embedding literature 🤔). That said, in most cases, such qualifiers are simply dropped. This results in a dataset where only 2% of facts have qualifiers, and 80% of those facts have only one qualifier pair :/"
},
{
"code": null,
"e": 14121,
"s": 13536,
"text": "JF17K has test set leakages. In fact, the authors themselves identified ‘significantly many redundant triples’ and do not recommend using it in the experiments. Being originally more of an n-ary dataset, HINGE transformed it into a hyper-relational format with auxiliary predicates. We conducted a further study and found that more than 40% of the test statements share the same (s,r,o) main triple as in the train set. That is, in the subject/object prediction task, a simple triple-only heuristic can outperform 🏆 all previous hyper-relational approaches which we show in the paper."
},
{
"code": null,
"e": 14270,
"s": 14121,
"text": "As both two datasets are not that suitable for evaluating hyper-relational approaches, we sampled WD50K from Wikidata with the following guidelines:"
},
{
"code": null,
"e": 14428,
"s": 14270,
"text": "Retain Wikidata-like distribution of qualifiers. In the vanilla WD50K, about 13% of statements have qualifiers (close to 17% of total statements in Wikidata)"
},
{
"code": null,
"e": 14482,
"s": 14428,
"text": "All qualifiers are entity-relation pairs, no literals"
},
{
"code": null,
"e": 14548,
"s": 14482,
"text": "Entities and relations can be seen in main triples and qualifiers"
},
{
"code": null,
"e": 14597,
"s": 14548,
"text": "99% of statements have at most 6 qualifier pairs"
},
{
"code": null,
"e": 14656,
"s": 14597,
"text": "For further experiments, we sampled 3 additional datasets:"
},
{
"code": null,
"e": 14709,
"s": 14656,
"text": "WD50K (33) — about 33% of statements have qualifiers"
},
{
"code": null,
"e": 14762,
"s": 14709,
"text": "WD50K (66) — about 66% of statements have qualifiers"
},
{
"code": null,
"e": 14807,
"s": 14762,
"text": "WD50K (100) — all statements have qualifiers"
},
{
"code": null,
"e": 14920,
"s": 14807,
"text": "Naturally, those datasets are smaller than the original WD50K with more qualifier-unique entities and relations."
},
{
"code": null,
"e": 15053,
"s": 14920,
"text": "At this step, we finally have a StarE encoder and suitable link prediction datasets for the experiments. Our main research question:"
},
{
"code": null,
"e": 15131,
"s": 15053,
"text": "Do qualifiers help to predict subjects and objects of hyper-relational facts?"
},
{
"code": null,
"e": 15399,
"s": 15131,
"text": "That is, given subject, predicate, and all qualifiers we predict the object or vice versa for a subject. For that, we linearize a given fact into a sequence as shown in the illustration and use a 2-layer Transformer with avg pooling and a final FC layer as a decoder."
},
{
"code": null,
"e": 15547,
"s": 15399,
"text": "The Transformer also allows us to feed sequences of different lengths using padding tokens which are masked 👺 from the self-attention computations."
},
{
"code": null,
"e": 15693,
"s": 15547,
"text": "For comparison, we applied decoder-only HINGE and 2-layer Transformer on the same task to measure if the StarE encoder brings any benefits there."
},
{
"code": null,
"e": 15720,
"s": 15693,
"text": "Well, turns out it does! 🎆"
},
{
"code": null,
"e": 15740,
"s": 15720,
"text": "What we observe 🕵 :"
},
{
"code": null,
"e": 15837,
"s": 15740,
"text": "StarE drastically increases the link prediction performance compared to decoder-only approaches;"
},
{
"code": null,
"e": 15945,
"s": 15837,
"text": "StarE is even more effective (the performance gap is larger) when there are more qualifiers in the dataset;"
},
{
"code": null,
"e": 16065,
"s": 15945,
"text": "Hyper-relational approaches do help to better predict subjects and objects given qualifiers that triple-only baselines."
},
{
"code": null,
"e": 16145,
"s": 16065,
"text": "How many qualifiers do you need to see the quality improve? Just 2 are enough 😉"
},
{
"code": null,
"e": 16258,
"s": 16145,
"text": "Our experimental program with particular numbers and interactive charts is reported with Weights & Biases here 📈"
},
{
"code": null,
"e": 16298,
"s": 16258,
"text": "So the takeaways 🔖 to the KG community:"
},
{
"code": null,
"e": 16436,
"s": 16298,
"text": "Seek to assign descriptive qualifiers to more triple facts in the graph — the more the betterIf you do assign qualifiers — add 2 or more!"
},
{
"code": null,
"e": 16530,
"s": 16436,
"text": "Seek to assign descriptive qualifiers to more triple facts in the graph — the more the better"
},
{
"code": null,
"e": 16575,
"s": 16530,
"text": "If you do assign qualifiers — add 2 or more!"
},
{
"code": null,
"e": 16674,
"s": 16575,
"text": "Hyper-relational graphs are closer to reality and describe facts in more detail than plain triples"
},
{
"code": null,
"e": 16731,
"s": 16674,
"text": "RDF* and LPG provide means to build hyper-relational KGs"
},
{
"code": null,
"e": 16787,
"s": 16731,
"text": "A hyper-relational graph is different from a hypergraph"
},
{
"code": null,
"e": 16866,
"s": 16787,
"text": "Hyper-relational KGs are already in use — both in open-domain KGs and industry"
},
{
"code": null,
"e": 16983,
"s": 16866,
"text": "RDF* motivated StarE — a GNN encoder for hyper-relational KGs that can be paired with a decoder for downstream tasks"
},
{
"code": null,
"e": 17050,
"s": 16983,
"text": "StarE improves link prediction compared to decoder-only approaches"
},
{
"code": null,
"e": 17150,
"s": 17050,
"text": "The WD50K datasets family better captures the challenges of link prediction on hyper-relational KGs"
},
{
"code": null,
"e": 17184,
"s": 17150,
"text": "You can find more information in:"
}
] |
Introduction to Rust Programming Language - GeeksforGeeks | 23 Nov, 2021
Rust is a blazing fast and memory-efficient static compiled language with a rich type system and ownership model. It can be used to power performance-critical services while guaranteeing memory-safety and thread-safety, empowering developers to debug at compile-time. In addition to that Rust has great documentation and a user-friendly compiler with top-end tools like integrated package managers and multi-editor with features like type inspection and auto-completion. Rust prevents all the crashes, and it is very interesting that rust is safe by default like JavaScript, Ruby, and Python. This is much powerful than C/C++ because we cannot write the wrong parallel code you can never see fault in rust. It is very fast in representing a lot of programming paradigms very well.
But the question arises as there are already so many programming languages like Python, C++, Java, etc, then why the need for developing a new programming language. The answer to this is the other programming language has a lot of control over the hardware that you are running, like, you can optimize it well, translate directly to assembly code, But it’s not very safe.
So rust provides us all the controls that we can have and all the levels of security that we can achieve.
Rust is using Rust which means the all the standard compiler the libraries are written in rust, there is a bit of use of C programming language but most of them is Rust. The big project of Rust is “servo”, It is a project to write out the totally parallel layout engine like things like a gecko as Firefox or WebKit in safari.
Servo built the layout engine something to render HTML from bottom to top.
Functions are the block of reusable code that can perform similar related actions. You have already seen one of the most important functions in the language: the main function, which is the entry point of many programs. You’ve also seen the “fn” keyword, which allows you to declare new functions. Rust code uses snake case as the conventional style for function and variable names. In snake case, all letters are lowercase and underscore separate words.
Syntax:
fn functionname(arguments){
code
}
To create a function we need to use the fn keyword.
The function name is written after the fn keyword
Arguments are passed after function name inside parenthesis
You can write function code in function block
Example: The below function simply prints “Hello, World!” in the console:
Rust
fn main() { println!("Hello, world!");}
Output:
Hello, World!
The concept of ownership is that when you own something you can decide to pass it to someone else, if you have a book, and you have done reading it you can permanently give it to someone and not worry about it.
Rust
fn helper() -> Box<int> {let three = box 3;return three; //transfer ownership}fn main() {// acquire ownership of return valuelet my_three = helper();}
Owned values in rust can be borrowed to allow usage for a certain period of time The “&” sign represents the borrowed reference. Borrowed values have a lifetime and are valid for that time only. Borrowing prevents moving. While there is an active borrow I can not transfer ownership. I still own it but cannot transfer it until I handed it in to really relinquish that borrowed.
Rust
let a: ∫{let b =3; //b lifetime is not same as aa =&b;} //
Here “a” and “b” has a different lifetime, so it will not work.
Rust
let a: ∫let b=3; // a and b have same lifetimea = &b;
Here “a” and “b” have the same life, so it will work. Borrow can be nested. Through cloning, borrowed values can become owned.
Rust has fine-grain memory management but is automatically managed once created.In Rust when you allocate memory you never have to really free it you can decide when to free it but never call it. Rust takes care of it automatically.Each variable has a scope it is valid for, and it gets automatically deallocated once it goes out of scope.In rust, each program is allocated memory from the operating system.Rust also has a shared memory where we can have a reference piece of data, we can use ownership to keep track of reference count.
Rust has fine-grain memory management but is automatically managed once created.
In Rust when you allocate memory you never have to really free it you can decide when to free it but never call it. Rust takes care of it automatically.
Each variable has a scope it is valid for, and it gets automatically deallocated once it goes out of scope.
In rust, each program is allocated memory from the operating system.
Rust also has a shared memory where we can have a reference piece of data, we can use ownership to keep track of reference count.
Heap:
It is the biggest memory block and is managed by the rust ownership model.
At this place, all the dynamic data is stored.
Stack:
All values in rust are allocated on the stack.
At this, the static memory is allocated by default.
There is one stack per thread.
It includes structures and pointers to dynamic data.
Values in rust are immutable by default and must be tagged as being mutable(if needed).
Example:
Rust
let x = 2;x = 9; //it will show an error
The above example will show an error because we have not tagged it as mutable.
Rust
let mut x = 2;x = 9; //work correctly
This will work fine as we have tagged it as being mutable. As in this case we are explicitly mutating it.
The structure is a user-defined data type in rust that is used to combine different data items of a different type. Structure defines data as a key-value pair. The struct keyword is used to define Structures in Rust.
Syntax:
struct Name_of_structure {
field1:data_type,
field2:data_type,
field3:data_type
}
Example:
Rust
struct Employee { name: String, company: String, employee_id: u32, profile: String }fn main() { let value = Employee { name: String::from("Geek"), company: String::from("Geeksforgeeks.org"), employee_id: 007, profile:String::from("Manager"), }; println!("Employee: {} of {} Company bearing EmployeeID {} is of {} level.", value.name, value.company, value.employee_id, value.profile);}
Output:
Employee: Geek of Geeksforgeeks.org Company bearing EmployeeID 7 is of Manager level.
This is an example of how we create structures in rust. This will compile perfectly.
A tuple in rust is a finite heterogeneous compound data type, meaning it can store more than one value at once. In tuples, there is no inbuilt method to add elements into a tuple. We can use the index to get the value of a tuple, and we also can not iterate over a tuple using for loop.
Tuples in Rust are defined using small brackets as shown below :
Syntax: ("geeksforgeeks", 1, 'geek')
Example:
Rust
// Rust program to get value from tuple// using indexfn main() { let gfg = ("cp", "algo", "FAANG", "Data Structure"); // complete tuple println!("complete tuple = {:?} ", gfg ); // first value println!("at 0 index = {} ", gfg.0 ); // second value println!("at 0 index = {} ", gfg.1 ); // third value println!("at 0 index = {} ", gfg.2 ); // fourth value println!("at 0 index = {} ", gfg.3 );}
Output:
complete tuple = ("cp", "algo", "FAANG", "Data Structure")
at 0 index = cp
at 0 index = algo
at 0 index = FAANG
at 0 index = Data Structure
In Rust, every variable, value, and item has a type. The type defines how much memory it is holding and which operation can be performed on the value. The below table states all the types in Rust:
Advantages:
Quick debugging and testing: Rust is a very fast language and supports quick and effective debugging.Rust supports more complex code as compared to other languages, so we can achieve more in less code.It enables cross-platform development.Ease of integration: Rust can be easily integrated with C and many other famous programming languages.Rust is safer than other programming languages.There is a wide community of developer which support Rust.
Quick debugging and testing: Rust is a very fast language and supports quick and effective debugging.
Rust supports more complex code as compared to other languages, so we can achieve more in less code.
It enables cross-platform development.
Ease of integration: Rust can be easily integrated with C and many other famous programming languages.
Rust is safer than other programming languages.
There is a wide community of developer which support Rust.
Disadvantages:
Due to complexity, it may take a longer time to learn Rust.In rust, code can be less efficient and also it takes more time to compile.As it is more complex, so it may take more time to complete apps written in Rust.It is a new language, so it will take more time to spread over and jobs in rust also may not be as much as in other popular programming languages.In some cases, rust can leak memory and become slower than a popular programming language.
Due to complexity, it may take a longer time to learn Rust.
In rust, code can be less efficient and also it takes more time to compile.
As it is more complex, so it may take more time to complete apps written in Rust.
It is a new language, so it will take more time to spread over and jobs in rust also may not be as much as in other popular programming languages.
In some cases, rust can leak memory and become slower than a popular programming language.
varshagumber28
as5853535
Picked
Rust-basics
Rust
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Rust - Casting
Rust - For and Range
Rust - Generic Function
Rust - References & Borrowing
Rust - While Loop
Rust - Box Smart Pointer
Rust - Concept of Structures
Primitive Compound Datatypes in Rust
Rust - Recoverable Errors
Rust - Concept of Smart Pointers | [
{
"code": null,
"e": 23222,
"s": 23194,
"text": "\n23 Nov, 2021"
},
{
"code": null,
"e": 24004,
"s": 23222,
"text": "Rust is a blazing fast and memory-efficient static compiled language with a rich type system and ownership model. It can be used to power performance-critical services while guaranteeing memory-safety and thread-safety, empowering developers to debug at compile-time. In addition to that Rust has great documentation and a user-friendly compiler with top-end tools like integrated package managers and multi-editor with features like type inspection and auto-completion. Rust prevents all the crashes, and it is very interesting that rust is safe by default like JavaScript, Ruby, and Python. This is much powerful than C/C++ because we cannot write the wrong parallel code you can never see fault in rust. It is very fast in representing a lot of programming paradigms very well. "
},
{
"code": null,
"e": 24376,
"s": 24004,
"text": "But the question arises as there are already so many programming languages like Python, C++, Java, etc, then why the need for developing a new programming language. The answer to this is the other programming language has a lot of control over the hardware that you are running, like, you can optimize it well, translate directly to assembly code, But it’s not very safe."
},
{
"code": null,
"e": 24482,
"s": 24376,
"text": "So rust provides us all the controls that we can have and all the levels of security that we can achieve."
},
{
"code": null,
"e": 24810,
"s": 24482,
"text": "Rust is using Rust which means the all the standard compiler the libraries are written in rust, there is a bit of use of C programming language but most of them is Rust. The big project of Rust is “servo”, It is a project to write out the totally parallel layout engine like things like a gecko as Firefox or WebKit in safari."
},
{
"code": null,
"e": 24885,
"s": 24810,
"text": "Servo built the layout engine something to render HTML from bottom to top."
},
{
"code": null,
"e": 25340,
"s": 24885,
"text": "Functions are the block of reusable code that can perform similar related actions. You have already seen one of the most important functions in the language: the main function, which is the entry point of many programs. You’ve also seen the “fn” keyword, which allows you to declare new functions. Rust code uses snake case as the conventional style for function and variable names. In snake case, all letters are lowercase and underscore separate words."
},
{
"code": null,
"e": 25348,
"s": 25340,
"text": "Syntax:"
},
{
"code": null,
"e": 25385,
"s": 25348,
"text": "fn functionname(arguments){\n code\n}"
},
{
"code": null,
"e": 25437,
"s": 25385,
"text": "To create a function we need to use the fn keyword."
},
{
"code": null,
"e": 25487,
"s": 25437,
"text": "The function name is written after the fn keyword"
},
{
"code": null,
"e": 25547,
"s": 25487,
"text": "Arguments are passed after function name inside parenthesis"
},
{
"code": null,
"e": 25593,
"s": 25547,
"text": "You can write function code in function block"
},
{
"code": null,
"e": 25667,
"s": 25593,
"text": "Example: The below function simply prints “Hello, World!” in the console:"
},
{
"code": null,
"e": 25672,
"s": 25667,
"text": "Rust"
},
{
"code": "fn main() { println!(\"Hello, world!\");}",
"e": 25714,
"s": 25672,
"text": null
},
{
"code": null,
"e": 25722,
"s": 25714,
"text": "Output:"
},
{
"code": null,
"e": 25736,
"s": 25722,
"text": "Hello, World!"
},
{
"code": null,
"e": 25948,
"s": 25736,
"text": "The concept of ownership is that when you own something you can decide to pass it to someone else, if you have a book, and you have done reading it you can permanently give it to someone and not worry about it. "
},
{
"code": null,
"e": 25953,
"s": 25948,
"text": "Rust"
},
{
"code": "fn helper() -> Box<int> {let three = box 3;return three; //transfer ownership}fn main() {// acquire ownership of return valuelet my_three = helper();}",
"e": 26104,
"s": 25953,
"text": null
},
{
"code": null,
"e": 26484,
"s": 26104,
"text": "Owned values in rust can be borrowed to allow usage for a certain period of time The “&” sign represents the borrowed reference. Borrowed values have a lifetime and are valid for that time only. Borrowing prevents moving. While there is an active borrow I can not transfer ownership. I still own it but cannot transfer it until I handed it in to really relinquish that borrowed. "
},
{
"code": null,
"e": 26489,
"s": 26484,
"text": "Rust"
},
{
"code": "let a: ∫{let b =3; //b lifetime is not same as aa =&b;} //",
"e": 26553,
"s": 26489,
"text": null
},
{
"code": null,
"e": 26617,
"s": 26553,
"text": "Here “a” and “b” has a different lifetime, so it will not work."
},
{
"code": null,
"e": 26622,
"s": 26617,
"text": "Rust"
},
{
"code": "let a: ∫let b=3; // a and b have same lifetimea = &b;",
"e": 26681,
"s": 26622,
"text": null
},
{
"code": null,
"e": 26808,
"s": 26681,
"text": "Here “a” and “b” have the same life, so it will work. Borrow can be nested. Through cloning, borrowed values can become owned."
},
{
"code": null,
"e": 27345,
"s": 26808,
"text": "Rust has fine-grain memory management but is automatically managed once created.In Rust when you allocate memory you never have to really free it you can decide when to free it but never call it. Rust takes care of it automatically.Each variable has a scope it is valid for, and it gets automatically deallocated once it goes out of scope.In rust, each program is allocated memory from the operating system.Rust also has a shared memory where we can have a reference piece of data, we can use ownership to keep track of reference count."
},
{
"code": null,
"e": 27426,
"s": 27345,
"text": "Rust has fine-grain memory management but is automatically managed once created."
},
{
"code": null,
"e": 27579,
"s": 27426,
"text": "In Rust when you allocate memory you never have to really free it you can decide when to free it but never call it. Rust takes care of it automatically."
},
{
"code": null,
"e": 27687,
"s": 27579,
"text": "Each variable has a scope it is valid for, and it gets automatically deallocated once it goes out of scope."
},
{
"code": null,
"e": 27756,
"s": 27687,
"text": "In rust, each program is allocated memory from the operating system."
},
{
"code": null,
"e": 27886,
"s": 27756,
"text": "Rust also has a shared memory where we can have a reference piece of data, we can use ownership to keep track of reference count."
},
{
"code": null,
"e": 27892,
"s": 27886,
"text": "Heap:"
},
{
"code": null,
"e": 27967,
"s": 27892,
"text": "It is the biggest memory block and is managed by the rust ownership model."
},
{
"code": null,
"e": 28014,
"s": 27967,
"text": "At this place, all the dynamic data is stored."
},
{
"code": null,
"e": 28021,
"s": 28014,
"text": "Stack:"
},
{
"code": null,
"e": 28068,
"s": 28021,
"text": "All values in rust are allocated on the stack."
},
{
"code": null,
"e": 28120,
"s": 28068,
"text": "At this, the static memory is allocated by default."
},
{
"code": null,
"e": 28151,
"s": 28120,
"text": "There is one stack per thread."
},
{
"code": null,
"e": 28204,
"s": 28151,
"text": "It includes structures and pointers to dynamic data."
},
{
"code": null,
"e": 28292,
"s": 28204,
"text": "Values in rust are immutable by default and must be tagged as being mutable(if needed)."
},
{
"code": null,
"e": 28301,
"s": 28292,
"text": "Example:"
},
{
"code": null,
"e": 28306,
"s": 28301,
"text": "Rust"
},
{
"code": "let x = 2;x = 9; //it will show an error",
"e": 28347,
"s": 28306,
"text": null
},
{
"code": null,
"e": 28426,
"s": 28347,
"text": "The above example will show an error because we have not tagged it as mutable."
},
{
"code": null,
"e": 28431,
"s": 28426,
"text": "Rust"
},
{
"code": "let mut x = 2;x = 9; //work correctly",
"e": 28470,
"s": 28431,
"text": null
},
{
"code": null,
"e": 28576,
"s": 28470,
"text": "This will work fine as we have tagged it as being mutable. As in this case we are explicitly mutating it."
},
{
"code": null,
"e": 28793,
"s": 28576,
"text": "The structure is a user-defined data type in rust that is used to combine different data items of a different type. Structure defines data as a key-value pair. The struct keyword is used to define Structures in Rust."
},
{
"code": null,
"e": 28802,
"s": 28793,
"text": "Syntax: "
},
{
"code": null,
"e": 28890,
"s": 28802,
"text": "struct Name_of_structure {\n field1:data_type,\n field2:data_type,\n field3:data_type\n}"
},
{
"code": null,
"e": 28899,
"s": 28890,
"text": "Example:"
},
{
"code": null,
"e": 28904,
"s": 28899,
"text": "Rust"
},
{
"code": "struct Employee { name: String, company: String, employee_id: u32, profile: String }fn main() { let value = Employee { name: String::from(\"Geek\"), company: String::from(\"Geeksforgeeks.org\"), employee_id: 007, profile:String::from(\"Manager\"), }; println!(\"Employee: {} of {} Company bearing EmployeeID {} is of {} level.\", value.name, value.company, value.employee_id, value.profile);}",
"e": 29321,
"s": 28904,
"text": null
},
{
"code": null,
"e": 29329,
"s": 29321,
"text": "Output:"
},
{
"code": null,
"e": 29415,
"s": 29329,
"text": "Employee: Geek of Geeksforgeeks.org Company bearing EmployeeID 7 is of Manager level."
},
{
"code": null,
"e": 29500,
"s": 29415,
"text": "This is an example of how we create structures in rust. This will compile perfectly."
},
{
"code": null,
"e": 29787,
"s": 29500,
"text": "A tuple in rust is a finite heterogeneous compound data type, meaning it can store more than one value at once. In tuples, there is no inbuilt method to add elements into a tuple. We can use the index to get the value of a tuple, and we also can not iterate over a tuple using for loop."
},
{
"code": null,
"e": 29852,
"s": 29787,
"text": "Tuples in Rust are defined using small brackets as shown below :"
},
{
"code": null,
"e": 29889,
"s": 29852,
"text": "Syntax: (\"geeksforgeeks\", 1, 'geek')"
},
{
"code": null,
"e": 29898,
"s": 29889,
"text": "Example:"
},
{
"code": null,
"e": 29903,
"s": 29898,
"text": "Rust"
},
{
"code": "// Rust program to get value from tuple// using indexfn main() { let gfg = (\"cp\", \"algo\", \"FAANG\", \"Data Structure\"); // complete tuple println!(\"complete tuple = {:?} \", gfg ); // first value println!(\"at 0 index = {} \", gfg.0 ); // second value println!(\"at 0 index = {} \", gfg.1 ); // third value println!(\"at 0 index = {} \", gfg.2 ); // fourth value println!(\"at 0 index = {} \", gfg.3 );}",
"e": 30359,
"s": 29903,
"text": null
},
{
"code": null,
"e": 30367,
"s": 30359,
"text": "Output:"
},
{
"code": null,
"e": 30512,
"s": 30367,
"text": "complete tuple = (\"cp\", \"algo\", \"FAANG\", \"Data Structure\") \nat 0 index = cp \nat 0 index = algo \nat 0 index = FAANG \nat 0 index = Data Structure "
},
{
"code": null,
"e": 30709,
"s": 30512,
"text": "In Rust, every variable, value, and item has a type. The type defines how much memory it is holding and which operation can be performed on the value. The below table states all the types in Rust:"
},
{
"code": null,
"e": 30721,
"s": 30709,
"text": "Advantages:"
},
{
"code": null,
"e": 31168,
"s": 30721,
"text": "Quick debugging and testing: Rust is a very fast language and supports quick and effective debugging.Rust supports more complex code as compared to other languages, so we can achieve more in less code.It enables cross-platform development.Ease of integration: Rust can be easily integrated with C and many other famous programming languages.Rust is safer than other programming languages.There is a wide community of developer which support Rust."
},
{
"code": null,
"e": 31270,
"s": 31168,
"text": "Quick debugging and testing: Rust is a very fast language and supports quick and effective debugging."
},
{
"code": null,
"e": 31371,
"s": 31270,
"text": "Rust supports more complex code as compared to other languages, so we can achieve more in less code."
},
{
"code": null,
"e": 31410,
"s": 31371,
"text": "It enables cross-platform development."
},
{
"code": null,
"e": 31513,
"s": 31410,
"text": "Ease of integration: Rust can be easily integrated with C and many other famous programming languages."
},
{
"code": null,
"e": 31561,
"s": 31513,
"text": "Rust is safer than other programming languages."
},
{
"code": null,
"e": 31620,
"s": 31561,
"text": "There is a wide community of developer which support Rust."
},
{
"code": null,
"e": 31635,
"s": 31620,
"text": "Disadvantages:"
},
{
"code": null,
"e": 32087,
"s": 31635,
"text": "Due to complexity, it may take a longer time to learn Rust.In rust, code can be less efficient and also it takes more time to compile.As it is more complex, so it may take more time to complete apps written in Rust.It is a new language, so it will take more time to spread over and jobs in rust also may not be as much as in other popular programming languages.In some cases, rust can leak memory and become slower than a popular programming language."
},
{
"code": null,
"e": 32147,
"s": 32087,
"text": "Due to complexity, it may take a longer time to learn Rust."
},
{
"code": null,
"e": 32223,
"s": 32147,
"text": "In rust, code can be less efficient and also it takes more time to compile."
},
{
"code": null,
"e": 32305,
"s": 32223,
"text": "As it is more complex, so it may take more time to complete apps written in Rust."
},
{
"code": null,
"e": 32452,
"s": 32305,
"text": "It is a new language, so it will take more time to spread over and jobs in rust also may not be as much as in other popular programming languages."
},
{
"code": null,
"e": 32543,
"s": 32452,
"text": "In some cases, rust can leak memory and become slower than a popular programming language."
},
{
"code": null,
"e": 32558,
"s": 32543,
"text": "varshagumber28"
},
{
"code": null,
"e": 32568,
"s": 32558,
"text": "as5853535"
},
{
"code": null,
"e": 32575,
"s": 32568,
"text": "Picked"
},
{
"code": null,
"e": 32587,
"s": 32575,
"text": "Rust-basics"
},
{
"code": null,
"e": 32592,
"s": 32587,
"text": "Rust"
},
{
"code": null,
"e": 32690,
"s": 32592,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32699,
"s": 32690,
"text": "Comments"
},
{
"code": null,
"e": 32712,
"s": 32699,
"text": "Old Comments"
},
{
"code": null,
"e": 32727,
"s": 32712,
"text": "Rust - Casting"
},
{
"code": null,
"e": 32748,
"s": 32727,
"text": "Rust - For and Range"
},
{
"code": null,
"e": 32772,
"s": 32748,
"text": "Rust - Generic Function"
},
{
"code": null,
"e": 32802,
"s": 32772,
"text": "Rust - References & Borrowing"
},
{
"code": null,
"e": 32820,
"s": 32802,
"text": "Rust - While Loop"
},
{
"code": null,
"e": 32845,
"s": 32820,
"text": "Rust - Box Smart Pointer"
},
{
"code": null,
"e": 32874,
"s": 32845,
"text": "Rust - Concept of Structures"
},
{
"code": null,
"e": 32911,
"s": 32874,
"text": "Primitive Compound Datatypes in Rust"
},
{
"code": null,
"e": 32937,
"s": 32911,
"text": "Rust - Recoverable Errors"
}
] |
Program to implement Simpson’s 3/8 rule | 16 May, 2022
Write a program to implement Simpson’s 3/8 rule.The Simpson’s 3/8 rule was developed by Thomas Simpson. This method is used for performing numerical integrations. This method is generally used for numerical approximation of definite integrals. Here, parabolas are used to approximate each part of curve.Simpson’s 3/8 formula := [Tex]( [/Tex]F(a) + 3F [Tex]\frac{2a + b}{3} ) [/Tex]+ 3F[Tex]\frac{a + 2b}{3} ) [/Tex]+ F(b) Here, h is the interval size given by h = ( b – a ) / n n is number of intervals or interval limitExamples :
Input : lower_limit = 1, upper_limit = 10,
interval_limit = 10
Output : integration_result = 0.687927
Input : lower_limit = 1, upper_limit = 5,
interval_limit = 3
Output : integration_result = 0.605835
C++
Java
Python3
C#
PHP
Javascript
// CPP program to implement Simpson's rule#include<iostream>using namespace std; // Given function to be integratedfloat func( float x){ return (1 / ( 1 + x * x ));} // Function to perform calculationsfloat calculate(float lower_limit, float upper_limit, int interval_limit ){ float value; float interval_size = (upper_limit - lower_limit) / interval_limit; float sum = func(lower_limit) + func(upper_limit); // Calculates value till integral limit for (int i = 1 ; i < interval_limit ; i++) { if (i % 3 == 0) sum = sum + 2 * func(lower_limit + i * interval_size); else sum = sum + 3 * func(lower_limit + i * interval_size); } return ( 3 * interval_size / 8 ) * sum ;} // Driver Codeint main(){ int interval_limit = 10; float lower_limit = 1; float upper_limit = 10; float integral_res = calculate(lower_limit, upper_limit, interval_limit); cout << integral_res; return 0;}
// Java Code to implement Simpson's ruleimport java.util.*; class GFG { // Given function to be integrated static float func( float x) { return (1 / ( 1 + x * x )); } // Function to perform calculations static float calculate(float lower_limit, float upper_limit, int interval_limit ) { float value; float interval_size = (upper_limit - lower_limit) / interval_limit; float sum = func(lower_limit) + func(upper_limit); // Calculates value till integral limit for (int i = 1 ; i < interval_limit ; i++) { if (i % 3 == 0) sum = sum + 2 * func(lower_limit + i * interval_size); else sum = sum + 3 * func(lower_limit + i * interval_size); } return ( 3 * interval_size / 8 ) * sum ; } // Driver program to test above function public static void main(String[] args) { int interval_limit = 10; float lower_limit = 1; float upper_limit = 10; float integral_res = calculate(lower_limit, upper_limit, interval_limit); System.out.println(integral_res); } } // This article is contributed by Arnav Kr. Mandal.
# Python3 code to implement# Simpson's rule # Given function to be# integrateddef func(x): return (float(1) / ( 1 + x * x )) # Function to perform calculationsdef calculate(lower_limit, upper_limit, interval_limit ): interval_size = (float(upper_limit - lower_limit) / interval_limit) sum = func(lower_limit) + func(upper_limit); # Calculates value till integral limit for i in range(1, interval_limit ): if (i % 3 == 0): sum = sum + 2 * func(lower_limit + i * interval_size) else: sum = sum + 3 * func(lower_limit + i * interval_size) return ((float( 3 * interval_size) / 8 ) * sum ) # driver functioninterval_limit = 10lower_limit = 1upper_limit = 10 integral_res = calculate(lower_limit, upper_limit, interval_limit) # rounding the final answer to 6 decimal placesprint (round(integral_res, 6)) # This code is contributed by Saloni.
// C# Code to implement Simpson's ruleusing System; class GFG { // Given function to be integrated static float func( float x) { return (1 / ( 1 + x * x )); } // Function to perform calculations static float calculate(float lower_limit, float upper_limit, int interval_limit ) { //float value; float interval_size = (upper_limit - lower_limit) / interval_limit; float sum = func(lower_limit) + func(upper_limit); // Calculates value till integral limit for (int i = 1 ; i < interval_limit ; i++) { if (i % 3 == 0) sum = sum + 2 * func(lower_limit + i * interval_size); else sum = sum + 3 * func(lower_limit + i * interval_size); } return ( 3 * interval_size / 8 ) * sum ; } // Driver program to test above function public static void Main() { int interval_limit = 10; float lower_limit = 1; float upper_limit = 10; float integral_res = calculate(lower_limit, upper_limit, interval_limit); Console.WriteLine(integral_res); } } // This code is contributed by Vt_m.
<?php// PHP program to implement// Simpson's rule // Given function to be integratedfunction func( $x){ return (1 / ( 1 + $x * $x ));} // Function to perform calculationsfunction calculate($lower_limit, $upper_limit, $interval_limit){ $interval_size = ($upper_limit - $lower_limit) / $interval_limit; $sum = func($lower_limit) + func($upper_limit); // Calculates value till // integral limit for ($i = 1 ; $i < $interval_limit ; $i++) { if ($i % 3 == 0) $sum = $sum + 2 * func($lower_limit + $i * $interval_size); else $sum = $sum + 3 * func($lower_limit + $i * $interval_size); } return ( 3 * $interval_size / 8 ) * $sum ;} // Driver Code$interval_limit = 10;$lower_limit = 1;$upper_limit = 10;$integral_res = calculate($lower_limit, $upper_limit, $interval_limit); echo $integral_res; // This code is contributed by mits.?>
<script> // javascript program to implement Simpson's rule // Given function to be integrated function func(x) { return (1 / ( 1 + x * x )); } // Function to perform calculations function calculate(lower_limit, upper_limit, interval_limit ) { let value; let interval_size = (upper_limit - lower_limit) / interval_limit; let sum = func(lower_limit) + func(upper_limit); // Calculates value till integral limit for (let i = 1 ; i < interval_limit ; i++) { if (i % 3 == 0) sum = sum + 2 * func(lower_limit + i * interval_size); else sum = sum + 3 * func(lower_limit + i * interval_size); } return ( 3 * interval_size / 8 ) * sum ; } // Driver Function let interval_limit = 10; let lower_limit = 1; let upper_limit = 10; let integral_res = calculate(lower_limit, upper_limit, interval_limit); document.write(integral_res); // This code is contributed by susmitakundugoaldanga.</script>
Output :
0.687927
Mithun Kumar
susmitakundugoaldanga
simmytarika5
Algebra
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Algorithm to solve Rubik's Cube
Merge two sorted arrays with O(1) extra space
Program to print prime numbers from 1 to N.
Segment Tree | Set 1 (Sum of given range)
Check if a number is Palindrome
Count ways to reach the n'th stair
Fizz Buzz Implementation
Median of two sorted arrays of same size
Product of Array except itself
Find Union and Intersection of two unsorted arrays | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n16 May, 2022"
},
{
"code": null,
"e": 591,
"s": 52,
"text": "Write a program to implement Simpson’s 3/8 rule.The Simpson’s 3/8 rule was developed by Thomas Simpson. This method is used for performing numerical integrations. This method is generally used for numerical approximation of definite integrals. Here, parabolas are used to approximate each part of curve.Simpson’s 3/8 formula := [Tex]( [/Tex]F(a) + 3F [Tex]\\frac{2a + b}{3} ) [/Tex]+ 3F[Tex]\\frac{a + 2b}{3} ) [/Tex]+ F(b) Here, h is the interval size given by h = ( b – a ) / n n is number of intervals or interval limitExamples : "
},
{
"code": null,
"e": 813,
"s": 591,
"text": "Input : lower_limit = 1, upper_limit = 10, \n interval_limit = 10\nOutput : integration_result = 0.687927\n\n\nInput : lower_limit = 1, upper_limit = 5, \n interval_limit = 3\nOutput : integration_result = 0.605835"
},
{
"code": null,
"e": 821,
"s": 817,
"text": "C++"
},
{
"code": null,
"e": 826,
"s": 821,
"text": "Java"
},
{
"code": null,
"e": 834,
"s": 826,
"text": "Python3"
},
{
"code": null,
"e": 837,
"s": 834,
"text": "C#"
},
{
"code": null,
"e": 841,
"s": 837,
"text": "PHP"
},
{
"code": null,
"e": 852,
"s": 841,
"text": "Javascript"
},
{
"code": "// CPP program to implement Simpson's rule#include<iostream>using namespace std; // Given function to be integratedfloat func( float x){ return (1 / ( 1 + x * x ));} // Function to perform calculationsfloat calculate(float lower_limit, float upper_limit, int interval_limit ){ float value; float interval_size = (upper_limit - lower_limit) / interval_limit; float sum = func(lower_limit) + func(upper_limit); // Calculates value till integral limit for (int i = 1 ; i < interval_limit ; i++) { if (i % 3 == 0) sum = sum + 2 * func(lower_limit + i * interval_size); else sum = sum + 3 * func(lower_limit + i * interval_size); } return ( 3 * interval_size / 8 ) * sum ;} // Driver Codeint main(){ int interval_limit = 10; float lower_limit = 1; float upper_limit = 10; float integral_res = calculate(lower_limit, upper_limit, interval_limit); cout << integral_res; return 0;}",
"e": 1883,
"s": 852,
"text": null
},
{
"code": "// Java Code to implement Simpson's ruleimport java.util.*; class GFG { // Given function to be integrated static float func( float x) { return (1 / ( 1 + x * x )); } // Function to perform calculations static float calculate(float lower_limit, float upper_limit, int interval_limit ) { float value; float interval_size = (upper_limit - lower_limit) / interval_limit; float sum = func(lower_limit) + func(upper_limit); // Calculates value till integral limit for (int i = 1 ; i < interval_limit ; i++) { if (i % 3 == 0) sum = sum + 2 * func(lower_limit + i * interval_size); else sum = sum + 3 * func(lower_limit + i * interval_size); } return ( 3 * interval_size / 8 ) * sum ; } // Driver program to test above function public static void main(String[] args) { int interval_limit = 10; float lower_limit = 1; float upper_limit = 10; float integral_res = calculate(lower_limit, upper_limit, interval_limit); System.out.println(integral_res); } } // This article is contributed by Arnav Kr. Mandal.",
"e": 3269,
"s": 1883,
"text": null
},
{
"code": "# Python3 code to implement# Simpson's rule # Given function to be# integrateddef func(x): return (float(1) / ( 1 + x * x )) # Function to perform calculationsdef calculate(lower_limit, upper_limit, interval_limit ): interval_size = (float(upper_limit - lower_limit) / interval_limit) sum = func(lower_limit) + func(upper_limit); # Calculates value till integral limit for i in range(1, interval_limit ): if (i % 3 == 0): sum = sum + 2 * func(lower_limit + i * interval_size) else: sum = sum + 3 * func(lower_limit + i * interval_size) return ((float( 3 * interval_size) / 8 ) * sum ) # driver functioninterval_limit = 10lower_limit = 1upper_limit = 10 integral_res = calculate(lower_limit, upper_limit, interval_limit) # rounding the final answer to 6 decimal placesprint (round(integral_res, 6)) # This code is contributed by Saloni.",
"e": 4178,
"s": 3269,
"text": null
},
{
"code": "// C# Code to implement Simpson's ruleusing System; class GFG { // Given function to be integrated static float func( float x) { return (1 / ( 1 + x * x )); } // Function to perform calculations static float calculate(float lower_limit, float upper_limit, int interval_limit ) { //float value; float interval_size = (upper_limit - lower_limit) / interval_limit; float sum = func(lower_limit) + func(upper_limit); // Calculates value till integral limit for (int i = 1 ; i < interval_limit ; i++) { if (i % 3 == 0) sum = sum + 2 * func(lower_limit + i * interval_size); else sum = sum + 3 * func(lower_limit + i * interval_size); } return ( 3 * interval_size / 8 ) * sum ; } // Driver program to test above function public static void Main() { int interval_limit = 10; float lower_limit = 1; float upper_limit = 10; float integral_res = calculate(lower_limit, upper_limit, interval_limit); Console.WriteLine(integral_res); } } // This code is contributed by Vt_m.",
"e": 5515,
"s": 4178,
"text": null
},
{
"code": "<?php// PHP program to implement// Simpson's rule // Given function to be integratedfunction func( $x){ return (1 / ( 1 + $x * $x ));} // Function to perform calculationsfunction calculate($lower_limit, $upper_limit, $interval_limit){ $interval_size = ($upper_limit - $lower_limit) / $interval_limit; $sum = func($lower_limit) + func($upper_limit); // Calculates value till // integral limit for ($i = 1 ; $i < $interval_limit ; $i++) { if ($i % 3 == 0) $sum = $sum + 2 * func($lower_limit + $i * $interval_size); else $sum = $sum + 3 * func($lower_limit + $i * $interval_size); } return ( 3 * $interval_size / 8 ) * $sum ;} // Driver Code$interval_limit = 10;$lower_limit = 1;$upper_limit = 10;$integral_res = calculate($lower_limit, $upper_limit, $interval_limit); echo $integral_res; // This code is contributed by mits.?>",
"e": 6572,
"s": 5515,
"text": null
},
{
"code": "<script> // javascript program to implement Simpson's rule // Given function to be integrated function func(x) { return (1 / ( 1 + x * x )); } // Function to perform calculations function calculate(lower_limit, upper_limit, interval_limit ) { let value; let interval_size = (upper_limit - lower_limit) / interval_limit; let sum = func(lower_limit) + func(upper_limit); // Calculates value till integral limit for (let i = 1 ; i < interval_limit ; i++) { if (i % 3 == 0) sum = sum + 2 * func(lower_limit + i * interval_size); else sum = sum + 3 * func(lower_limit + i * interval_size); } return ( 3 * interval_size / 8 ) * sum ; } // Driver Function let interval_limit = 10; let lower_limit = 1; let upper_limit = 10; let integral_res = calculate(lower_limit, upper_limit, interval_limit); document.write(integral_res); // This code is contributed by susmitakundugoaldanga.</script>",
"e": 7827,
"s": 6572,
"text": null
},
{
"code": null,
"e": 7838,
"s": 7827,
"text": "Output : "
},
{
"code": null,
"e": 7847,
"s": 7838,
"text": "0.687927"
},
{
"code": null,
"e": 7862,
"s": 7849,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 7884,
"s": 7862,
"text": "susmitakundugoaldanga"
},
{
"code": null,
"e": 7897,
"s": 7884,
"text": "simmytarika5"
},
{
"code": null,
"e": 7905,
"s": 7897,
"text": "Algebra"
},
{
"code": null,
"e": 7918,
"s": 7905,
"text": "Mathematical"
},
{
"code": null,
"e": 7931,
"s": 7918,
"text": "Mathematical"
},
{
"code": null,
"e": 8029,
"s": 7931,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8061,
"s": 8029,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 8107,
"s": 8061,
"text": "Merge two sorted arrays with O(1) extra space"
},
{
"code": null,
"e": 8151,
"s": 8107,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 8193,
"s": 8151,
"text": "Segment Tree | Set 1 (Sum of given range)"
},
{
"code": null,
"e": 8225,
"s": 8193,
"text": "Check if a number is Palindrome"
},
{
"code": null,
"e": 8260,
"s": 8225,
"text": "Count ways to reach the n'th stair"
},
{
"code": null,
"e": 8285,
"s": 8260,
"text": "Fizz Buzz Implementation"
},
{
"code": null,
"e": 8326,
"s": 8285,
"text": "Median of two sorted arrays of same size"
},
{
"code": null,
"e": 8357,
"s": 8326,
"text": "Product of Array except itself"
}
] |
Minimum no. of operations required to make all Array Elements Zero | 23 May, 2022
Given an array of N elements and each element is either 1 or 0. You need to make all the elements of the array equal to 0 by performing below operations:
If an element is 1, You can change it’s value equal to 0 then, if the next consecutive element is 1, it will automatically get converted to 0.if the next consecutive element is already 0, nothing will happen.
if the next consecutive element is 1, it will automatically get converted to 0.
if the next consecutive element is already 0, nothing will happen.
Now, the task is to find the minimum number of operations required to make all elements equal to 0.Examples:
Input : arr[] = {1, 1, 0, 0, 1, 1, 1, 0, 0, 1}
Output : Minimum changes: 3
Input : arr[] = {1, 1, 1, 1}
Output : Minimum changes: 1
Approach 1:
To find the minimum number of changes required, iterate the array from left to right and check if the current element is 1 or not. If the current element is 1, then change it to 0 and increment the count by 1 and search for the 0 for the next operation as all consecutive 1’s will be automatically converted to 0.
Below is the implementation of above approach:
C++
Java
Python 3
C#
PHP
Javascript
// CPP program to find minimum number of// operations required to make all// array elements zero #include <bits/stdc++.h>using namespace std; // Function to find minimum number of// operations required to make all// array elements zeroint minimumChanges(int arr[], int n){ int i; // It will maintain total changes required int changes = 0; for (i = 0; i < n; i++) { // Check for the first 1 if (arr[i] == 1) { int j; // Check for number of // consecutive 1's for(j = i+1; j<n; j++) { if(arr[j]==0) break; } // Increment i to the position of // last consecutive 1 i = j-1; changes++; } } return changes;} // Driver codeint main(){ int arr[] = { 1, 1, 0, 0, 0, 1, 0, 1, 1 }; int n = sizeof(arr) / sizeof(arr[0]); cout << "Minimum operations: " << minimumChanges(arr, n); return 0;}
// Java program to find minimum// number of operations required// to make all array elements zero class GFG{ // Function to find minimum number// of operations required to make // all array elements zerostatic int minimumChanges(int arr[], int n){ int i; // It will maintain total // changes required int changes = 0; for (i = 0; i < n; i++) { // Check for the first 1 if (arr[i] == 1) { int j; // Check for number of // consecutive 1's for(j = i + 1; j < n; j++) { if(arr[j] == 0) break; } // Increment i to the position // of last consecutive 1 i = j - 1; changes++; } } return changes;} // Driver codepublic static void main (String args[]){ int arr[] = { 1, 1, 0, 0, 0, 1, 0, 1, 1 }; int n = arr.length ; System.out.println("Minimum operations: " + minimumChanges(arr, n)); }} // This code is contributed by ANKITRAI1
# Python 3 program to find# minimum number of operations# required to make all array# elements zero # Function to find minimum number# of operations required to make# all array elements zerodef minimumChanges(arr, n) : # It will maintain total # changes required changes = 0 i = 0 while i < n : # Check for the first 1 if arr[i] == 1 : j = i + 1 # Check for number of # consecutive 1's while j < n: if arr[j] == 0 : break j += 1 # Increment i to the position # of last consecutive 1 i = j - 1 changes += 1 i += 1 return changes # Driver code if __name__ == "__main__" : arr = [ 1, 1, 0, 0, 0, 1, 0, 1, 1] n = len(arr) print("Minimum operations:", minimumChanges(arr, n)) # This code is contributed by ANKITRAI1
// C# program to find minimum// number of operations required// to make all array elements zeroclass GFG{ // Function to find minimum number// of operations required to make// all array elements zerostatic int minimumChanges(int[] arr, int n){ int i; // It will maintain total // changes required int changes = 0; for (i = 0; i < n; i++) { // Check for the first 1 if (arr[i] == 1) { int j; // Check for number of // consecutive 1's for(j = i + 1; j < n; j++) { if(arr[j] == 0) break; } // Increment i to the position // of last consecutive 1 i = j - 1; changes++; } } return changes;} // Driver codestatic void Main(){ int[] arr = new int[]{ 1, 1, 0, 0, 0, 1, 0, 1, 1 }; int n = arr.Length ; System.Console.WriteLine("Minimum operations: " + minimumChanges(arr, n));}} // This code is contributed by mits
<?php// PHP program to find minimum number // of operations required to make all// array elements zero // Function to find minimum number // of operations required to make // all array elements zerofunction minimumChanges($arr, $n){ $i; // It will maintain total // changes required $changes = 0; for ($i = 0; $i < $n; $i++) { // Check for the first 1 if ($arr[$i] == 1) { $j; // Check for number of // consecutive 1's for($j = $i + 1; $j < $n; $j++) { if($arr[$j] == 0) break; } // Increment i to the position // of last consecutive 1 $i = $j - 1; $changes++; } } return $changes;} // Driver code$arr = array( 1, 1, 0, 0, 0, 1, 0, 1, 1 );$n = sizeof($arr); echo "Minimum operations: " . minimumChanges($arr, $n); // This code is contributed// by Akanksha Rai(Abby_akku)
<script> // Javascript program to find minimum number of// operations required to make all// array elements zero // Function to find minimum number of// operations required to make all// array elements zerofunction minimumChanges(arr, n){ var i; // It will maintain total changes required var changes = 0; for (i = 0; i < n; i++) { // Check for the first 1 if (arr[i] == 1) { var j; // Check for number of // consecutive 1's for(j = i+1; j<n; j++) { if(arr[j]==0) break; } // Increment i to the position of // last consecutive 1 i = j-1; changes++; } } return changes;} // Driver codevar arr = [1, 1, 0, 0, 0, 1, 0, 1, 1 ];var n = arr.length; document.write( "Minimum operations: " + minimumChanges(arr, n)); </script>
Minimum operations: 3
Time Complexity: O(N*N), where N represents the size of the given array.
Auxiliary Space: O(1), no extra space is required, so it is a constant.
Approach 2:
As we already know that we have to look for consecutive group/cluster of ‘1’, as after change the first ‘1’ of the group, rest of the consecutive ‘1’s will automatically be changed. So to find the consecutive ‘1’, we can iterate over the array and find the no. of consecutive pair of ‘1’ and ‘0’, as it will indicate the breakpoint for consecutive ‘1’s.And at the last index, we will check if the last element of the array is ‘1’ or ‘0’, because, if it is ‘1’, then it is possible that a continuous group of ‘1’ was there and therefore our loop couldn’t find the breakpoint as the iteration ended.
As we already know that we have to look for consecutive group/cluster of ‘1’, as after change the first ‘1’ of the group, rest of the consecutive ‘1’s will automatically be changed. So to find the consecutive ‘1’, we can iterate over the array and find the no. of consecutive pair of ‘1’ and ‘0’, as it will indicate the breakpoint for consecutive ‘1’s.
And at the last index, we will check if the last element of the array is ‘1’ or ‘0’, because, if it is ‘1’, then it is possible that a continuous group of ‘1’ was there and therefore our loop couldn’t find the breakpoint as the iteration ended.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// CPP program to find minimum number of// operations required to make all// array elements zero #include <bits/stdc++.h>using namespace std; // Function to find minimum number of// operations required to make all// array elements zeroint minimumChanges(int arr[], int n){ int i; // It will maintain total changes // required and return as // answer int changes = 0; // We iterate from 0 to n-1 // We can't iterate from 0 to n as // the arr[i+1] will be // out of index for (i = 0; i < n-1; i++) { // If we there is a consecutive pair of '1' and // '0'(in respective order) if ((arr[i] == 1) && (arr[i + 1] == 0)) { // We increment our returning variable by 1 changes++; } } // After the loop ends, we check the last element // whether it is '1' if (arr[n - 1] == 1) { changes++; // If it is '1', we again increment our // returning variable by 1 } return changes;} // Driver codeint main(){ int arr[] = { 1, 1, 0, 0, 0, 1, 0, 1, 1 }; int n = sizeof(arr) / sizeof(arr[0]); cout << "Minimum operations: " << minimumChanges(arr, n); return 0;} // This code is contributed by yashbro
// Java program to find minimum number of// operations required to make all// array elements zeroclass GFG{ // Function to find minimum number of // operations required to make all // array elements zero public static int minimumChanges(int arr[], int n) { int i; // It will maintain total changes // required and return as // answer int changes = 0; // We iterate from 0 to n-1 // We can't iterate from 0 to n as // the arr[i+1] will be // out of index for (i = 0; i < n-1; i++) { // If we there is a consecutive pair of '1' and // '0'(in respective order) if ((arr[i] == 1) && (arr[i + 1] == 0)) { // We increment our returning variable by 1 changes++; } } // After the loop ends, we check the last element // whether it is '1' if (arr[n - 1] == 1) { changes++; // If it is '1', we again increment our // returning variable by 1 } return changes; } // Driver code public static void main(String[] args) { int arr[] = { 1, 1, 0, 0, 0, 1, 0, 1, 1 }; int n = arr.length; System.out.println( "Minimum operations: "+ minimumChanges(arr, n)); }} //This code is contributed by sravan kumar
# Python 3 program to find# minimum number of operations# required to make all array# elements zero # Function to find minimum number# of operations required to make# all array elements zero def minimumChanges(arr, n): # It will maintain total # changes required changes = 0 # We iterate from 0 to n-1 # We can't iterate from 0 to n as the arr[i+1] will be out of index for i in range(n - 1): # If we there is a consecutive pair of '1' and '0'(in respective order) if arr[i] == 1 and arr[i + 1] == 0: # We increment our returning variable by 1 changes += 1 # After the loop ends, we check the last element whether it is '1' if arr[n - 1] == 1: changes += 1 # If it is '1', we again increment our returning variable by 1 return changes # Driver codeif __name__ == "__main__": arr = [1, 1, 0, 0, 0, 1, 0, 1, 1] n = len(arr) print("Minimum operations:", minimumChanges(arr, n)) # This code is contributed by yashbro
// C# program to find minimum number of// operations required to make all// array elements zerousing System;class GFG{ // Function to find minimum number of // operations required to make all // array elements zero static int minimumChanges(int[] arr, int n) { int i; // It will maintain total changes // required and return as // answer int changes = 0; // We iterate from 0 to n-1 // We can't iterate from 0 to n as // the arr[i+1] will be // out of index for (i = 0; i < n - 1; i++) { // If we there is a consecutive pair of '1' and // '0'(in respective order) if ((arr[i] == 1) && (arr[i + 1] == 0)) { // We increment our returning variable by 1 changes++; } } // After the loop ends, we check the last element // whether it is '1' if (arr[n - 1] == 1) { changes++; // If it is '1', we again increment our // returning variable by 1 } return changes; } // Driver code public static int Main() { int[] arr = { 1, 1, 0, 0, 0, 1, 0, 1, 1 }; int n = arr.Length; Console.Write("Minimum operations: " + minimumChanges(arr, n)); return 0; }}// This code is contributed by Taranpreet
<script>// Js program to find minimum number of// operations required to make all// array elements zero // Function to find minimum number of// operations required to make all// array elements zerofunction minimumChanges( arr, n){ let i; // It will maintain total changes // required and return as // answer let changes = 0; // We iterate from 0 to n-1 // We can't iterate from 0 to n as // the arr[i+1] will be // out of index for (i = 0; i < n-1; i++) { // If we there is a consecutive pair of '1' and // '0'(in respective order) if ((arr[i] == 1) && (arr[i + 1] == 0)) { // We increment our returning variable by 1 changes++; } } // After the loop ends, we check the last element // whether it is '1' if (arr[n - 1] == 1) { changes++; // If it is '1', we again increment our // returning variable by 1 } return changes;} // Driver codelet arr= [1, 1, 0, 0, 0, 1, 0, 1, 1];let n =arr.length;document.write("Minimum operations: " , minimumChanges(arr, n)); </script>
Minimum operations: 3
Time complexity : O(N), where N represents the size of the given array.
Auxiliary Space: O(1), no extra space is required, so it is a constant.
ankthon
Mithun Kumar
Akanksha_Rai
nidhi_biet
yashbro
rrrtnx
rohan07
sravankumar8128
singhh3010
tamanna17122007
Constructive Algorithms
Arrays
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Stack Data Structure (Introduction and Program)
Linear Search
Introduction to Arrays
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
K'th Smallest/Largest Element in Unsorted Array | Set 1
Subset Sum Problem | DP-25
Python | Using 2D arrays/lists the right way | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n23 May, 2022"
},
{
"code": null,
"e": 206,
"s": 52,
"text": "Given an array of N elements and each element is either 1 or 0. You need to make all the elements of the array equal to 0 by performing below operations:"
},
{
"code": null,
"e": 415,
"s": 206,
"text": "If an element is 1, You can change it’s value equal to 0 then, if the next consecutive element is 1, it will automatically get converted to 0.if the next consecutive element is already 0, nothing will happen."
},
{
"code": null,
"e": 495,
"s": 415,
"text": "if the next consecutive element is 1, it will automatically get converted to 0."
},
{
"code": null,
"e": 562,
"s": 495,
"text": "if the next consecutive element is already 0, nothing will happen."
},
{
"code": null,
"e": 673,
"s": 562,
"text": "Now, the task is to find the minimum number of operations required to make all elements equal to 0.Examples: "
},
{
"code": null,
"e": 809,
"s": 673,
"text": "Input : arr[] = {1, 1, 0, 0, 1, 1, 1, 0, 0, 1} \nOutput : Minimum changes: 3 \n\nInput : arr[] = {1, 1, 1, 1}\nOutput : Minimum changes: 1 "
},
{
"code": null,
"e": 822,
"s": 809,
"text": "Approach 1: "
},
{
"code": null,
"e": 1137,
"s": 822,
"text": "To find the minimum number of changes required, iterate the array from left to right and check if the current element is 1 or not. If the current element is 1, then change it to 0 and increment the count by 1 and search for the 0 for the next operation as all consecutive 1’s will be automatically converted to 0. "
},
{
"code": null,
"e": 1186,
"s": 1137,
"text": "Below is the implementation of above approach: "
},
{
"code": null,
"e": 1190,
"s": 1186,
"text": "C++"
},
{
"code": null,
"e": 1195,
"s": 1190,
"text": "Java"
},
{
"code": null,
"e": 1204,
"s": 1195,
"text": "Python 3"
},
{
"code": null,
"e": 1207,
"s": 1204,
"text": "C#"
},
{
"code": null,
"e": 1211,
"s": 1207,
"text": "PHP"
},
{
"code": null,
"e": 1222,
"s": 1211,
"text": "Javascript"
},
{
"code": "// CPP program to find minimum number of// operations required to make all// array elements zero #include <bits/stdc++.h>using namespace std; // Function to find minimum number of// operations required to make all// array elements zeroint minimumChanges(int arr[], int n){ int i; // It will maintain total changes required int changes = 0; for (i = 0; i < n; i++) { // Check for the first 1 if (arr[i] == 1) { int j; // Check for number of // consecutive 1's for(j = i+1; j<n; j++) { if(arr[j]==0) break; } // Increment i to the position of // last consecutive 1 i = j-1; changes++; } } return changes;} // Driver codeint main(){ int arr[] = { 1, 1, 0, 0, 0, 1, 0, 1, 1 }; int n = sizeof(arr) / sizeof(arr[0]); cout << \"Minimum operations: \" << minimumChanges(arr, n); return 0;}",
"e": 2277,
"s": 1222,
"text": null
},
{
"code": "// Java program to find minimum// number of operations required// to make all array elements zero class GFG{ // Function to find minimum number// of operations required to make // all array elements zerostatic int minimumChanges(int arr[], int n){ int i; // It will maintain total // changes required int changes = 0; for (i = 0; i < n; i++) { // Check for the first 1 if (arr[i] == 1) { int j; // Check for number of // consecutive 1's for(j = i + 1; j < n; j++) { if(arr[j] == 0) break; } // Increment i to the position // of last consecutive 1 i = j - 1; changes++; } } return changes;} // Driver codepublic static void main (String args[]){ int arr[] = { 1, 1, 0, 0, 0, 1, 0, 1, 1 }; int n = arr.length ; System.out.println(\"Minimum operations: \" + minimumChanges(arr, n)); }} // This code is contributed by ANKITRAI1",
"e": 3436,
"s": 2277,
"text": null
},
{
"code": "# Python 3 program to find# minimum number of operations# required to make all array# elements zero # Function to find minimum number# of operations required to make# all array elements zerodef minimumChanges(arr, n) : # It will maintain total # changes required changes = 0 i = 0 while i < n : # Check for the first 1 if arr[i] == 1 : j = i + 1 # Check for number of # consecutive 1's while j < n: if arr[j] == 0 : break j += 1 # Increment i to the position # of last consecutive 1 i = j - 1 changes += 1 i += 1 return changes # Driver code if __name__ == \"__main__\" : arr = [ 1, 1, 0, 0, 0, 1, 0, 1, 1] n = len(arr) print(\"Minimum operations:\", minimumChanges(arr, n)) # This code is contributed by ANKITRAI1",
"e": 4387,
"s": 3436,
"text": null
},
{
"code": "// C# program to find minimum// number of operations required// to make all array elements zeroclass GFG{ // Function to find minimum number// of operations required to make// all array elements zerostatic int minimumChanges(int[] arr, int n){ int i; // It will maintain total // changes required int changes = 0; for (i = 0; i < n; i++) { // Check for the first 1 if (arr[i] == 1) { int j; // Check for number of // consecutive 1's for(j = i + 1; j < n; j++) { if(arr[j] == 0) break; } // Increment i to the position // of last consecutive 1 i = j - 1; changes++; } } return changes;} // Driver codestatic void Main(){ int[] arr = new int[]{ 1, 1, 0, 0, 0, 1, 0, 1, 1 }; int n = arr.Length ; System.Console.WriteLine(\"Minimum operations: \" + minimumChanges(arr, n));}} // This code is contributed by mits",
"e": 5536,
"s": 4387,
"text": null
},
{
"code": "<?php// PHP program to find minimum number // of operations required to make all// array elements zero // Function to find minimum number // of operations required to make // all array elements zerofunction minimumChanges($arr, $n){ $i; // It will maintain total // changes required $changes = 0; for ($i = 0; $i < $n; $i++) { // Check for the first 1 if ($arr[$i] == 1) { $j; // Check for number of // consecutive 1's for($j = $i + 1; $j < $n; $j++) { if($arr[$j] == 0) break; } // Increment i to the position // of last consecutive 1 $i = $j - 1; $changes++; } } return $changes;} // Driver code$arr = array( 1, 1, 0, 0, 0, 1, 0, 1, 1 );$n = sizeof($arr); echo \"Minimum operations: \" . minimumChanges($arr, $n); // This code is contributed// by Akanksha Rai(Abby_akku)",
"e": 6580,
"s": 5536,
"text": null
},
{
"code": "<script> // Javascript program to find minimum number of// operations required to make all// array elements zero // Function to find minimum number of// operations required to make all// array elements zerofunction minimumChanges(arr, n){ var i; // It will maintain total changes required var changes = 0; for (i = 0; i < n; i++) { // Check for the first 1 if (arr[i] == 1) { var j; // Check for number of // consecutive 1's for(j = i+1; j<n; j++) { if(arr[j]==0) break; } // Increment i to the position of // last consecutive 1 i = j-1; changes++; } } return changes;} // Driver codevar arr = [1, 1, 0, 0, 0, 1, 0, 1, 1 ];var n = arr.length; document.write( \"Minimum operations: \" + minimumChanges(arr, n)); </script>",
"e": 7552,
"s": 6580,
"text": null
},
{
"code": null,
"e": 7574,
"s": 7552,
"text": "Minimum operations: 3"
},
{
"code": null,
"e": 7649,
"s": 7576,
"text": "Time Complexity: O(N*N), where N represents the size of the given array."
},
{
"code": null,
"e": 7721,
"s": 7649,
"text": "Auxiliary Space: O(1), no extra space is required, so it is a constant."
},
{
"code": null,
"e": 7734,
"s": 7721,
"text": "Approach 2: "
},
{
"code": null,
"e": 8332,
"s": 7734,
"text": "As we already know that we have to look for consecutive group/cluster of ‘1’, as after change the first ‘1’ of the group, rest of the consecutive ‘1’s will automatically be changed. So to find the consecutive ‘1’, we can iterate over the array and find the no. of consecutive pair of ‘1’ and ‘0’, as it will indicate the breakpoint for consecutive ‘1’s.And at the last index, we will check if the last element of the array is ‘1’ or ‘0’, because, if it is ‘1’, then it is possible that a continuous group of ‘1’ was there and therefore our loop couldn’t find the breakpoint as the iteration ended."
},
{
"code": null,
"e": 8686,
"s": 8332,
"text": "As we already know that we have to look for consecutive group/cluster of ‘1’, as after change the first ‘1’ of the group, rest of the consecutive ‘1’s will automatically be changed. So to find the consecutive ‘1’, we can iterate over the array and find the no. of consecutive pair of ‘1’ and ‘0’, as it will indicate the breakpoint for consecutive ‘1’s."
},
{
"code": null,
"e": 8931,
"s": 8686,
"text": "And at the last index, we will check if the last element of the array is ‘1’ or ‘0’, because, if it is ‘1’, then it is possible that a continuous group of ‘1’ was there and therefore our loop couldn’t find the breakpoint as the iteration ended."
},
{
"code": null,
"e": 8982,
"s": 8931,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 8986,
"s": 8982,
"text": "C++"
},
{
"code": null,
"e": 8991,
"s": 8986,
"text": "Java"
},
{
"code": null,
"e": 8999,
"s": 8991,
"text": "Python3"
},
{
"code": null,
"e": 9002,
"s": 8999,
"text": "C#"
},
{
"code": null,
"e": 9013,
"s": 9002,
"text": "Javascript"
},
{
"code": "// CPP program to find minimum number of// operations required to make all// array elements zero #include <bits/stdc++.h>using namespace std; // Function to find minimum number of// operations required to make all// array elements zeroint minimumChanges(int arr[], int n){ int i; // It will maintain total changes // required and return as // answer int changes = 0; // We iterate from 0 to n-1 // We can't iterate from 0 to n as // the arr[i+1] will be // out of index for (i = 0; i < n-1; i++) { // If we there is a consecutive pair of '1' and // '0'(in respective order) if ((arr[i] == 1) && (arr[i + 1] == 0)) { // We increment our returning variable by 1 changes++; } } // After the loop ends, we check the last element // whether it is '1' if (arr[n - 1] == 1) { changes++; // If it is '1', we again increment our // returning variable by 1 } return changes;} // Driver codeint main(){ int arr[] = { 1, 1, 0, 0, 0, 1, 0, 1, 1 }; int n = sizeof(arr) / sizeof(arr[0]); cout << \"Minimum operations: \" << minimumChanges(arr, n); return 0;} // This code is contributed by yashbro",
"e": 10264,
"s": 9013,
"text": null
},
{
"code": "// Java program to find minimum number of// operations required to make all// array elements zeroclass GFG{ // Function to find minimum number of // operations required to make all // array elements zero public static int minimumChanges(int arr[], int n) { int i; // It will maintain total changes // required and return as // answer int changes = 0; // We iterate from 0 to n-1 // We can't iterate from 0 to n as // the arr[i+1] will be // out of index for (i = 0; i < n-1; i++) { // If we there is a consecutive pair of '1' and // '0'(in respective order) if ((arr[i] == 1) && (arr[i + 1] == 0)) { // We increment our returning variable by 1 changes++; } } // After the loop ends, we check the last element // whether it is '1' if (arr[n - 1] == 1) { changes++; // If it is '1', we again increment our // returning variable by 1 } return changes; } // Driver code public static void main(String[] args) { int arr[] = { 1, 1, 0, 0, 0, 1, 0, 1, 1 }; int n = arr.length; System.out.println( \"Minimum operations: \"+ minimumChanges(arr, n)); }} //This code is contributed by sravan kumar",
"e": 11477,
"s": 10264,
"text": null
},
{
"code": "# Python 3 program to find# minimum number of operations# required to make all array# elements zero # Function to find minimum number# of operations required to make# all array elements zero def minimumChanges(arr, n): # It will maintain total # changes required changes = 0 # We iterate from 0 to n-1 # We can't iterate from 0 to n as the arr[i+1] will be out of index for i in range(n - 1): # If we there is a consecutive pair of '1' and '0'(in respective order) if arr[i] == 1 and arr[i + 1] == 0: # We increment our returning variable by 1 changes += 1 # After the loop ends, we check the last element whether it is '1' if arr[n - 1] == 1: changes += 1 # If it is '1', we again increment our returning variable by 1 return changes # Driver codeif __name__ == \"__main__\": arr = [1, 1, 0, 0, 0, 1, 0, 1, 1] n = len(arr) print(\"Minimum operations:\", minimumChanges(arr, n)) # This code is contributed by yashbro",
"e": 12486,
"s": 11477,
"text": null
},
{
"code": "// C# program to find minimum number of// operations required to make all// array elements zerousing System;class GFG{ // Function to find minimum number of // operations required to make all // array elements zero static int minimumChanges(int[] arr, int n) { int i; // It will maintain total changes // required and return as // answer int changes = 0; // We iterate from 0 to n-1 // We can't iterate from 0 to n as // the arr[i+1] will be // out of index for (i = 0; i < n - 1; i++) { // If we there is a consecutive pair of '1' and // '0'(in respective order) if ((arr[i] == 1) && (arr[i + 1] == 0)) { // We increment our returning variable by 1 changes++; } } // After the loop ends, we check the last element // whether it is '1' if (arr[n - 1] == 1) { changes++; // If it is '1', we again increment our // returning variable by 1 } return changes; } // Driver code public static int Main() { int[] arr = { 1, 1, 0, 0, 0, 1, 0, 1, 1 }; int n = arr.Length; Console.Write(\"Minimum operations: \" + minimumChanges(arr, n)); return 0; }}// This code is contributed by Taranpreet",
"e": 13712,
"s": 12486,
"text": null
},
{
"code": "<script>// Js program to find minimum number of// operations required to make all// array elements zero // Function to find minimum number of// operations required to make all// array elements zerofunction minimumChanges( arr, n){ let i; // It will maintain total changes // required and return as // answer let changes = 0; // We iterate from 0 to n-1 // We can't iterate from 0 to n as // the arr[i+1] will be // out of index for (i = 0; i < n-1; i++) { // If we there is a consecutive pair of '1' and // '0'(in respective order) if ((arr[i] == 1) && (arr[i + 1] == 0)) { // We increment our returning variable by 1 changes++; } } // After the loop ends, we check the last element // whether it is '1' if (arr[n - 1] == 1) { changes++; // If it is '1', we again increment our // returning variable by 1 } return changes;} // Driver codelet arr= [1, 1, 0, 0, 0, 1, 0, 1, 1];let n =arr.length;document.write(\"Minimum operations: \" , minimumChanges(arr, n)); </script>",
"e": 14836,
"s": 13712,
"text": null
},
{
"code": null,
"e": 14858,
"s": 14836,
"text": "Minimum operations: 3"
},
{
"code": null,
"e": 14930,
"s": 14858,
"text": "Time complexity : O(N), where N represents the size of the given array."
},
{
"code": null,
"e": 15002,
"s": 14930,
"text": "Auxiliary Space: O(1), no extra space is required, so it is a constant."
},
{
"code": null,
"e": 15010,
"s": 15002,
"text": "ankthon"
},
{
"code": null,
"e": 15023,
"s": 15010,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 15036,
"s": 15023,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 15047,
"s": 15036,
"text": "nidhi_biet"
},
{
"code": null,
"e": 15055,
"s": 15047,
"text": "yashbro"
},
{
"code": null,
"e": 15062,
"s": 15055,
"text": "rrrtnx"
},
{
"code": null,
"e": 15070,
"s": 15062,
"text": "rohan07"
},
{
"code": null,
"e": 15086,
"s": 15070,
"text": "sravankumar8128"
},
{
"code": null,
"e": 15097,
"s": 15086,
"text": "singhh3010"
},
{
"code": null,
"e": 15113,
"s": 15097,
"text": "tamanna17122007"
},
{
"code": null,
"e": 15137,
"s": 15113,
"text": "Constructive Algorithms"
},
{
"code": null,
"e": 15144,
"s": 15137,
"text": "Arrays"
},
{
"code": null,
"e": 15151,
"s": 15144,
"text": "Arrays"
},
{
"code": null,
"e": 15249,
"s": 15151,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 15317,
"s": 15249,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 15361,
"s": 15317,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 15393,
"s": 15361,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 15441,
"s": 15393,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 15455,
"s": 15441,
"text": "Linear Search"
},
{
"code": null,
"e": 15478,
"s": 15455,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 15563,
"s": 15478,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 15619,
"s": 15563,
"text": "K'th Smallest/Largest Element in Unsorted Array | Set 1"
},
{
"code": null,
"e": 15646,
"s": 15619,
"text": "Subset Sum Problem | DP-25"
}
] |
json.loads() in Python - GeeksforGeeks | 22 Jun, 2020
JSON stands for JavaScript Object Notation. It is a lightweight data-interchange format that is used to store and exchange data. It is a language-independent format and is very easy to understand since it is self-describing in nature. There is a built-in package in python that supports JSON data which is called as json. The data in JSON is represented as quoted-strings consisting of key-value mapping enclosed between curly brackets {}.
json.loads() method can be used to parse a valid JSON string and convert it into a Python Dictionary. It is mainly used for deserializing native string, byte, or byte array which consists of JSON data into Python Dictionary.
Syntax : json.loads(s)
Argument: it takes a string, bytes, or byte array instance which contains the JSON document as a parameter (s).
Return: It returns a Python object.
Example 1:Suppose the JSON string looks like this.
x = """{
"Name": "Jennifer Smith",
"Contact Number": 7867567898,
"Email": "[email protected]",
"Hobbies":["Reading", "Sketching", "Horse Riding"]
}"""
In order to read the content of this string following implementation needs to be carried out:
import json # JSON string:# Multi-line stringx = """{ "Name": "Jennifer Smith", "Contact Number": 7867567898, "Email": "[email protected]", "Hobbies":["Reading", "Sketching", "Horse Riding"] }""" # parse x:y = json.loads(x) # the result is a Python dictionary:print(y)
Output:
{‘Hobbies’: [‘Reading’, ‘Sketching’, ‘Horse Riding’], ‘Name’: ‘Jennifer Smith’, ‘Email’: ‘[email protected]’, ‘Contact Number’: 7867567898}
Here, the string x is parsed using json.loads() method which returns a dictionary.
Example 2:
import json # JSON string employee ='{"id":"09", "name": "Nitin", "department":"Finance"}' # Convert string to Python dict employee_dict = json.loads(employee) print(employee_dict) print(employee_dict['name'])
Output:
{'id': '09', 'department': 'Finance', 'name': 'Nitin'}
Nitin
Python-json
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists | [
{
"code": null,
"e": 25479,
"s": 25451,
"text": "\n22 Jun, 2020"
},
{
"code": null,
"e": 25919,
"s": 25479,
"text": "JSON stands for JavaScript Object Notation. It is a lightweight data-interchange format that is used to store and exchange data. It is a language-independent format and is very easy to understand since it is self-describing in nature. There is a built-in package in python that supports JSON data which is called as json. The data in JSON is represented as quoted-strings consisting of key-value mapping enclosed between curly brackets {}."
},
{
"code": null,
"e": 26144,
"s": 25919,
"text": "json.loads() method can be used to parse a valid JSON string and convert it into a Python Dictionary. It is mainly used for deserializing native string, byte, or byte array which consists of JSON data into Python Dictionary."
},
{
"code": null,
"e": 26167,
"s": 26144,
"text": "Syntax : json.loads(s)"
},
{
"code": null,
"e": 26279,
"s": 26167,
"text": "Argument: it takes a string, bytes, or byte array instance which contains the JSON document as a parameter (s)."
},
{
"code": null,
"e": 26315,
"s": 26279,
"text": "Return: It returns a Python object."
},
{
"code": null,
"e": 26366,
"s": 26315,
"text": "Example 1:Suppose the JSON string looks like this."
},
{
"code": null,
"e": 26537,
"s": 26366,
"text": "x = \"\"\"{\n \"Name\": \"Jennifer Smith\",\n \"Contact Number\": 7867567898,\n \"Email\": \"[email protected]\",\n \"Hobbies\":[\"Reading\", \"Sketching\", \"Horse Riding\"]\n }\"\"\"\n"
},
{
"code": null,
"e": 26631,
"s": 26537,
"text": "In order to read the content of this string following implementation needs to be carried out:"
},
{
"code": "import json # JSON string:# Multi-line stringx = \"\"\"{ \"Name\": \"Jennifer Smith\", \"Contact Number\": 7867567898, \"Email\": \"[email protected]\", \"Hobbies\":[\"Reading\", \"Sketching\", \"Horse Riding\"] }\"\"\" # parse x:y = json.loads(x) # the result is a Python dictionary:print(y)",
"e": 26917,
"s": 26631,
"text": null
},
{
"code": null,
"e": 26925,
"s": 26917,
"text": "Output:"
},
{
"code": null,
"e": 27064,
"s": 26925,
"text": "{‘Hobbies’: [‘Reading’, ‘Sketching’, ‘Horse Riding’], ‘Name’: ‘Jennifer Smith’, ‘Email’: ‘[email protected]’, ‘Contact Number’: 7867567898}"
},
{
"code": null,
"e": 27147,
"s": 27064,
"text": "Here, the string x is parsed using json.loads() method which returns a dictionary."
},
{
"code": null,
"e": 27158,
"s": 27147,
"text": "Example 2:"
},
{
"code": "import json # JSON string employee ='{\"id\":\"09\", \"name\": \"Nitin\", \"department\":\"Finance\"}' # Convert string to Python dict employee_dict = json.loads(employee) print(employee_dict) print(employee_dict['name']) ",
"e": 27380,
"s": 27158,
"text": null
},
{
"code": null,
"e": 27388,
"s": 27380,
"text": "Output:"
},
{
"code": null,
"e": 27449,
"s": 27388,
"text": "{'id': '09', 'department': 'Finance', 'name': 'Nitin'}\nNitin"
},
{
"code": null,
"e": 27461,
"s": 27449,
"text": "Python-json"
},
{
"code": null,
"e": 27468,
"s": 27461,
"text": "Python"
},
{
"code": null,
"e": 27566,
"s": 27468,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27584,
"s": 27566,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27619,
"s": 27584,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 27651,
"s": 27619,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27673,
"s": 27651,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27715,
"s": 27673,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27745,
"s": 27715,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 27771,
"s": 27745,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27800,
"s": 27771,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 27844,
"s": 27800,
"text": "Reading and Writing to text files in Python"
}
] |
Sum of two large numbers - GeeksforGeeks | 25 Feb, 2022
Given two numbers as strings. The numbers may be very large (may not fit in long long int), the task is to find sum of these two numbers.
Examples:
Input : str1 = "3333311111111111",
str2 = "44422222221111"
Output : 3377733333332222
Input : str1 = "7777555511111111",
str2 = "3332222221111"
Output : 7780887733332222
The idea is based on school mathematics. We traverse both strings from end, one by one add digits and keep track of carry. To simplify the process, we do following: 1) Reverse both strings. 2) Keep adding digits one by one from 0’th index (in reversed strings) to end of smaller string, append the sum % 10 to end of result and keep track of carry as sum/10. 3) Finally reverse the result.
// C++ program to find sum of two large numbers.#include<bits/stdc++.h>using namespace std; // Function for finding sum of larger numbersstring findSum(string str1, string str2){ // Before proceeding further, make sure length // of str2 is larger. if (str1.length() > str2.length()) swap(str1, str2); // Take an empty string for storing result string str = ""; // Calculate length of both string int n1 = str1.length(), n2 = str2.length(); // Reverse both of strings reverse(str1.begin(), str1.end()); reverse(str2.begin(), str2.end()); int carry = 0; for (int i=0; i<n1; i++) { // Do school mathematics, compute sum of // current digits and carry int sum = ((str1[i]-'0')+(str2[i]-'0')+carry); str.push_back(sum%10 + '0'); // Calculate carry for next step carry = sum/10; } // Add remaining digits of larger number for (int i=n1; i<n2; i++) { int sum = ((str2[i]-'0')+carry); str.push_back(sum%10 + '0'); carry = sum/10; } // Add remaining carry if (carry) str.push_back(carry+'0'); // reverse resultant string reverse(str.begin(), str.end()); return str;} // Driver codeint main(){ string str1 = "12"; string str2 = "198111"; cout << findSum(str1, str2); return 0;}
// Java program to find sum of two large numbers.import java.util.*;class GFG{// Function for finding sum of larger numbersstatic String findSum(String str1, String str2){ // Before proceeding further, make sure length // of str2 is larger. if (str1.length() > str2.length()){ String t = str1; str1 = str2; str2 = t; } // Take an empty String for storing result String str = ""; // Calculate length of both String int n1 = str1.length(), n2 = str2.length(); // Reverse both of Strings str1=new StringBuilder(str1).reverse().toString(); str2=new StringBuilder(str2).reverse().toString(); int carry = 0; for (int i = 0; i < n1; i++) { // Do school mathematics, compute sum of // current digits and carry int sum = ((int)(str1.charAt(i) - '0') + (int)(str2.charAt(i) - '0') + carry); str += (char)(sum % 10 + '0'); // Calculate carry for next step carry = sum / 10; } // Add remaining digits of larger number for (int i = n1; i < n2; i++) { int sum = ((int)(str2.charAt(i) - '0') + carry); str += (char)(sum % 10 + '0'); carry = sum / 10; } // Add remaining carry if (carry > 0) str += (char)(carry + '0'); // reverse resultant String str = new StringBuilder(str).reverse().toString(); return str;} // Driver codepublic static void main(String[] args){ String str1 = "12"; String str2 = "198111"; System.out.println(findSum(str1, str2));}}// This code is contributed by mits
# Python3 program to find sum of# two large numbers. # Function for finding sum of# larger numbersdef findSum(str1, str2): # Before proceeding further, # make sure length of str2 is larger. if (len(str1) > len(str2)): t = str1; str1 = str2; str2 = t; # Take an empty string for # storing result str = ""; # Calculate length of both string n1 = len(str1); n2 = len(str2); # Reverse both of strings str1 = str1[::-1]; str2 = str2[::-1]; carry = 0; for i in range(n1): # Do school mathematics, compute # sum of current digits and carry sum = ((ord(str1[i]) - 48) + ((ord(str2[i]) - 48) + carry)); str += chr(sum % 10 + 48); # Calculate carry for next step carry = int(sum / 10); # Add remaining digits of larger number for i in range(n1, n2): sum = ((ord(str2[i]) - 48) + carry); str += chr(sum % 10 + 48); carry = (int)(sum / 10); # Add remaining carry if (carry): str += chr(carry + 48); # reverse resultant string str = str[::-1]; return str; # Driver codestr1 = "12";str2 = "198111";print(findSum(str1, str2)); # This code is contributed by mits
// C# program to find sum of two large numbers.using System;class GFG{// Function for finding sum of larger numbersstatic string findSum(string str1, string str2){ // Before proceeding further, make sure length // of str2 is larger. if (str1.Length > str2.Length){ string t = str1; str1 = str2; str2 = t; } // Take an empty string for storing result string str = ""; // Calculate length of both string int n1 = str1.Length, n2 = str2.Length; // Reverse both of strings char[] ch = str1.ToCharArray(); Array.Reverse( ch ); str1 = new string( ch ); char[] ch1 = str2.ToCharArray(); Array.Reverse( ch1 ); str2 = new string( ch1 ); int carry = 0; for (int i = 0; i < n1; i++) { // Do school mathematics, compute sum of // current digits and carry int sum = ((int)(str1[i] - '0') + (int)(str2[i] - '0') + carry); str += (char)(sum % 10 + '0'); // Calculate carry for next step carry = sum/10; } // Add remaining digits of larger number for (int i = n1; i < n2; i++) { int sum = ((int)(str2[i] - '0') + carry); str += (char)(sum % 10 + '0'); carry = sum/10; } // Add remaining carry if (carry > 0) str += (char)(carry + '0'); // reverse resultant string char[] ch2 = str.ToCharArray(); Array.Reverse( ch2 ); str = new string( ch2 ); return str;} // Driver codestatic void Main(){ string str1 = "12"; string str2 = "198111"; Console.WriteLine(findSum(str1, str2));}} // This code is contributed by mits
<?php// PHP program to find sum of two large numbers. // Function for finding sum of larger numbersfunction findSum($str1, $str2){ // Before proceeding further, make sure length // of str2 is larger. if (strlen($str1) > strlen($str2)) { $t=$str1; $str1=$str2; $str2=$t; } // Take an empty string for storing result $str = ""; // Calculate length of both string $n1 = strlen($str1); $n2 = strlen($str2); // Reverse both of strings $str1 = strrev($str1); $str2 = strrev($str2); $carry = 0; for ($i=0; $i<$n1; $i++) { // Do school mathematics, compute sum of // current digits and carry $sum = ((ord($str1[$i])-48)+((ord($str2[$i])-48)+$carry)); $str.=chr($sum%10 + 48); // Calculate carry for next step $carry = (int)($sum/10); } // Add remaining digits of larger number for ($i=$n1; $i<$n2; $i++) { $sum = ((ord($str2[$i])-48)+$carry); $str.=chr($sum%10 + 48); $carry = (int)($sum/10); } // Add remaining carry if ($carry) $str.=chr($carry+48); // reverse resultant string $str=strrev($str); return $str;} // Driver code $str1 = "12"; $str2 = "198111"; echo findSum($str1, $str2); // This code is contributed by mits?>
<script> // Javascript program to find sum of// two large numbers. // Function for finding sum of larger numbersfunction findSum(str1, str2){ // Before proceeding further, make // sure length of str2 is larger. if (str1.length > str2.length) { let t = str1; str1 = str2; str2 = t; } // Take an empty String for storing result let str = ""; // Calculate length of both String let n1 = str1.length, n2 = str2.length; // Reverse both of Strings str1 = str1.split("").reverse().join(""); str2 = str2.split("").reverse().join(""); let carry = 0; for(let i = 0; i < n1; i++) { // Do school mathematics, compute sum of // current digits and carry let sum = ((str1[i].charCodeAt(0) - '0'.charCodeAt(0)) + (str2[i].charCodeAt(0) - '0'.charCodeAt(0)) + carry); str += String.fromCharCode(sum % 10 + '0'.charCodeAt(0)); // Calculate carry for next step carry = Math.floor(sum / 10); } // Add remaining digits of larger number for(let i = n1; i < n2; i++) { let sum = ((str2[i].charCodeAt(0) - '0'.charCodeAt(0)) + carry); str += String.fromCharCode(sum % 10 + '0'.charCodeAt(0)); carry = Math.floor(sum / 10); } // Add remaining carry if (carry > 0) str += String.fromCharCode(carry + '0'.charCodeAt(0)); // reverse resultant String str = str.split("").reverse().join(""); return str;} // Driver codelet str1 = "12";let str2 = "198111"; document.write(findSum(str1, str2)) // This code is contributed by rag2127 </script>
Output:
198123
Optimization: We can avoid the first two string reverse operations by traversing them from end. Below is optimized solution.
// C++ program to find sum of two large numbers.#include<bits/stdc++.h>using namespace std; // Function for finding sum of larger numbersstring findSum(string str1, string str2){ // Before proceeding further, make sure length // of str2 is larger. if (str1.length() > str2.length()) swap(str1, str2); // Take an empty string for storing result string str = ""; // Calculate length of both string int n1 = str1.length(), n2 = str2.length(); int diff = n2 - n1; // Initially take carry zero int carry = 0; // Traverse from end of both strings for (int i=n1-1; i>=0; i--) { // Do school mathematics, compute sum of // current digits and carry int sum = ((str1[i]-'0') + (str2[i+diff]-'0') + carry); str.push_back(sum%10 + '0'); carry = sum/10; } // Add remaining digits of str2[] for (int i=n2-n1-1; i>=0; i--) { int sum = ((str2[i]-'0')+carry); str.push_back(sum%10 + '0'); carry = sum/10; } // Add remaining carry if (carry) str.push_back(carry+'0'); // reverse resultant string reverse(str.begin(), str.end()); return str;} // Driver codeint main(){ string str1 = "12"; string str2 = "198111"; cout << findSum(str1, str2); return 0;}
// Java program to find sum of two large numbers.import java.util.*; class GFG{ // Function for finding sum of larger numbersstatic String findSum(String str1, String str2){ // Before proceeding further, make sure length // of str2 is larger. if (str1.length() > str2.length()){ String t = str1; str1 = str2; str2 = t; } // Take an empty String for storing result String str = ""; // Calculate length of both String int n1 = str1.length(), n2 = str2.length(); int diff = n2 - n1; // Initially take carry zero int carry = 0; // Traverse from end of both Strings for (int i = n1 - 1; i>=0; i--) { // Do school mathematics, compute sum of // current digits and carry int sum = ((int)(str1.charAt(i)-'0') + (int)(str2.charAt(i+diff)-'0') + carry); str += (char)(sum % 10 + '0'); carry = sum / 10; } // Add remaining digits of str2[] for (int i = n2 - n1 - 1; i >= 0; i--) { int sum = ((int)(str2.charAt(i) - '0') + carry); str += (char)(sum % 10 + '0'); carry = sum / 10; } // Add remaining carry if (carry > 0) str += (char)(carry + '0'); // reverse resultant String return new StringBuilder(str).reverse().toString();} // Driver codepublic static void main(String[] args){ String str1 = "12"; String str2 = "198111"; System.out.println(findSum(str1, str2));}} // This code is contributed by mits
# python 3 program to find sum of two large numbers. # Function for finding sum of larger numbersdef findSum(str1, str2): # Before proceeding further, make sure length # of str2 is larger. if len(str1)> len(str2): temp = str1 str1 = str2 str2 = temp # Take an empty string for storing result str3 = "" # Calculate length of both string n1 = len(str1) n2 = len(str2) diff = n2 - n1 # Initially take carry zero carry = 0 # Traverse from end of both strings for i in range(n1-1,-1,-1): # Do school mathematics, compute sum of # current digits and carry sum = ((ord(str1[i])-ord('0')) + int((ord(str2[i+diff])-ord('0'))) + carry) str3 = str3+str(sum%10 ) carry = sum//10 # Add remaining digits of str2[] for i in range(n2-n1-1,-1,-1): sum = ((ord(str2[i])-ord('0'))+carry) str3 = str3+str(sum%10 ) carry = sum//10 # Add remaining carry if (carry): str3+str(carry+'0') # reverse resultant string str3 = str3[::-1] return str3 # Driver codeif __name__ == "__main__": str1 = "12" str2 = "198111" print(findSum(str1, str2)) # This code is contributed by ChitraNayal
// C# program to find sum of two large numbers.using System; class GFG{ // Function for finding sum of larger numbersstatic string findSum(string str1, string str2){ // Before proceeding further, make sure length // of str2 is larger. if (str1.Length > str2.Length) { string t = str1; str1 = str2; str2 = t; } // Take an empty string for storing result string str = ""; // Calculate length of both string int n1 = str1.Length, n2 = str2.Length; int diff = n2 - n1; // Initially take carry zero int carry = 0; // Traverse from end of both strings for (int i = n1 - 1; i >= 0; i--) { // Do school mathematics, compute sum of // current digits and carry int sum = ((int)(str1[i] - '0') + (int)(str2[i + diff]-'0') + carry); str += (char)(sum % 10 + '0'); carry = sum / 10; } // Add remaining digits of str2[] for (int i = n2 - n1 - 1; i >= 0; i--) { int sum = ((int)(str2[i] - '0') + carry); str += (char)(sum % 10 + '0'); carry = sum / 10; } // Add remaining carry if (carry > 0) str += (char)(carry + '0'); // reverse resultant string char[] ch2 = str.ToCharArray(); Array.Reverse(ch2); return new string(ch2);} // Driver codestatic void Main(){ string str1 = "12"; string str2 = "198111"; Console.WriteLine(findSum(str1, str2));}} // This code is contributed by mits
<?php// PHP program to find sum of two large numbers. // Function for finding sum of larger numbersfunction findSum($str1, $str2){ // Before proceeding further, make // sure length of str2 is larger. if(strlen($str1)> strlen($str2)) { $temp = $str1; $str1 = $str2; $str2 = $temp; } // Take an empty string for storing result $str3 = ""; // Calculate length of both string $n1 = strlen($str1); $n2 = strlen($str2); $diff = $n2 - $n1; // Initially take carry zero $carry = 0; // Traverse from end of both strings for ($i = $n1 - 1; $i >= 0; $i--) { // Do school mathematics, compute sum // of current digits and carry $sum = ((ord($str1[$i]) - ord('0')) + ((ord($str2[$i + $diff]) - ord('0'))) + $carry); $str3 .= chr($sum % 10 + ord('0')); $carry = (int)($sum / 10); } // Add remaining digits of str2[] for ($i = $n2 - $n1 - 1; $i >= 0; $i--) { $sum = ((ord($str2[$i]) - ord('0')) + $carry); $str3 .= chr($sum % 10 + ord('0')); $carry = (int)($sum / 10); } // Add remaining carry if ($carry) $str3 .= chr($carry + ord('0')); // reverse resultant string return strrev($str3);} // Driver code$str1 = "12";$str2 = "198111";print(findSum($str1, $str2)); // This code is contributed by mits?>
<script> // JavaScript program to find sum of two large numbers. // Function for finding sum of larger numbersfunction findSum(str1,str2){ // Before proceeding further, make sure length // of str2 is larger. if (str1.length > str2.length){ let temp = str1 str1 = str2 str2 = temp } // Take an empty string for storing result let str = ""; // Calculate length of both string let n1 = str1.length, n2 = str2.length; let diff = n2 - n1; // Initially take carry zero let carry = 0; // Traverse from end of both strings for (let i=n1-1; i>=0; i--) { // Do school mathematics, compute sum of // current digits and carry // console.log((str1.charCodeAt(i)-48),(str2.charCodeAt(i+diff)-48)) let sum = ((str1.charCodeAt(i)-48) + (str2.charCodeAt(i+diff)-48) + carry); str+=(sum%10); carry = Math.floor(sum/10); } // // Add remaining digits of str2[] for (let i=n2-n1-1; i>=0; i--) { let sum = ((str2.charCodeAt(i)-48)+carry); str+=(sum%10); carry = Math.floor(sum/10); } // Add remaining carry if (carry) str+=(carry+'0'); // reverse resultant string str = str.split("").reverse().join(""); return str;} // Driver codelet str1 = "12";let str2 = "198111";document.write(findSum(str1, str2),"</br>"); // This code is contributed by shinjanpatra.</script>
Output:
198123
Time Complexity : O(n1 + n2) where n1 and n2 are lengths of two input strings representing numbers.
Auxiliary Space: O(max(n1, n2))
This article is contributed by DANISH_RAZA . 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.
ukasp
Mithun Kumar
Shivam_k
subhammahato348
rag2127
nareshsaharan1
shinjanpatra
Accolite
Amazon
large-numbers
Microsoft
Zoho
Arrays
Mathematical
Strings
Zoho
Accolite
Amazon
Microsoft
Arrays
Strings
Mathematical
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
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7 | [
{
"code": null,
"e": 26509,
"s": 26481,
"text": "\n25 Feb, 2022"
},
{
"code": null,
"e": 26647,
"s": 26509,
"text": "Given two numbers as strings. The numbers may be very large (may not fit in long long int), the task is to find sum of these two numbers."
},
{
"code": null,
"e": 26658,
"s": 26647,
"text": "Examples: "
},
{
"code": null,
"e": 26855,
"s": 26658,
"text": "Input : str1 = \"3333311111111111\", \n str2 = \"44422222221111\"\nOutput : 3377733333332222\n\nInput : str1 = \"7777555511111111\", \n str2 = \"3332222221111\"\nOutput : 7780887733332222"
},
{
"code": null,
"e": 27246,
"s": 26855,
"text": "The idea is based on school mathematics. We traverse both strings from end, one by one add digits and keep track of carry. To simplify the process, we do following: 1) Reverse both strings. 2) Keep adding digits one by one from 0’th index (in reversed strings) to end of smaller string, append the sum % 10 to end of result and keep track of carry as sum/10. 3) Finally reverse the result. "
},
{
"code": "// C++ program to find sum of two large numbers.#include<bits/stdc++.h>using namespace std; // Function for finding sum of larger numbersstring findSum(string str1, string str2){ // Before proceeding further, make sure length // of str2 is larger. if (str1.length() > str2.length()) swap(str1, str2); // Take an empty string for storing result string str = \"\"; // Calculate length of both string int n1 = str1.length(), n2 = str2.length(); // Reverse both of strings reverse(str1.begin(), str1.end()); reverse(str2.begin(), str2.end()); int carry = 0; for (int i=0; i<n1; i++) { // Do school mathematics, compute sum of // current digits and carry int sum = ((str1[i]-'0')+(str2[i]-'0')+carry); str.push_back(sum%10 + '0'); // Calculate carry for next step carry = sum/10; } // Add remaining digits of larger number for (int i=n1; i<n2; i++) { int sum = ((str2[i]-'0')+carry); str.push_back(sum%10 + '0'); carry = sum/10; } // Add remaining carry if (carry) str.push_back(carry+'0'); // reverse resultant string reverse(str.begin(), str.end()); return str;} // Driver codeint main(){ string str1 = \"12\"; string str2 = \"198111\"; cout << findSum(str1, str2); return 0;}",
"e": 28581,
"s": 27246,
"text": null
},
{
"code": "// Java program to find sum of two large numbers.import java.util.*;class GFG{// Function for finding sum of larger numbersstatic String findSum(String str1, String str2){ // Before proceeding further, make sure length // of str2 is larger. if (str1.length() > str2.length()){ String t = str1; str1 = str2; str2 = t; } // Take an empty String for storing result String str = \"\"; // Calculate length of both String int n1 = str1.length(), n2 = str2.length(); // Reverse both of Strings str1=new StringBuilder(str1).reverse().toString(); str2=new StringBuilder(str2).reverse().toString(); int carry = 0; for (int i = 0; i < n1; i++) { // Do school mathematics, compute sum of // current digits and carry int sum = ((int)(str1.charAt(i) - '0') + (int)(str2.charAt(i) - '0') + carry); str += (char)(sum % 10 + '0'); // Calculate carry for next step carry = sum / 10; } // Add remaining digits of larger number for (int i = n1; i < n2; i++) { int sum = ((int)(str2.charAt(i) - '0') + carry); str += (char)(sum % 10 + '0'); carry = sum / 10; } // Add remaining carry if (carry > 0) str += (char)(carry + '0'); // reverse resultant String str = new StringBuilder(str).reverse().toString(); return str;} // Driver codepublic static void main(String[] args){ String str1 = \"12\"; String str2 = \"198111\"; System.out.println(findSum(str1, str2));}}// This code is contributed by mits",
"e": 30153,
"s": 28581,
"text": null
},
{
"code": "# Python3 program to find sum of# two large numbers. # Function for finding sum of# larger numbersdef findSum(str1, str2): # Before proceeding further, # make sure length of str2 is larger. if (len(str1) > len(str2)): t = str1; str1 = str2; str2 = t; # Take an empty string for # storing result str = \"\"; # Calculate length of both string n1 = len(str1); n2 = len(str2); # Reverse both of strings str1 = str1[::-1]; str2 = str2[::-1]; carry = 0; for i in range(n1): # Do school mathematics, compute # sum of current digits and carry sum = ((ord(str1[i]) - 48) + ((ord(str2[i]) - 48) + carry)); str += chr(sum % 10 + 48); # Calculate carry for next step carry = int(sum / 10); # Add remaining digits of larger number for i in range(n1, n2): sum = ((ord(str2[i]) - 48) + carry); str += chr(sum % 10 + 48); carry = (int)(sum / 10); # Add remaining carry if (carry): str += chr(carry + 48); # reverse resultant string str = str[::-1]; return str; # Driver codestr1 = \"12\";str2 = \"198111\";print(findSum(str1, str2)); # This code is contributed by mits",
"e": 31390,
"s": 30153,
"text": null
},
{
"code": "// C# program to find sum of two large numbers.using System;class GFG{// Function for finding sum of larger numbersstatic string findSum(string str1, string str2){ // Before proceeding further, make sure length // of str2 is larger. if (str1.Length > str2.Length){ string t = str1; str1 = str2; str2 = t; } // Take an empty string for storing result string str = \"\"; // Calculate length of both string int n1 = str1.Length, n2 = str2.Length; // Reverse both of strings char[] ch = str1.ToCharArray(); Array.Reverse( ch ); str1 = new string( ch ); char[] ch1 = str2.ToCharArray(); Array.Reverse( ch1 ); str2 = new string( ch1 ); int carry = 0; for (int i = 0; i < n1; i++) { // Do school mathematics, compute sum of // current digits and carry int sum = ((int)(str1[i] - '0') + (int)(str2[i] - '0') + carry); str += (char)(sum % 10 + '0'); // Calculate carry for next step carry = sum/10; } // Add remaining digits of larger number for (int i = n1; i < n2; i++) { int sum = ((int)(str2[i] - '0') + carry); str += (char)(sum % 10 + '0'); carry = sum/10; } // Add remaining carry if (carry > 0) str += (char)(carry + '0'); // reverse resultant string char[] ch2 = str.ToCharArray(); Array.Reverse( ch2 ); str = new string( ch2 ); return str;} // Driver codestatic void Main(){ string str1 = \"12\"; string str2 = \"198111\"; Console.WriteLine(findSum(str1, str2));}} // This code is contributed by mits",
"e": 33000,
"s": 31390,
"text": null
},
{
"code": "<?php// PHP program to find sum of two large numbers. // Function for finding sum of larger numbersfunction findSum($str1, $str2){ // Before proceeding further, make sure length // of str2 is larger. if (strlen($str1) > strlen($str2)) { $t=$str1; $str1=$str2; $str2=$t; } // Take an empty string for storing result $str = \"\"; // Calculate length of both string $n1 = strlen($str1); $n2 = strlen($str2); // Reverse both of strings $str1 = strrev($str1); $str2 = strrev($str2); $carry = 0; for ($i=0; $i<$n1; $i++) { // Do school mathematics, compute sum of // current digits and carry $sum = ((ord($str1[$i])-48)+((ord($str2[$i])-48)+$carry)); $str.=chr($sum%10 + 48); // Calculate carry for next step $carry = (int)($sum/10); } // Add remaining digits of larger number for ($i=$n1; $i<$n2; $i++) { $sum = ((ord($str2[$i])-48)+$carry); $str.=chr($sum%10 + 48); $carry = (int)($sum/10); } // Add remaining carry if ($carry) $str.=chr($carry+48); // reverse resultant string $str=strrev($str); return $str;} // Driver code $str1 = \"12\"; $str2 = \"198111\"; echo findSum($str1, $str2); // This code is contributed by mits?>",
"e": 34305,
"s": 33000,
"text": null
},
{
"code": "<script> // Javascript program to find sum of// two large numbers. // Function for finding sum of larger numbersfunction findSum(str1, str2){ // Before proceeding further, make // sure length of str2 is larger. if (str1.length > str2.length) { let t = str1; str1 = str2; str2 = t; } // Take an empty String for storing result let str = \"\"; // Calculate length of both String let n1 = str1.length, n2 = str2.length; // Reverse both of Strings str1 = str1.split(\"\").reverse().join(\"\"); str2 = str2.split(\"\").reverse().join(\"\"); let carry = 0; for(let i = 0; i < n1; i++) { // Do school mathematics, compute sum of // current digits and carry let sum = ((str1[i].charCodeAt(0) - '0'.charCodeAt(0)) + (str2[i].charCodeAt(0) - '0'.charCodeAt(0)) + carry); str += String.fromCharCode(sum % 10 + '0'.charCodeAt(0)); // Calculate carry for next step carry = Math.floor(sum / 10); } // Add remaining digits of larger number for(let i = n1; i < n2; i++) { let sum = ((str2[i].charCodeAt(0) - '0'.charCodeAt(0)) + carry); str += String.fromCharCode(sum % 10 + '0'.charCodeAt(0)); carry = Math.floor(sum / 10); } // Add remaining carry if (carry > 0) str += String.fromCharCode(carry + '0'.charCodeAt(0)); // reverse resultant String str = str.split(\"\").reverse().join(\"\"); return str;} // Driver codelet str1 = \"12\";let str2 = \"198111\"; document.write(findSum(str1, str2)) // This code is contributed by rag2127 </script>",
"e": 36100,
"s": 34305,
"text": null
},
{
"code": null,
"e": 36109,
"s": 36100,
"text": "Output: "
},
{
"code": null,
"e": 36116,
"s": 36109,
"text": "198123"
},
{
"code": null,
"e": 36242,
"s": 36116,
"text": "Optimization: We can avoid the first two string reverse operations by traversing them from end. Below is optimized solution. "
},
{
"code": "// C++ program to find sum of two large numbers.#include<bits/stdc++.h>using namespace std; // Function for finding sum of larger numbersstring findSum(string str1, string str2){ // Before proceeding further, make sure length // of str2 is larger. if (str1.length() > str2.length()) swap(str1, str2); // Take an empty string for storing result string str = \"\"; // Calculate length of both string int n1 = str1.length(), n2 = str2.length(); int diff = n2 - n1; // Initially take carry zero int carry = 0; // Traverse from end of both strings for (int i=n1-1; i>=0; i--) { // Do school mathematics, compute sum of // current digits and carry int sum = ((str1[i]-'0') + (str2[i+diff]-'0') + carry); str.push_back(sum%10 + '0'); carry = sum/10; } // Add remaining digits of str2[] for (int i=n2-n1-1; i>=0; i--) { int sum = ((str2[i]-'0')+carry); str.push_back(sum%10 + '0'); carry = sum/10; } // Add remaining carry if (carry) str.push_back(carry+'0'); // reverse resultant string reverse(str.begin(), str.end()); return str;} // Driver codeint main(){ string str1 = \"12\"; string str2 = \"198111\"; cout << findSum(str1, str2); return 0;}",
"e": 37571,
"s": 36242,
"text": null
},
{
"code": "// Java program to find sum of two large numbers.import java.util.*; class GFG{ // Function for finding sum of larger numbersstatic String findSum(String str1, String str2){ // Before proceeding further, make sure length // of str2 is larger. if (str1.length() > str2.length()){ String t = str1; str1 = str2; str2 = t; } // Take an empty String for storing result String str = \"\"; // Calculate length of both String int n1 = str1.length(), n2 = str2.length(); int diff = n2 - n1; // Initially take carry zero int carry = 0; // Traverse from end of both Strings for (int i = n1 - 1; i>=0; i--) { // Do school mathematics, compute sum of // current digits and carry int sum = ((int)(str1.charAt(i)-'0') + (int)(str2.charAt(i+diff)-'0') + carry); str += (char)(sum % 10 + '0'); carry = sum / 10; } // Add remaining digits of str2[] for (int i = n2 - n1 - 1; i >= 0; i--) { int sum = ((int)(str2.charAt(i) - '0') + carry); str += (char)(sum % 10 + '0'); carry = sum / 10; } // Add remaining carry if (carry > 0) str += (char)(carry + '0'); // reverse resultant String return new StringBuilder(str).reverse().toString();} // Driver codepublic static void main(String[] args){ String str1 = \"12\"; String str2 = \"198111\"; System.out.println(findSum(str1, str2));}} // This code is contributed by mits",
"e": 39050,
"s": 37571,
"text": null
},
{
"code": "# python 3 program to find sum of two large numbers. # Function for finding sum of larger numbersdef findSum(str1, str2): # Before proceeding further, make sure length # of str2 is larger. if len(str1)> len(str2): temp = str1 str1 = str2 str2 = temp # Take an empty string for storing result str3 = \"\" # Calculate length of both string n1 = len(str1) n2 = len(str2) diff = n2 - n1 # Initially take carry zero carry = 0 # Traverse from end of both strings for i in range(n1-1,-1,-1): # Do school mathematics, compute sum of # current digits and carry sum = ((ord(str1[i])-ord('0')) + int((ord(str2[i+diff])-ord('0'))) + carry) str3 = str3+str(sum%10 ) carry = sum//10 # Add remaining digits of str2[] for i in range(n2-n1-1,-1,-1): sum = ((ord(str2[i])-ord('0'))+carry) str3 = str3+str(sum%10 ) carry = sum//10 # Add remaining carry if (carry): str3+str(carry+'0') # reverse resultant string str3 = str3[::-1] return str3 # Driver codeif __name__ == \"__main__\": str1 = \"12\" str2 = \"198111\" print(findSum(str1, str2)) # This code is contributed by ChitraNayal",
"e": 40338,
"s": 39050,
"text": null
},
{
"code": "// C# program to find sum of two large numbers.using System; class GFG{ // Function for finding sum of larger numbersstatic string findSum(string str1, string str2){ // Before proceeding further, make sure length // of str2 is larger. if (str1.Length > str2.Length) { string t = str1; str1 = str2; str2 = t; } // Take an empty string for storing result string str = \"\"; // Calculate length of both string int n1 = str1.Length, n2 = str2.Length; int diff = n2 - n1; // Initially take carry zero int carry = 0; // Traverse from end of both strings for (int i = n1 - 1; i >= 0; i--) { // Do school mathematics, compute sum of // current digits and carry int sum = ((int)(str1[i] - '0') + (int)(str2[i + diff]-'0') + carry); str += (char)(sum % 10 + '0'); carry = sum / 10; } // Add remaining digits of str2[] for (int i = n2 - n1 - 1; i >= 0; i--) { int sum = ((int)(str2[i] - '0') + carry); str += (char)(sum % 10 + '0'); carry = sum / 10; } // Add remaining carry if (carry > 0) str += (char)(carry + '0'); // reverse resultant string char[] ch2 = str.ToCharArray(); Array.Reverse(ch2); return new string(ch2);} // Driver codestatic void Main(){ string str1 = \"12\"; string str2 = \"198111\"; Console.WriteLine(findSum(str1, str2));}} // This code is contributed by mits",
"e": 41802,
"s": 40338,
"text": null
},
{
"code": "<?php// PHP program to find sum of two large numbers. // Function for finding sum of larger numbersfunction findSum($str1, $str2){ // Before proceeding further, make // sure length of str2 is larger. if(strlen($str1)> strlen($str2)) { $temp = $str1; $str1 = $str2; $str2 = $temp; } // Take an empty string for storing result $str3 = \"\"; // Calculate length of both string $n1 = strlen($str1); $n2 = strlen($str2); $diff = $n2 - $n1; // Initially take carry zero $carry = 0; // Traverse from end of both strings for ($i = $n1 - 1; $i >= 0; $i--) { // Do school mathematics, compute sum // of current digits and carry $sum = ((ord($str1[$i]) - ord('0')) + ((ord($str2[$i + $diff]) - ord('0'))) + $carry); $str3 .= chr($sum % 10 + ord('0')); $carry = (int)($sum / 10); } // Add remaining digits of str2[] for ($i = $n2 - $n1 - 1; $i >= 0; $i--) { $sum = ((ord($str2[$i]) - ord('0')) + $carry); $str3 .= chr($sum % 10 + ord('0')); $carry = (int)($sum / 10); } // Add remaining carry if ($carry) $str3 .= chr($carry + ord('0')); // reverse resultant string return strrev($str3);} // Driver code$str1 = \"12\";$str2 = \"198111\";print(findSum($str1, $str2)); // This code is contributed by mits?>",
"e": 43209,
"s": 41802,
"text": null
},
{
"code": "<script> // JavaScript program to find sum of two large numbers. // Function for finding sum of larger numbersfunction findSum(str1,str2){ // Before proceeding further, make sure length // of str2 is larger. if (str1.length > str2.length){ let temp = str1 str1 = str2 str2 = temp } // Take an empty string for storing result let str = \"\"; // Calculate length of both string let n1 = str1.length, n2 = str2.length; let diff = n2 - n1; // Initially take carry zero let carry = 0; // Traverse from end of both strings for (let i=n1-1; i>=0; i--) { // Do school mathematics, compute sum of // current digits and carry // console.log((str1.charCodeAt(i)-48),(str2.charCodeAt(i+diff)-48)) let sum = ((str1.charCodeAt(i)-48) + (str2.charCodeAt(i+diff)-48) + carry); str+=(sum%10); carry = Math.floor(sum/10); } // // Add remaining digits of str2[] for (let i=n2-n1-1; i>=0; i--) { let sum = ((str2.charCodeAt(i)-48)+carry); str+=(sum%10); carry = Math.floor(sum/10); } // Add remaining carry if (carry) str+=(carry+'0'); // reverse resultant string str = str.split(\"\").reverse().join(\"\"); return str;} // Driver codelet str1 = \"12\";let str2 = \"198111\";document.write(findSum(str1, str2),\"</br>\"); // This code is contributed by shinjanpatra.</script>",
"e": 44670,
"s": 43209,
"text": null
},
{
"code": null,
"e": 44678,
"s": 44670,
"text": "Output:"
},
{
"code": null,
"e": 44685,
"s": 44678,
"text": "198123"
},
{
"code": null,
"e": 44785,
"s": 44685,
"text": "Time Complexity : O(n1 + n2) where n1 and n2 are lengths of two input strings representing numbers."
},
{
"code": null,
"e": 44817,
"s": 44785,
"text": "Auxiliary Space: O(max(n1, n2))"
},
{
"code": null,
"e": 45237,
"s": 44817,
"text": "This article is contributed by DANISH_RAZA . 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": 45243,
"s": 45237,
"text": "ukasp"
},
{
"code": null,
"e": 45256,
"s": 45243,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 45265,
"s": 45256,
"text": "Shivam_k"
},
{
"code": null,
"e": 45281,
"s": 45265,
"text": "subhammahato348"
},
{
"code": null,
"e": 45289,
"s": 45281,
"text": "rag2127"
},
{
"code": null,
"e": 45304,
"s": 45289,
"text": "nareshsaharan1"
},
{
"code": null,
"e": 45317,
"s": 45304,
"text": "shinjanpatra"
},
{
"code": null,
"e": 45326,
"s": 45317,
"text": "Accolite"
},
{
"code": null,
"e": 45333,
"s": 45326,
"text": "Amazon"
},
{
"code": null,
"e": 45347,
"s": 45333,
"text": "large-numbers"
},
{
"code": null,
"e": 45357,
"s": 45347,
"text": "Microsoft"
},
{
"code": null,
"e": 45362,
"s": 45357,
"text": "Zoho"
},
{
"code": null,
"e": 45369,
"s": 45362,
"text": "Arrays"
},
{
"code": null,
"e": 45382,
"s": 45369,
"text": "Mathematical"
},
{
"code": null,
"e": 45390,
"s": 45382,
"text": "Strings"
},
{
"code": null,
"e": 45395,
"s": 45390,
"text": "Zoho"
},
{
"code": null,
"e": 45404,
"s": 45395,
"text": "Accolite"
},
{
"code": null,
"e": 45411,
"s": 45404,
"text": "Amazon"
},
{
"code": null,
"e": 45421,
"s": 45411,
"text": "Microsoft"
},
{
"code": null,
"e": 45428,
"s": 45421,
"text": "Arrays"
},
{
"code": null,
"e": 45436,
"s": 45428,
"text": "Strings"
},
{
"code": null,
"e": 45449,
"s": 45436,
"text": "Mathematical"
},
{
"code": null,
"e": 45547,
"s": 45449,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 45615,
"s": 45547,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 45659,
"s": 45615,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 45707,
"s": 45659,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 45730,
"s": 45707,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 45762,
"s": 45730,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 45792,
"s": 45762,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 45852,
"s": 45792,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 45867,
"s": 45852,
"text": "C++ Data Types"
},
{
"code": null,
"e": 45910,
"s": 45867,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
Puzzle 29 | (Car Wheel Puzzle) - GeeksforGeeks | 13 Jan, 2022
Puzzle: A car has 4 tyres and 1 spare tyre. Each tyre can travel a maximum distance of 20000 miles before wearing off. What is the maximum distance the car can travel before you are forced to buy a new tyre? You are allowed to change tyres (using the spare tyre) an unlimited number of times.
Answer: 25000 kmsSolution: Divide the lifetime of the spare tire into 4 equal part i.e., 5000 and swap it at each completion of 5000 miles distance. Let four tyres be named as A, B, C and D and spare tyre be S.
5000 KMs: Replace A with S. Remaining distances (A, B, C, D, S) : 15000, 15000, 15000, 15000, 20000.
5000 KMs: Replace A with S. Remaining distances (A, B, C, D, S) : 15000, 15000, 15000, 15000, 20000.
10000 KMs: Put A back to its original position and replace B with S. Remaining distances (A, B, C, D, S) : 15000, 10000, 10000, 10000, 15000.
10000 KMs: Put A back to its original position and replace B with S. Remaining distances (A, B, C, D, S) : 15000, 10000, 10000, 10000, 15000.
15000 KMs: Put B back to its original position and replace C with S. Remaining distances (A, B, C, D, S) : 10000, 10000, 5000, 5000, 10000.
15000 KMs: Put B back to its original position and replace C with S. Remaining distances (A, B, C, D, S) : 10000, 10000, 5000, 5000, 10000.
20000 KMs: Put C back to its original position and replace D with S. Remaining distances (A, B, C, D, S) : 5000, 5000, 5000, 0, 5000.
20000 KMs: Put C back to its original position and replace D with S. Remaining distances (A, B, C, D, S) : 5000, 5000, 5000, 0, 5000.
25000 KMs: Every tyre is now worn out completely.
25000 KMs: Every tyre is now worn out completely.
All tyres are used to their full strength.
There are n pencils, each having l length. Each can write 4 kilometres. After writing 4 kilometres it has l/4 length. One can join 4 pencils which are having l/4 length and can make 1 pencil. One can’t make pencil of pieces if remaining pieces are 3 or 2 or 1 in number but one can include these remaining pieces whenever needed. Write a relation independent of l, length of the given pencil, for how much one can write from n pencils. Examples:
Input: 4
Output: 20
Recursive Approach: Suppose we use 3 pencils that will 12 and generate 3 used pencils, now if the remaining pencils are greater than zero at least 1 unused pencil can be used with those 3 unused to write 4 and that will generate 1 more unused pencil. This will keep repeating.
if(n-3 >= 1){
f(n) = f(n-3) + 12 + 4
}
else{
// Used pencil that cannot be used
f(n) = 4*n
}
Below is the implementation of the above approach:
C
int count(int n){ if (n < 4) { return (n * 4); } else { return (16 + count(n - 3)); }}
Mathematical Approach O(1): Above relation can be optimized in O(1)
// x is max no of time we can
//subtract 3 without n-3 <= 3
n - 3*x <= 3
x > (n-3)/3
i.e. n/3 - 1 if it divides exactly
else n/3
Below is the implementation of the above approach:
CPP
Java
Python3
C#
Javascript
// C++ program to find relation independent of l// length of the given pencil, for how much one// can write from n pencils. #include <bits/stdc++.h>using namespace std; // Function to find no of pencilsint count(int n){ int x = (n / 3) - 1; if (n % 3) { x++; } return (4 * x + 4 * n);} // Driver functionint main(){ int n = 5; cout << count(n) << endl;}
// Java program to find relation independent of l// length of the given pencil, for how much one// can write from n pencils.class GFG{ // Function to find no of pencilsstatic int count(int n){ int x = (n / 3) - 1; if (n % 3 > 0) { x++; } return (4 * x + 4 * n);} // Driver codepublic static void main(String[] args){ int n = 5; System.out.print(count(n) +"\n");}} // This code is contributed by PrinciRaj1992
# Python3 program to find relation independent of l# length of the given pencil, for how much one# can write from n pencils. # Function to find no of pencilsdef count(n): x = (n // 3) - 1; if (n % 3 > 0): x+=1; return (4 * x + 4 * n); # Driver codeif __name__ == '__main__': n = 5; print(count(n)); # This code is contributed by PrinciRaj1992
// C# program to find relation independent of l// length of the given pencil, for how much one// can write from n pencils.using System; class GFG{ // Function to find no of pencilsstatic int count(int n){ int x = (n / 3) - 1; if (n % 3 > 0) { x++; } return (4 * x + 4 * n);} // Driver codepublic static void Main(String[] args){ int n = 5; Console.Write(count(n) +"\n");}} // This code is contributed by 29AjayKumar
<script>// Javascript program to find relation independent of l// length of the given pencil, for how much one// can write from n pencils. // Function to find no of pencilsfunction count(n){ let x = Math.floor(n / 3) - 1; if (n % 3 > 0) { x++; } return (4 * x + 4 * n);} // Driver codelet n = 5;document.write(count(n) +"<br>"); // This code is contributed by rag2127</script>
24
YouTubeGeeksforGeeks School17.7K subscribersCar Wheel PuzzleWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:30•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=s1WfONpTfbY" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Gurjeet Singh 2
md1844
Chinmoy Lenka
princiraj1992
29AjayKumar
rag2127
akash19990918
MakeMyTrip
Puzzles
MakeMyTrip
Puzzles
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Algorithm to solve Rubik's Cube
Top 20 Puzzles Commonly Asked During SDE Interviews
Puzzle 16 | (100 Doors)
Puzzle 18 | (Torch and Bridge)
Container with Most Water
Puzzle 8 | (Find the Jar with contaminated pills)
Puzzle 11 | (1000 Coins and 10 Bags)
Puzzle 10 | (A Man with Medical Condition and 2 Pills)
Puzzle 13 | (100 Prisoners with Red/Black Hats)
Puzzle 19 | (Poison and Rat) | [
{
"code": null,
"e": 25965,
"s": 25937,
"text": "\n13 Jan, 2022"
},
{
"code": null,
"e": 26260,
"s": 25965,
"text": "Puzzle: A car has 4 tyres and 1 spare tyre. Each tyre can travel a maximum distance of 20000 miles before wearing off. What is the maximum distance the car can travel before you are forced to buy a new tyre? You are allowed to change tyres (using the spare tyre) an unlimited number of times. "
},
{
"code": null,
"e": 26472,
"s": 26260,
"text": "Answer: 25000 kmsSolution: Divide the lifetime of the spare tire into 4 equal part i.e., 5000 and swap it at each completion of 5000 miles distance. Let four tyres be named as A, B, C and D and spare tyre be S. "
},
{
"code": null,
"e": 26575,
"s": 26472,
"text": "5000 KMs: Replace A with S. Remaining distances (A, B, C, D, S) : 15000, 15000, 15000, 15000, 20000. "
},
{
"code": null,
"e": 26678,
"s": 26575,
"text": "5000 KMs: Replace A with S. Remaining distances (A, B, C, D, S) : 15000, 15000, 15000, 15000, 20000. "
},
{
"code": null,
"e": 26822,
"s": 26678,
"text": "10000 KMs: Put A back to its original position and replace B with S. Remaining distances (A, B, C, D, S) : 15000, 10000, 10000, 10000, 15000. "
},
{
"code": null,
"e": 26966,
"s": 26822,
"text": "10000 KMs: Put A back to its original position and replace B with S. Remaining distances (A, B, C, D, S) : 15000, 10000, 10000, 10000, 15000. "
},
{
"code": null,
"e": 27108,
"s": 26966,
"text": "15000 KMs: Put B back to its original position and replace C with S. Remaining distances (A, B, C, D, S) : 10000, 10000, 5000, 5000, 10000. "
},
{
"code": null,
"e": 27250,
"s": 27108,
"text": "15000 KMs: Put B back to its original position and replace C with S. Remaining distances (A, B, C, D, S) : 10000, 10000, 5000, 5000, 10000. "
},
{
"code": null,
"e": 27386,
"s": 27250,
"text": "20000 KMs: Put C back to its original position and replace D with S. Remaining distances (A, B, C, D, S) : 5000, 5000, 5000, 0, 5000. "
},
{
"code": null,
"e": 27522,
"s": 27386,
"text": "20000 KMs: Put C back to its original position and replace D with S. Remaining distances (A, B, C, D, S) : 5000, 5000, 5000, 0, 5000. "
},
{
"code": null,
"e": 27574,
"s": 27522,
"text": "25000 KMs: Every tyre is now worn out completely. "
},
{
"code": null,
"e": 27626,
"s": 27574,
"text": "25000 KMs: Every tyre is now worn out completely. "
},
{
"code": null,
"e": 27671,
"s": 27626,
"text": "All tyres are used to their full strength. "
},
{
"code": null,
"e": 28121,
"s": 27673,
"text": "There are n pencils, each having l length. Each can write 4 kilometres. After writing 4 kilometres it has l/4 length. One can join 4 pencils which are having l/4 length and can make 1 pencil. One can’t make pencil of pieces if remaining pieces are 3 or 2 or 1 in number but one can include these remaining pieces whenever needed. Write a relation independent of l, length of the given pencil, for how much one can write from n pencils. Examples: "
},
{
"code": null,
"e": 28141,
"s": 28121,
"text": "Input: 4\nOutput: 20"
},
{
"code": null,
"e": 28421,
"s": 28143,
"text": "Recursive Approach: Suppose we use 3 pencils that will 12 and generate 3 used pencils, now if the remaining pencils are greater than zero at least 1 unused pencil can be used with those 3 unused to write 4 and that will generate 1 more unused pencil. This will keep repeating. "
},
{
"code": null,
"e": 28521,
"s": 28421,
"text": "if(n-3 >= 1){\n f(n) = f(n-3) + 12 + 4\n} \nelse{\n // Used pencil that cannot be used\n f(n) = 4*n\n}"
},
{
"code": null,
"e": 28573,
"s": 28521,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 28575,
"s": 28573,
"text": "C"
},
{
"code": "int count(int n){ if (n < 4) { return (n * 4); } else { return (16 + count(n - 3)); }}",
"e": 28688,
"s": 28575,
"text": null
},
{
"code": null,
"e": 28757,
"s": 28688,
"text": "Mathematical Approach O(1): Above relation can be optimized in O(1) "
},
{
"code": null,
"e": 28894,
"s": 28757,
"text": "// x is max no of time we can \n//subtract 3 without n-3 <= 3\nn - 3*x <= 3 \nx > (n-3)/3\ni.e. n/3 - 1 if it divides exactly\nelse n/3"
},
{
"code": null,
"e": 28947,
"s": 28894,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 28951,
"s": 28947,
"text": "CPP"
},
{
"code": null,
"e": 28956,
"s": 28951,
"text": "Java"
},
{
"code": null,
"e": 28964,
"s": 28956,
"text": "Python3"
},
{
"code": null,
"e": 28967,
"s": 28964,
"text": "C#"
},
{
"code": null,
"e": 28978,
"s": 28967,
"text": "Javascript"
},
{
"code": "// C++ program to find relation independent of l// length of the given pencil, for how much one// can write from n pencils. #include <bits/stdc++.h>using namespace std; // Function to find no of pencilsint count(int n){ int x = (n / 3) - 1; if (n % 3) { x++; } return (4 * x + 4 * n);} // Driver functionint main(){ int n = 5; cout << count(n) << endl;}",
"e": 29357,
"s": 28978,
"text": null
},
{
"code": "// Java program to find relation independent of l// length of the given pencil, for how much one// can write from n pencils.class GFG{ // Function to find no of pencilsstatic int count(int n){ int x = (n / 3) - 1; if (n % 3 > 0) { x++; } return (4 * x + 4 * n);} // Driver codepublic static void main(String[] args){ int n = 5; System.out.print(count(n) +\"\\n\");}} // This code is contributed by PrinciRaj1992",
"e": 29794,
"s": 29357,
"text": null
},
{
"code": "# Python3 program to find relation independent of l# length of the given pencil, for how much one# can write from n pencils. # Function to find no of pencilsdef count(n): x = (n // 3) - 1; if (n % 3 > 0): x+=1; return (4 * x + 4 * n); # Driver codeif __name__ == '__main__': n = 5; print(count(n)); # This code is contributed by PrinciRaj1992",
"e": 30168,
"s": 29794,
"text": null
},
{
"code": "// C# program to find relation independent of l// length of the given pencil, for how much one// can write from n pencils.using System; class GFG{ // Function to find no of pencilsstatic int count(int n){ int x = (n / 3) - 1; if (n % 3 > 0) { x++; } return (4 * x + 4 * n);} // Driver codepublic static void Main(String[] args){ int n = 5; Console.Write(count(n) +\"\\n\");}} // This code is contributed by 29AjayKumar",
"e": 30612,
"s": 30168,
"text": null
},
{
"code": "<script>// Javascript program to find relation independent of l// length of the given pencil, for how much one// can write from n pencils. // Function to find no of pencilsfunction count(n){ let x = Math.floor(n / 3) - 1; if (n % 3 > 0) { x++; } return (4 * x + 4 * n);} // Driver codelet n = 5;document.write(count(n) +\"<br>\"); // This code is contributed by rag2127</script>",
"e": 31011,
"s": 30612,
"text": null
},
{
"code": null,
"e": 31014,
"s": 31011,
"text": "24"
},
{
"code": null,
"e": 31823,
"s": 31016,
"text": "YouTubeGeeksforGeeks School17.7K subscribersCar Wheel PuzzleWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:30•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=s1WfONpTfbY\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>"
},
{
"code": null,
"e": 31839,
"s": 31823,
"text": "Gurjeet Singh 2"
},
{
"code": null,
"e": 31846,
"s": 31839,
"text": "md1844"
},
{
"code": null,
"e": 31860,
"s": 31846,
"text": "Chinmoy Lenka"
},
{
"code": null,
"e": 31874,
"s": 31860,
"text": "princiraj1992"
},
{
"code": null,
"e": 31886,
"s": 31874,
"text": "29AjayKumar"
},
{
"code": null,
"e": 31894,
"s": 31886,
"text": "rag2127"
},
{
"code": null,
"e": 31908,
"s": 31894,
"text": "akash19990918"
},
{
"code": null,
"e": 31919,
"s": 31908,
"text": "MakeMyTrip"
},
{
"code": null,
"e": 31927,
"s": 31919,
"text": "Puzzles"
},
{
"code": null,
"e": 31938,
"s": 31927,
"text": "MakeMyTrip"
},
{
"code": null,
"e": 31946,
"s": 31938,
"text": "Puzzles"
},
{
"code": null,
"e": 32044,
"s": 31946,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32076,
"s": 32044,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 32128,
"s": 32076,
"text": "Top 20 Puzzles Commonly Asked During SDE Interviews"
},
{
"code": null,
"e": 32152,
"s": 32128,
"text": "Puzzle 16 | (100 Doors)"
},
{
"code": null,
"e": 32183,
"s": 32152,
"text": "Puzzle 18 | (Torch and Bridge)"
},
{
"code": null,
"e": 32209,
"s": 32183,
"text": "Container with Most Water"
},
{
"code": null,
"e": 32259,
"s": 32209,
"text": "Puzzle 8 | (Find the Jar with contaminated pills)"
},
{
"code": null,
"e": 32296,
"s": 32259,
"text": "Puzzle 11 | (1000 Coins and 10 Bags)"
},
{
"code": null,
"e": 32351,
"s": 32296,
"text": "Puzzle 10 | (A Man with Medical Condition and 2 Pills)"
},
{
"code": null,
"e": 32399,
"s": 32351,
"text": "Puzzle 13 | (100 Prisoners with Red/Black Hats)"
}
] |
Matplotlib.pyplot.barh() function in Python - GeeksforGeeks | 23 Dec, 2020
A bar plot or bar chart is a graph that represents the category of data with rectangular bars with lengths and heights that is proportional to the values which they represent. The bar plots can be plotted horizontally or vertically. A bar chart describes the comparisons between the discrete categories. One of the axis of the plot represents the specific categories being compared, while the other axis represents the measured values corresponding to those categories.
The matplotlib API in Python provides the barh() function which can be used in MATLAB style use or as an object-oriented API. The syntax of the barh() function to be used with the axes is as follows:-
Syntax: matplotlib.pyplot.barh(y, width, height=0.8, left=None, *, align=’center’, **kwargs)
Some of the positional and optional parameters of the above function are described below:
The function creates a horizontal bar plot bounded with a rectangle depending on the given parameters. Following is a simple example of the barh() method to create a horizontal bar plot, which represents the number of students enrolled in different courses of an institute.
Example 1:
Python3
import numpy as npimport matplotlib.pyplot as plt # creating the datasetdata = {'C': 20, 'C++': 15, 'Java': 30, 'Python': 35} courses = list(data.keys())values = list(data.values()) fig = plt.figure(figsize=(10, 5)) # creating the bar plotplt.barh(courses, values, color='maroon') plt.xlabel("Courses offered")plt.ylabel("No. of students enrolled")plt.title("Students enrolled in different courses")plt.show()
Output :
Here plt.barh(courses, values, color=’maroon’) is used to specify that the bar chart is to be plotted by using the courses column as the Y-axis, and the values as the X-axis. The color attribute is used to set the color of the bars(maroon in this case).plt.xlabel(“Courses offered”) and plt.ylabel(“students enrolled”) are used to label the corresponding axes.plt.title() is used to make a title for the graph.plt.show() is used to show the graph as output using the previous commands.
Example 2:
Python3
import pandas as pdfrom matplotlib import pyplot as plt # Read CSV into pandasdata = pd.read_csv(r"Downloads/cars1.csv")data.head()df = pd.DataFrame(data) name = df['car'].head(12)price = df['price'].head(12) # Figure Sizefig, ax = plt.subplots(figsize=(16, 9)) # Horizontal Bar Plotax.barh(name, price) # Remove axes splinesfor s in ['top', 'bottom', 'left', 'right']: ax.spines[s].set_visible(False) # Remove x, y Ticksax.xaxis.set_ticks_position('none')ax.yaxis.set_ticks_position('none') # Add padding between axes and labelsax.xaxis.set_tick_params(pad=5)ax.yaxis.set_tick_params(pad=10) # Add x, y gridlinesax.grid(b=True, color='grey', linestyle='-.', linewidth=0.5, alpha=0.2) # Show top valuesax.invert_yaxis() # Add annotation to barsfor i in ax.patches: plt.text(i.get_width()+0.2, i.get_y()+0.5, str(round((i.get_width()), 2)), fontsize=10, fontweight='bold', color='grey') # Add Plot Titleax.set_title('Sports car and their price in crore', loc='left', ) # Add Text watermarkfig.text(0.9, 0.15, 'Jeeteshgavande30', fontsize=12, color='grey', ha='right', va='bottom', alpha=0.7) # Show Plotplt.show()
Output:
Matplotlib Pyplot-class
Picked
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 | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 25555,
"s": 25527,
"text": "\n23 Dec, 2020"
},
{
"code": null,
"e": 26025,
"s": 25555,
"text": "A bar plot or bar chart is a graph that represents the category of data with rectangular bars with lengths and heights that is proportional to the values which they represent. The bar plots can be plotted horizontally or vertically. A bar chart describes the comparisons between the discrete categories. One of the axis of the plot represents the specific categories being compared, while the other axis represents the measured values corresponding to those categories."
},
{
"code": null,
"e": 26226,
"s": 26025,
"text": "The matplotlib API in Python provides the barh() function which can be used in MATLAB style use or as an object-oriented API. The syntax of the barh() function to be used with the axes is as follows:-"
},
{
"code": null,
"e": 26319,
"s": 26226,
"text": "Syntax: matplotlib.pyplot.barh(y, width, height=0.8, left=None, *, align=’center’, **kwargs)"
},
{
"code": null,
"e": 26409,
"s": 26319,
"text": "Some of the positional and optional parameters of the above function are described below:"
},
{
"code": null,
"e": 26683,
"s": 26409,
"text": "The function creates a horizontal bar plot bounded with a rectangle depending on the given parameters. Following is a simple example of the barh() method to create a horizontal bar plot, which represents the number of students enrolled in different courses of an institute."
},
{
"code": null,
"e": 26694,
"s": 26683,
"text": "Example 1:"
},
{
"code": null,
"e": 26702,
"s": 26694,
"text": "Python3"
},
{
"code": "import numpy as npimport matplotlib.pyplot as plt # creating the datasetdata = {'C': 20, 'C++': 15, 'Java': 30, 'Python': 35} courses = list(data.keys())values = list(data.values()) fig = plt.figure(figsize=(10, 5)) # creating the bar plotplt.barh(courses, values, color='maroon') plt.xlabel(\"Courses offered\")plt.ylabel(\"No. of students enrolled\")plt.title(\"Students enrolled in different courses\")plt.show()",
"e": 27126,
"s": 26702,
"text": null
},
{
"code": null,
"e": 27135,
"s": 27126,
"text": "Output :"
},
{
"code": null,
"e": 27621,
"s": 27135,
"text": "Here plt.barh(courses, values, color=’maroon’) is used to specify that the bar chart is to be plotted by using the courses column as the Y-axis, and the values as the X-axis. The color attribute is used to set the color of the bars(maroon in this case).plt.xlabel(“Courses offered”) and plt.ylabel(“students enrolled”) are used to label the corresponding axes.plt.title() is used to make a title for the graph.plt.show() is used to show the graph as output using the previous commands."
},
{
"code": null,
"e": 27632,
"s": 27621,
"text": "Example 2:"
},
{
"code": null,
"e": 27640,
"s": 27632,
"text": "Python3"
},
{
"code": "import pandas as pdfrom matplotlib import pyplot as plt # Read CSV into pandasdata = pd.read_csv(r\"Downloads/cars1.csv\")data.head()df = pd.DataFrame(data) name = df['car'].head(12)price = df['price'].head(12) # Figure Sizefig, ax = plt.subplots(figsize=(16, 9)) # Horizontal Bar Plotax.barh(name, price) # Remove axes splinesfor s in ['top', 'bottom', 'left', 'right']: ax.spines[s].set_visible(False) # Remove x, y Ticksax.xaxis.set_ticks_position('none')ax.yaxis.set_ticks_position('none') # Add padding between axes and labelsax.xaxis.set_tick_params(pad=5)ax.yaxis.set_tick_params(pad=10) # Add x, y gridlinesax.grid(b=True, color='grey', linestyle='-.', linewidth=0.5, alpha=0.2) # Show top valuesax.invert_yaxis() # Add annotation to barsfor i in ax.patches: plt.text(i.get_width()+0.2, i.get_y()+0.5, str(round((i.get_width()), 2)), fontsize=10, fontweight='bold', color='grey') # Add Plot Titleax.set_title('Sports car and their price in crore', loc='left', ) # Add Text watermarkfig.text(0.9, 0.15, 'Jeeteshgavande30', fontsize=12, color='grey', ha='right', va='bottom', alpha=0.7) # Show Plotplt.show()",
"e": 28850,
"s": 27640,
"text": null
},
{
"code": null,
"e": 28858,
"s": 28850,
"text": "Output:"
},
{
"code": null,
"e": 28882,
"s": 28858,
"text": "Matplotlib Pyplot-class"
},
{
"code": null,
"e": 28889,
"s": 28882,
"text": "Picked"
},
{
"code": null,
"e": 28907,
"s": 28889,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 28914,
"s": 28907,
"text": "Python"
},
{
"code": null,
"e": 29012,
"s": 28914,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29044,
"s": 29012,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29086,
"s": 29044,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 29128,
"s": 29086,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 29184,
"s": 29128,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 29211,
"s": 29184,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 29242,
"s": 29211,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 29281,
"s": 29242,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 29310,
"s": 29281,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 29332,
"s": 29310,
"text": "Defaultdict in Python"
}
] |
Minimum number of deletions so that no two consecutive are same - GeeksforGeeks | 01 Feb, 2022
Given a string, find minimum number of deletions required so that there will be no two consecutive repeating characters in the string.Examples:
Input : AAABBB
Output : 4
Explanation : New string should be AB
Input : ABABABAB
Output : 0
Explanation : There are no consecutive repeating characters.
If there are n consecutive same characters delete n-1 out of those n characters.
C++
Java
Python3
C#
PHP
Javascript
// CPP code to count minimum deletions required// so that there are no consecutive characters left#include <bits/stdc++.h>using namespace std; int countDeletions(string str){ int ans = 0; for (int i = 0; i < str.length() - 1; i++) // If two consecutive characters are // the same, delete one of them. if (str[i] == str[i + 1]) ans++; return ans;} // Driver codeint main(){ string str = "AAABBB"; // Function call to print answer cout << countDeletions(str); return 0;}
// Java code to count minimum deletions required// so that there are no consecutive characters leftimport java.util.*; class GFG{ static int countDeletions(String s) { int ans = 0; char[] str = s.toCharArray(); for (int i = 0; i < str.length - 1; i++) // If two consecutive characters are // the same, delete one of them. if (str[i] == str[i + 1]) ans++; return ans; } // Driver code public static void main(String[] args) { String str = "AAABBB"; // Function call to print answer System.out.println(countDeletions(str)); }}/* This code is contributed by Mr. Somesh Awasthi */
# Python code to count minimum deletions required# so that there are no consecutive characters left\ def countDeletions(string): ans = 0 for i in range(len(string) - 1): # If two consecutive characters are # the same, delete one of them. if (string[i] == string[i + 1]): ans += 1 return ans # Driver codestring = "AAABBB" # Function call to print answerprint(countDeletions(string)) # This code is contributed by Sachin Bisht
// C# Program to count minimum deletions// required so that there are no// consecutive characters leftusing System; class GFG{ // Function for counting deletions static int countDeletions(String s){ int ans = 0; char []str = s.ToCharArray(); for (int i = 0; i < str.Length - 1; i++) // If two consecutive characters are // the same, delete one of them. if (str[i] == str[i + 1]) ans++; return ans;} // Driver code public static void Main() { String str = "AAABBB"; // Function call to print answer Console.Write(countDeletions(str)); }} // This code is contributed by Nitin Mittal.
<?php// PHP code to count minimum// deletions required so that// there are no consecutive// characters left function countDeletions($str){ $ans = 0; for ($i = 0; $i < strlen($str) - 1; $i++) // If two consecutive characters are // the same, delete one of them. if ($str[$i] == $str[$i + 1]) $ans++; return $ans;} // Driver Code $str = "AAABBB"; // Function call to // print answer echo countDeletions($str); // This code is contributed by nitin mittal?>
<script>// javascript code to count minimum deletions required// so that there are no consecutive characters left function countDeletions(s) { var ans = 0; var str = s; for (var i = 0; i < str.length - 1; i++) // If two consecutive characters are // the same, delete one of them. if (str[i] == str[i + 1]) ans++; return ans; } // Driver code var str = "AAABBB"; // Function call to print answer document.write(countDeletions(str)); // This code is contributed by gauravrajput1</script>
Output:
4
This article is contributed by Rohit Thapliyal. 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.
nitin mittal
GauravRajput1
simmytarika5
amartyaghoshgfg
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Check for Balanced Brackets in an expression (well-formedness) using Stack
KMP Algorithm for Pattern Searching
Array of Strings in C++ (5 Different Ways to Create)
Convert string to char array in C++
Check whether two strings are anagram of each other
Longest Palindromic Substring | Set 1
Caesar Cipher in Cryptography
Top 50 String Coding Problems for Interviews
Length of the longest substring without repeating characters
How to split a string in C/C++, Python and Java? | [
{
"code": null,
"e": 26284,
"s": 26256,
"text": "\n01 Feb, 2022"
},
{
"code": null,
"e": 26430,
"s": 26284,
"text": "Given a string, find minimum number of deletions required so that there will be no two consecutive repeating characters in the string.Examples: "
},
{
"code": null,
"e": 26584,
"s": 26430,
"text": "Input : AAABBB\nOutput : 4\nExplanation : New string should be AB\n\nInput : ABABABAB\nOutput : 0\nExplanation : There are no consecutive repeating characters."
},
{
"code": null,
"e": 26669,
"s": 26586,
"text": "If there are n consecutive same characters delete n-1 out of those n characters. "
},
{
"code": null,
"e": 26673,
"s": 26669,
"text": "C++"
},
{
"code": null,
"e": 26678,
"s": 26673,
"text": "Java"
},
{
"code": null,
"e": 26686,
"s": 26678,
"text": "Python3"
},
{
"code": null,
"e": 26689,
"s": 26686,
"text": "C#"
},
{
"code": null,
"e": 26693,
"s": 26689,
"text": "PHP"
},
{
"code": null,
"e": 26704,
"s": 26693,
"text": "Javascript"
},
{
"code": "// CPP code to count minimum deletions required// so that there are no consecutive characters left#include <bits/stdc++.h>using namespace std; int countDeletions(string str){ int ans = 0; for (int i = 0; i < str.length() - 1; i++) // If two consecutive characters are // the same, delete one of them. if (str[i] == str[i + 1]) ans++; return ans;} // Driver codeint main(){ string str = \"AAABBB\"; // Function call to print answer cout << countDeletions(str); return 0;}",
"e": 27244,
"s": 26704,
"text": null
},
{
"code": "// Java code to count minimum deletions required// so that there are no consecutive characters leftimport java.util.*; class GFG{ static int countDeletions(String s) { int ans = 0; char[] str = s.toCharArray(); for (int i = 0; i < str.length - 1; i++) // If two consecutive characters are // the same, delete one of them. if (str[i] == str[i + 1]) ans++; return ans; } // Driver code public static void main(String[] args) { String str = \"AAABBB\"; // Function call to print answer System.out.println(countDeletions(str)); }}/* This code is contributed by Mr. Somesh Awasthi */",
"e": 27927,
"s": 27244,
"text": null
},
{
"code": "# Python code to count minimum deletions required# so that there are no consecutive characters left\\ def countDeletions(string): ans = 0 for i in range(len(string) - 1): # If two consecutive characters are # the same, delete one of them. if (string[i] == string[i + 1]): ans += 1 return ans # Driver codestring = \"AAABBB\" # Function call to print answerprint(countDeletions(string)) # This code is contributed by Sachin Bisht",
"e": 28413,
"s": 27927,
"text": null
},
{
"code": "// C# Program to count minimum deletions// required so that there are no// consecutive characters leftusing System; class GFG{ // Function for counting deletions static int countDeletions(String s){ int ans = 0; char []str = s.ToCharArray(); for (int i = 0; i < str.Length - 1; i++) // If two consecutive characters are // the same, delete one of them. if (str[i] == str[i + 1]) ans++; return ans;} // Driver code public static void Main() { String str = \"AAABBB\"; // Function call to print answer Console.Write(countDeletions(str)); }} // This code is contributed by Nitin Mittal.",
"e": 29111,
"s": 28413,
"text": null
},
{
"code": "<?php// PHP code to count minimum// deletions required so that// there are no consecutive// characters left function countDeletions($str){ $ans = 0; for ($i = 0; $i < strlen($str) - 1; $i++) // If two consecutive characters are // the same, delete one of them. if ($str[$i] == $str[$i + 1]) $ans++; return $ans;} // Driver Code $str = \"AAABBB\"; // Function call to // print answer echo countDeletions($str); // This code is contributed by nitin mittal?>",
"e": 29641,
"s": 29111,
"text": null
},
{
"code": "<script>// javascript code to count minimum deletions required// so that there are no consecutive characters left function countDeletions(s) { var ans = 0; var str = s; for (var i = 0; i < str.length - 1; i++) // If two consecutive characters are // the same, delete one of them. if (str[i] == str[i + 1]) ans++; return ans; } // Driver code var str = \"AAABBB\"; // Function call to print answer document.write(countDeletions(str)); // This code is contributed by gauravrajput1</script>",
"e": 30254,
"s": 29641,
"text": null
},
{
"code": null,
"e": 30264,
"s": 30254,
"text": "Output: "
},
{
"code": null,
"e": 30266,
"s": 30264,
"text": "4"
},
{
"code": null,
"e": 30690,
"s": 30266,
"text": "This article is contributed by Rohit Thapliyal. 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": 30703,
"s": 30690,
"text": "nitin mittal"
},
{
"code": null,
"e": 30717,
"s": 30703,
"text": "GauravRajput1"
},
{
"code": null,
"e": 30730,
"s": 30717,
"text": "simmytarika5"
},
{
"code": null,
"e": 30746,
"s": 30730,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 30754,
"s": 30746,
"text": "Strings"
},
{
"code": null,
"e": 30762,
"s": 30754,
"text": "Strings"
},
{
"code": null,
"e": 30860,
"s": 30762,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30935,
"s": 30860,
"text": "Check for Balanced Brackets in an expression (well-formedness) using Stack"
},
{
"code": null,
"e": 30971,
"s": 30935,
"text": "KMP Algorithm for Pattern Searching"
},
{
"code": null,
"e": 31024,
"s": 30971,
"text": "Array of Strings in C++ (5 Different Ways to Create)"
},
{
"code": null,
"e": 31060,
"s": 31024,
"text": "Convert string to char array in C++"
},
{
"code": null,
"e": 31112,
"s": 31060,
"text": "Check whether two strings are anagram of each other"
},
{
"code": null,
"e": 31150,
"s": 31112,
"text": "Longest Palindromic Substring | Set 1"
},
{
"code": null,
"e": 31180,
"s": 31150,
"text": "Caesar Cipher in Cryptography"
},
{
"code": null,
"e": 31225,
"s": 31180,
"text": "Top 50 String Coding Problems for Interviews"
},
{
"code": null,
"e": 31286,
"s": 31225,
"text": "Length of the longest substring without repeating characters"
}
] |
Difference between Convolution VS Correlation - GeeksforGeeks | 11 Nov, 2021
Correlation is a mathematical technique to see how close two things are related. In image processing terms, it is used to compute the response of a mask on an image. A mask is applied on a matrix from left to right. Mask slides over the matrix from left to right by one unit every time. Once the mask reaches the rightmost end, the mask is slid downward by one unit and again starts from left to right side. The computed output is assigned to the central pixel, while neighbourhood pixels are also get used in the computation. The mask or the matrix can be 1-D or 2-D. Generally, the mask’s dimension is taken as an odd number, so that the central pixel can easily be found.
Illustration:
Image, I = [100, 120, 100, 150, 160]Indexes of the image are 0, 1, 2, 3 and 4.
Mask, H = [1/3, 1/3, 1/3]Indexes of the mask are -1, 0 and 1.
Apply correlation between image and mask at index=2 in the image.
J(2) = I(1) . H(-1) + I(2) . H(0) + I(3) . H(1)Indexes are represented in the parentheses.
J(2) = 120 x 1/3 + 100 x 1/3 + 150 x 1/3
J(2) = 370/3
In general, J = I . H
Correlation is denoted by (.)
The formula of 1D correlation:
The formula of 2D correlation:
Note:
The size of the resultant image depends on padding.
If padding is allowed, size of resultant image = size of the original image (input)
If padding is not allowed, size of resultant image < size of the input image.
A convolution is also a mathematical tool that is used to combine two things in order to produce the result. In image processing, convolution is a process by which we transform an input image by applying a kernel over it in a pixel-wise fashion. When the convolution mask operates on a particular pixel, then it performs the action by considering that pixel and its neighbouring pixels and the result is returned to that one particular pixel. Thus, we conclude that convolution in image processing is the mask operator.
1. Flip the mask and do correlation.2. The 1D mask is flipped horizontally, as there is a single row.3. The 2D mask is flipped vertically and horizontally.4. Mask is slid over the image matrix from the left to the right direction.5. When the mask hovers on the image, corresponding elements of mask and image are multiplied and the products are added.6. This process repeats for all the pixels of the image.
There are two types of operators in image processing.
Point operator: While operating on a particular pixel, it takes only one pixel as input that is itself. For example Brightness increasing operation. We increase each pixel’s intensity by the same value to increase the brightness of the image.
Mask operator: While performing an action on a particular pixel it takes the particular pixel and its neighbouring pixels as the input. Convolution operation.
Illustration:
Image, I = [100, 120, 100, 150, 160]
Indexes of the image are 0, 1, 2, 3 and 4.
Mask used for correlation, H = [1/3, 1/3, 1/3]
Indexes of the mask are -1, 0 and 1.
We are using same mask not the flipped one, hence we shall use the indexes properly.
Apply convolution between image and mask at index=1 in the image.
J(2) = I(0) . H(1) + I(1) . H(0) + I(2) . H(-1)Indexes are represented in the parentheses.
J = I * H
Convolution is denoted by (*).
Size of resultant image follows same as in case of correlation.
The formula of 1D convolution:
The formula of 2D convolution:
Note: Convolution and correlation give the same response if the mask is symmetric. Both correlation and convolution look similar in nature. But we use convolution extensively in image processing because of its following properties.
Convolution is associative in nature, but not the correlation. i.e.
Convolution is commutative in nature. i.e.
Convolution follows linearity. i.e. where s is any constant and multiplied to the mask or the image.
Convolution follows separability if the mask is separable. i.e. If
If the kernel is separable then it can save computational cost.
Step 1: Matrix initialisation is done in one line in Matlab, order of matrix does not matter.
K = [1, 2, 3; 2, 4, 5];
Step 2: MatLab inbuilt method is used to create matrix of ones:
H = ones(3,3).*1/9;
Step 3: We have used (.) before *, cause (.) means we are multiplying all elements of (3, 3) matrix by 1/9.
Initialise the linear mask of order 1 by 3:
H1=ones(1,3).*1/3;
Initialise transpose mask, which is separated from the main mask:
H2=H1'
Step 4: Convolution between matrix K and mask H is applied using Matlab inbuilt function “conv2”
KH = conv2(K, H, 'same');
Step 5: Convolution between matrix K and mask H1:
KH1 = conv2(K, H1, 'same');
Step 6: Convolution between result matrix KH1 and mask H2:
KH2 = conv2(KH1, H2, 'same');
Example:
Matlab
% MATLAB Code for separable mask% D convolution% Define the matrix. K=[9 18 9 27 36; 81 9 45 54 9; 36 18 63 72 9]; % Define the averaging mask. H = ones(3,3).*1/9; % Separate the mask. H1 = ones(1,3).*1/3; % Transpose of separated mask. H2 = H1'; % Perform the same convolution. KH = conv2(K,H,'same') KH1 = conv2(K,H1,'same') KH2 = conv2(KH1,H2,'same')
Output:
Code explanation:
First, we define the matrix image.
After matrix creation, we define the main averaging mask, named H.
Separable masks H1 and H2 are defined.
The second mask is the transpose of mask1.
The convolution between matrix K and mask H is calculated in the KH variable.
The convolution between matrix K and mask H1 is stored in the KH1 variable.
KH2 = conv2(KH1, H2, ‘same’); This line applies the convolution between result matrix KH1 and masks H2.This result is the same as KH.
MATLAB image-processing
MATLAB
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Forward and Inverse Fourier Transform of an Image in MATLAB
How to Remove Noise from Digital Image in Frequency Domain Using MATLAB?
Boundary Extraction of image using MATLAB
How to Solve Histogram Equalization Numerical Problem in MATLAB?
How to Normalize a Histogram in MATLAB?
Double Integral in MATLAB
How to Remove Salt and Pepper Noise from Image Using MATLAB?
Classes and Object in MATLAB
What are different types of denoising filters in MATLAB?
How to Convert Three Channels of Colored Image into Grayscale Image in MATLAB? | [
{
"code": null,
"e": 25793,
"s": 25765,
"text": "\n11 Nov, 2021"
},
{
"code": null,
"e": 26468,
"s": 25793,
"text": "Correlation is a mathematical technique to see how close two things are related. In image processing terms, it is used to compute the response of a mask on an image. A mask is applied on a matrix from left to right. Mask slides over the matrix from left to right by one unit every time. Once the mask reaches the rightmost end, the mask is slid downward by one unit and again starts from left to right side. The computed output is assigned to the central pixel, while neighbourhood pixels are also get used in the computation. The mask or the matrix can be 1-D or 2-D. Generally, the mask’s dimension is taken as an odd number, so that the central pixel can easily be found."
},
{
"code": null,
"e": 26482,
"s": 26468,
"text": "Illustration:"
},
{
"code": null,
"e": 26561,
"s": 26482,
"text": "Image, I = [100, 120, 100, 150, 160]Indexes of the image are 0, 1, 2, 3 and 4."
},
{
"code": null,
"e": 26623,
"s": 26561,
"text": "Mask, H = [1/3, 1/3, 1/3]Indexes of the mask are -1, 0 and 1."
},
{
"code": null,
"e": 26689,
"s": 26623,
"text": "Apply correlation between image and mask at index=2 in the image."
},
{
"code": null,
"e": 26780,
"s": 26689,
"text": "J(2) = I(1) . H(-1) + I(2) . H(0) + I(3) . H(1)Indexes are represented in the parentheses."
},
{
"code": null,
"e": 26821,
"s": 26780,
"text": "J(2) = 120 x 1/3 + 100 x 1/3 + 150 x 1/3"
},
{
"code": null,
"e": 26834,
"s": 26821,
"text": "J(2) = 370/3"
},
{
"code": null,
"e": 26856,
"s": 26834,
"text": "In general, J = I . H"
},
{
"code": null,
"e": 26886,
"s": 26856,
"text": "Correlation is denoted by (.)"
},
{
"code": null,
"e": 26918,
"s": 26886,
"text": "The formula of 1D correlation: "
},
{
"code": null,
"e": 26950,
"s": 26918,
"text": "The formula of 2D correlation: "
},
{
"code": null,
"e": 26956,
"s": 26950,
"text": "Note:"
},
{
"code": null,
"e": 27008,
"s": 26956,
"text": "The size of the resultant image depends on padding."
},
{
"code": null,
"e": 27092,
"s": 27008,
"text": "If padding is allowed, size of resultant image = size of the original image (input)"
},
{
"code": null,
"e": 27170,
"s": 27092,
"text": "If padding is not allowed, size of resultant image < size of the input image."
},
{
"code": null,
"e": 27691,
"s": 27170,
"text": "A convolution is also a mathematical tool that is used to combine two things in order to produce the result. In image processing, convolution is a process by which we transform an input image by applying a kernel over it in a pixel-wise fashion. When the convolution mask operates on a particular pixel, then it performs the action by considering that pixel and its neighbouring pixels and the result is returned to that one particular pixel. Thus, we conclude that convolution in image processing is the mask operator. "
},
{
"code": null,
"e": 28099,
"s": 27691,
"text": "1. Flip the mask and do correlation.2. The 1D mask is flipped horizontally, as there is a single row.3. The 2D mask is flipped vertically and horizontally.4. Mask is slid over the image matrix from the left to the right direction.5. When the mask hovers on the image, corresponding elements of mask and image are multiplied and the products are added.6. This process repeats for all the pixels of the image."
},
{
"code": null,
"e": 28154,
"s": 28099,
"text": "There are two types of operators in image processing. "
},
{
"code": null,
"e": 28398,
"s": 28154,
"text": "Point operator: While operating on a particular pixel, it takes only one pixel as input that is itself. For example Brightness increasing operation. We increase each pixel’s intensity by the same value to increase the brightness of the image."
},
{
"code": null,
"e": 28557,
"s": 28398,
"text": "Mask operator: While performing an action on a particular pixel it takes the particular pixel and its neighbouring pixels as the input. Convolution operation."
},
{
"code": null,
"e": 28571,
"s": 28557,
"text": "Illustration:"
},
{
"code": null,
"e": 28608,
"s": 28571,
"text": "Image, I = [100, 120, 100, 150, 160]"
},
{
"code": null,
"e": 28651,
"s": 28608,
"text": "Indexes of the image are 0, 1, 2, 3 and 4."
},
{
"code": null,
"e": 28698,
"s": 28651,
"text": "Mask used for correlation, H = [1/3, 1/3, 1/3]"
},
{
"code": null,
"e": 28735,
"s": 28698,
"text": "Indexes of the mask are -1, 0 and 1."
},
{
"code": null,
"e": 28820,
"s": 28735,
"text": "We are using same mask not the flipped one, hence we shall use the indexes properly."
},
{
"code": null,
"e": 28886,
"s": 28820,
"text": "Apply convolution between image and mask at index=1 in the image."
},
{
"code": null,
"e": 28977,
"s": 28886,
"text": "J(2) = I(0) . H(1) + I(1) . H(0) + I(2) . H(-1)Indexes are represented in the parentheses."
},
{
"code": null,
"e": 28987,
"s": 28977,
"text": "J = I * H"
},
{
"code": null,
"e": 29018,
"s": 28987,
"text": "Convolution is denoted by (*)."
},
{
"code": null,
"e": 29082,
"s": 29018,
"text": "Size of resultant image follows same as in case of correlation."
},
{
"code": null,
"e": 29113,
"s": 29082,
"text": "The formula of 1D convolution:"
},
{
"code": null,
"e": 29145,
"s": 29113,
"text": "The formula of 2D convolution: "
},
{
"code": null,
"e": 29377,
"s": 29145,
"text": "Note: Convolution and correlation give the same response if the mask is symmetric. Both correlation and convolution look similar in nature. But we use convolution extensively in image processing because of its following properties."
},
{
"code": null,
"e": 29446,
"s": 29377,
"text": "Convolution is associative in nature, but not the correlation. i.e. "
},
{
"code": null,
"e": 29490,
"s": 29446,
"text": "Convolution is commutative in nature. i.e. "
},
{
"code": null,
"e": 29592,
"s": 29490,
"text": "Convolution follows linearity. i.e. where s is any constant and multiplied to the mask or the image."
},
{
"code": null,
"e": 29659,
"s": 29592,
"text": "Convolution follows separability if the mask is separable. i.e. If"
},
{
"code": null,
"e": 29723,
"s": 29659,
"text": "If the kernel is separable then it can save computational cost."
},
{
"code": null,
"e": 29817,
"s": 29723,
"text": "Step 1: Matrix initialisation is done in one line in Matlab, order of matrix does not matter."
},
{
"code": null,
"e": 29841,
"s": 29817,
"text": "K = [1, 2, 3; 2, 4, 5];"
},
{
"code": null,
"e": 29905,
"s": 29841,
"text": "Step 2: MatLab inbuilt method is used to create matrix of ones:"
},
{
"code": null,
"e": 29926,
"s": 29905,
"text": " H = ones(3,3).*1/9;"
},
{
"code": null,
"e": 30034,
"s": 29926,
"text": "Step 3: We have used (.) before *, cause (.) means we are multiplying all elements of (3, 3) matrix by 1/9."
},
{
"code": null,
"e": 30078,
"s": 30034,
"text": "Initialise the linear mask of order 1 by 3:"
},
{
"code": null,
"e": 30098,
"s": 30078,
"text": " H1=ones(1,3).*1/3;"
},
{
"code": null,
"e": 30164,
"s": 30098,
"text": "Initialise transpose mask, which is separated from the main mask:"
},
{
"code": null,
"e": 30171,
"s": 30164,
"text": "H2=H1'"
},
{
"code": null,
"e": 30268,
"s": 30171,
"text": "Step 4: Convolution between matrix K and mask H is applied using Matlab inbuilt function “conv2”"
},
{
"code": null,
"e": 30294,
"s": 30268,
"text": "KH = conv2(K, H, 'same');"
},
{
"code": null,
"e": 30345,
"s": 30294,
"text": "Step 5: Convolution between matrix K and mask H1: "
},
{
"code": null,
"e": 30373,
"s": 30345,
"text": "KH1 = conv2(K, H1, 'same');"
},
{
"code": null,
"e": 30433,
"s": 30373,
"text": "Step 6: Convolution between result matrix KH1 and mask H2: "
},
{
"code": null,
"e": 30463,
"s": 30433,
"text": "KH2 = conv2(KH1, H2, 'same');"
},
{
"code": null,
"e": 30472,
"s": 30463,
"text": "Example:"
},
{
"code": null,
"e": 30479,
"s": 30472,
"text": "Matlab"
},
{
"code": "% MATLAB Code for separable mask% D convolution% Define the matrix. K=[9 18 9 27 36; 81 9 45 54 9; 36 18 63 72 9]; % Define the averaging mask. H = ones(3,3).*1/9; % Separate the mask. H1 = ones(1,3).*1/3; % Transpose of separated mask. H2 = H1'; % Perform the same convolution. KH = conv2(K,H,'same') KH1 = conv2(K,H1,'same') KH2 = conv2(KH1,H2,'same')",
"e": 30848,
"s": 30479,
"text": null
},
{
"code": null,
"e": 30857,
"s": 30848,
"text": "Output: "
},
{
"code": null,
"e": 30880,
"s": 30861,
"text": "Code explanation: "
},
{
"code": null,
"e": 30915,
"s": 30880,
"text": "First, we define the matrix image."
},
{
"code": null,
"e": 30982,
"s": 30915,
"text": "After matrix creation, we define the main averaging mask, named H."
},
{
"code": null,
"e": 31021,
"s": 30982,
"text": "Separable masks H1 and H2 are defined."
},
{
"code": null,
"e": 31064,
"s": 31021,
"text": "The second mask is the transpose of mask1."
},
{
"code": null,
"e": 31142,
"s": 31064,
"text": "The convolution between matrix K and mask H is calculated in the KH variable."
},
{
"code": null,
"e": 31218,
"s": 31142,
"text": "The convolution between matrix K and mask H1 is stored in the KH1 variable."
},
{
"code": null,
"e": 31352,
"s": 31218,
"text": "KH2 = conv2(KH1, H2, ‘same’); This line applies the convolution between result matrix KH1 and masks H2.This result is the same as KH."
},
{
"code": null,
"e": 31378,
"s": 31354,
"text": "MATLAB image-processing"
},
{
"code": null,
"e": 31385,
"s": 31378,
"text": "MATLAB"
},
{
"code": null,
"e": 31483,
"s": 31385,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31543,
"s": 31483,
"text": "Forward and Inverse Fourier Transform of an Image in MATLAB"
},
{
"code": null,
"e": 31616,
"s": 31543,
"text": "How to Remove Noise from Digital Image in Frequency Domain Using MATLAB?"
},
{
"code": null,
"e": 31658,
"s": 31616,
"text": "Boundary Extraction of image using MATLAB"
},
{
"code": null,
"e": 31723,
"s": 31658,
"text": "How to Solve Histogram Equalization Numerical Problem in MATLAB?"
},
{
"code": null,
"e": 31763,
"s": 31723,
"text": "How to Normalize a Histogram in MATLAB?"
},
{
"code": null,
"e": 31789,
"s": 31763,
"text": "Double Integral in MATLAB"
},
{
"code": null,
"e": 31850,
"s": 31789,
"text": "How to Remove Salt and Pepper Noise from Image Using MATLAB?"
},
{
"code": null,
"e": 31879,
"s": 31850,
"text": "Classes and Object in MATLAB"
},
{
"code": null,
"e": 31936,
"s": 31879,
"text": "What are different types of denoising filters in MATLAB?"
}
] |
Ropes left after every removal of smallest - GeeksforGeeks | 05 Apr, 2022
Given an array of an integer of size, N. Array contains N ropes of length Ropes[i]. You have to perform a cut operation on ropes such that all of them are reduced by the length of the smallest rope. Display the number of ropes left after every cut. Perform operations till the length of each rope becomes zero. Note: IF no ropes left after a single operation, in this case, we print 0.
Examples:
Input : Ropes[] = { 5, 1, 1, 2, 3, 5 } Output : 4 3 2 Explanation : In first operation the minimum ropes is 1 so we reduce length 1 from all of them after reducing we left with 4 ropes and we do same for rest.
Input : Ropes[] = { 5, 1, 6, 9, 8, 11, 2, 2, 6, 5 } Output : 9 7 5 3 2 1
Simple solution is to we traverse a loop from [0...n-1], In each iterations first we find min length rope. After that, we reduce all ropes length by it and then count how many ropes are left whose length is greater than zero. this process is done until all ropes length is greater than zero. This solution work in O(n2) time.
Efficient solution works in O(nlog(n)). First we have to sort all Ropes in increasing order of there length. after that we have follow the step.
//initial cutting length "min rope"
CuttingLength = Ropes[0]
Now Traverse a loop from left to right [1...n]
.During traverse we check that
is current ropes length is greater than zero or not
IF ( Ropes[i] - CuttingLength > 0 )
.... IF Yes then all ropes to it's right side also greater than 0
.... Print number of ropes remains (n - i)
....update Cutting Length by current rope length
...... CuttingLength = Ropes[i]
Do the same process for the rest.
Below is the implementation of above idea.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to print how many// Ropes are Left After Every Cut#include <bits/stdc++.h>using namespace std; // Function print how many Ropes are// Left AfterEvery Cutting operationvoid cuttringRopes(int Ropes[], int n){ // sort all Ropes in increase // of there length sort(Ropes, Ropes + n); int singleOperation = 0; // min length rope int cuttingLength = Ropes[0]; // now traverse through the given // Ropes in increase order of length for (int i = 1; i < n; i++) { // After cutting if current rope length // is greater than '0' that mean all // ropes to it's right side are also // greater than 0 if (Ropes[i] - cuttingLength > 0) { // print number of ropes remains cout << (n - i) << " "; // now current rope become // min length rope cuttingLength = Ropes[i]; singleOperation++; } } if (singleOperation == 0) cout << "0 ";}int main(){ int Ropes[] = { 5, 1, 1, 2, 3, 5 }; int n = sizeof(Ropes) / sizeof(Ropes[0]); cuttringRopes(Ropes, n); return 0;}
// Java program to print how many// Ropes are Left After Every Cutimport java.util.*;import java.lang.*;import java.io.*; class GFG { // function print how many Ropes are Left After // Every Cutting operation public static void cuttringRopes(int Ropes[], int n) { // sort all Ropes in increasing // order of their length Arrays.sort(Ropes); int singleOperation = 0; // min length rope int cuttingLength = Ropes[0]; // now traverse through the given Ropes in // increase order of length for (int i = 1; i < n; i++) { // After cutting if current rope length // is greater than '0' that mean all // ropes to it's right side are also // greater than 0 if (Ropes[i] - cuttingLength > 0) { System.out.print(n - i + " "); // now current rope become // min length rope cuttingLength = Ropes[i]; singleOperation++; } } // after first operation all ropes // length become zero if (singleOperation == 0) System.out.print("0"); } public static void main(String[] arg) { int[] Ropes = { 5, 1, 1, 2, 3, 5 }; int n = Ropes.length; cuttringRopes(Ropes, n); }}
# Python program to print how many# Ropes are Left After Every Cut # Function print how many Ropes are# Left After Every Cutting operationdef cuttringRopes(Ropes, n): # Sort all Ropes in increasing # order of their length Ropes.sort() singleOperation = 0 # min length rope cuttingLength = Ropes[0] # Now traverse through the given # Ropes in increase order of length for i in range(1,n): # After cutting if current rope length # is greater than '0' that mean all # ropes to it's right side are also # greater than 0 if (Ropes[i] - cuttingLength > 0): print(n - i,end = " ") # Now current rope become # min length rope cuttingLength = Ropes[i] singleOperation += 1 # After first operation all ropes # length become zero if (singleOperation == 0): print("0") # Driver CodeRopes = [ 5, 1, 1, 2, 3, 5 ]n = len(Ropes) cuttringRopes(Ropes, n) # This code is contributed by shinjanpatra
// C# program to print how many// Ropes are Left After Every Cutusing System; class GFG { // function print how many Ropes are Left After // Every Cutting operation public static void cuttringRopes(int []Ropes, int n) { // sort all Ropes in increasing // order of their length Array.Sort(Ropes); int singleOperation = 0; // min length rope int cuttingLength = Ropes[0]; // now traverse through the given Ropes in // increase order of length for (int i = 1; i < n; i++) { // After cutting if current rope length // is greater than '0' that mean all // ropes to it's right side are also // greater than 0 if (Ropes[i] - cuttingLength > 0) { Console.Write(n - i + " "); // now current rope become // min length rope cuttingLength = Ropes[i]; singleOperation++; } } // after first operation all ropes // length become zero if (singleOperation == 0) Console.Write("0"); } // Driver code public static void Main() { int[] Ropes = { 5, 1, 1, 2, 3, 5 }; int n = Ropes.Length; cuttringRopes(Ropes, n); }} // This code is contributed by vt_m.
<?php// PHP program to print how many// Ropes are Left After Every Cut // Function print how many Ropes are// Left AfterEvery Cutting operationfunction cuttringRopes($Ropes, $n){ // sort all Ropes in increase // of there length sort($Ropes); $singleOperation = 0; // min length rope $cuttingLength = $Ropes[0]; // now traverse through the given // Ropes in increase order of length for ($i = 1; $i < $n; $i++) { // After cutting if current rope length // is greater than '0' that mean all // ropes to it's right side are also // greater than 0 if ($Ropes[$i] - $cuttingLength > 0) { // print number of ropes remains echo ($n - $i). " "; // now current rope become // min length rope $cuttingLength = $Ropes[$i]; $singleOperation++; } } if ($singleOperation == 0) echo "0 ";} // Driver Code $Ropes = array(5, 1, 1, 2, 3, 5); $n = count($Ropes); cuttringRopes($Ropes, $n); // This code is contributed by Sam007?>
<script> // JavaScript program to print how many// Ropes are Left After Every Cut // Function print how many Ropes are// Left After Every Cutting operationfunction cuttringRopes(Ropes, n){ // Sort all Ropes in increasing // order of their length Ropes.sort(); let singleOperation = 0; // min length rope let cuttingLength = Ropes[0]; // Now traverse through the given // Ropes in increase order of length for(let i = 1; i < n; i++) { // After cutting if current rope length // is greater than '0' that mean all // ropes to it's right side are also // greater than 0 if (Ropes[i] - cuttingLength > 0) { document.write(n - i + " "); // Now current rope become // min length rope cuttingLength = Ropes[i]; singleOperation++; } } // After first operation all ropes // length become zero if (singleOperation == 0) document.write("0");} // Driver Codelet Ropes = [ 5, 1, 1, 2, 3, 5 ];let n = Ropes.length; cuttringRopes(Ropes, n); // This code is contributed by avijitmondal1998 </script>
4 3 2
Time Complexity : O(n long (n)) Space complexity : O(1)
Sam007
shubham_singh
avijitmondal1998
sweetyty
varshagumber28
shinjanpatra
Arrays
Sorting
Arrays
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
Introduction to Arrays
Multidimensional Arrays in Java
Linear Search
Linked List vs Array | [
{
"code": null,
"e": 26697,
"s": 26669,
"text": "\n05 Apr, 2022"
},
{
"code": null,
"e": 27084,
"s": 26697,
"text": "Given an array of an integer of size, N. Array contains N ropes of length Ropes[i]. You have to perform a cut operation on ropes such that all of them are reduced by the length of the smallest rope. Display the number of ropes left after every cut. Perform operations till the length of each rope becomes zero. Note: IF no ropes left after a single operation, in this case, we print 0. "
},
{
"code": null,
"e": 27096,
"s": 27084,
"text": "Examples: "
},
{
"code": null,
"e": 27306,
"s": 27096,
"text": "Input : Ropes[] = { 5, 1, 1, 2, 3, 5 } Output : 4 3 2 Explanation : In first operation the minimum ropes is 1 so we reduce length 1 from all of them after reducing we left with 4 ropes and we do same for rest."
},
{
"code": null,
"e": 27381,
"s": 27306,
"text": "Input : Ropes[] = { 5, 1, 6, 9, 8, 11, 2, 2, 6, 5 } Output : 9 7 5 3 2 1 "
},
{
"code": null,
"e": 27707,
"s": 27381,
"text": "Simple solution is to we traverse a loop from [0...n-1], In each iterations first we find min length rope. After that, we reduce all ropes length by it and then count how many ropes are left whose length is greater than zero. this process is done until all ropes length is greater than zero. This solution work in O(n2) time."
},
{
"code": null,
"e": 27854,
"s": 27707,
"text": "Efficient solution works in O(nlog(n)). First we have to sort all Ropes in increasing order of there length. after that we have follow the step. "
},
{
"code": null,
"e": 28328,
"s": 27854,
"text": "//initial cutting length \"min rope\" \nCuttingLength = Ropes[0]\nNow Traverse a loop from left to right [1...n]\n .During traverse we check that \n is current ropes length is greater than zero or not \n IF ( Ropes[i] - CuttingLength > 0 ) \n .... IF Yes then all ropes to it's right side also greater than 0\n .... Print number of ropes remains (n - i)\n ....update Cutting Length by current rope length\n ...... CuttingLength = Ropes[i] \nDo the same process for the rest."
},
{
"code": null,
"e": 28372,
"s": 28328,
"text": "Below is the implementation of above idea. "
},
{
"code": null,
"e": 28376,
"s": 28372,
"text": "C++"
},
{
"code": null,
"e": 28381,
"s": 28376,
"text": "Java"
},
{
"code": null,
"e": 28389,
"s": 28381,
"text": "Python3"
},
{
"code": null,
"e": 28392,
"s": 28389,
"text": "C#"
},
{
"code": null,
"e": 28396,
"s": 28392,
"text": "PHP"
},
{
"code": null,
"e": 28407,
"s": 28396,
"text": "Javascript"
},
{
"code": "// C++ program to print how many// Ropes are Left After Every Cut#include <bits/stdc++.h>using namespace std; // Function print how many Ropes are// Left AfterEvery Cutting operationvoid cuttringRopes(int Ropes[], int n){ // sort all Ropes in increase // of there length sort(Ropes, Ropes + n); int singleOperation = 0; // min length rope int cuttingLength = Ropes[0]; // now traverse through the given // Ropes in increase order of length for (int i = 1; i < n; i++) { // After cutting if current rope length // is greater than '0' that mean all // ropes to it's right side are also // greater than 0 if (Ropes[i] - cuttingLength > 0) { // print number of ropes remains cout << (n - i) << \" \"; // now current rope become // min length rope cuttingLength = Ropes[i]; singleOperation++; } } if (singleOperation == 0) cout << \"0 \";}int main(){ int Ropes[] = { 5, 1, 1, 2, 3, 5 }; int n = sizeof(Ropes) / sizeof(Ropes[0]); cuttringRopes(Ropes, n); return 0;}",
"e": 29549,
"s": 28407,
"text": null
},
{
"code": "// Java program to print how many// Ropes are Left After Every Cutimport java.util.*;import java.lang.*;import java.io.*; class GFG { // function print how many Ropes are Left After // Every Cutting operation public static void cuttringRopes(int Ropes[], int n) { // sort all Ropes in increasing // order of their length Arrays.sort(Ropes); int singleOperation = 0; // min length rope int cuttingLength = Ropes[0]; // now traverse through the given Ropes in // increase order of length for (int i = 1; i < n; i++) { // After cutting if current rope length // is greater than '0' that mean all // ropes to it's right side are also // greater than 0 if (Ropes[i] - cuttingLength > 0) { System.out.print(n - i + \" \"); // now current rope become // min length rope cuttingLength = Ropes[i]; singleOperation++; } } // after first operation all ropes // length become zero if (singleOperation == 0) System.out.print(\"0\"); } public static void main(String[] arg) { int[] Ropes = { 5, 1, 1, 2, 3, 5 }; int n = Ropes.length; cuttringRopes(Ropes, n); }}",
"e": 30935,
"s": 29549,
"text": null
},
{
"code": "# Python program to print how many# Ropes are Left After Every Cut # Function print how many Ropes are# Left After Every Cutting operationdef cuttringRopes(Ropes, n): # Sort all Ropes in increasing # order of their length Ropes.sort() singleOperation = 0 # min length rope cuttingLength = Ropes[0] # Now traverse through the given # Ropes in increase order of length for i in range(1,n): # After cutting if current rope length # is greater than '0' that mean all # ropes to it's right side are also # greater than 0 if (Ropes[i] - cuttingLength > 0): print(n - i,end = \" \") # Now current rope become # min length rope cuttingLength = Ropes[i] singleOperation += 1 # After first operation all ropes # length become zero if (singleOperation == 0): print(\"0\") # Driver CodeRopes = [ 5, 1, 1, 2, 3, 5 ]n = len(Ropes) cuttringRopes(Ropes, n) # This code is contributed by shinjanpatra",
"e": 31992,
"s": 30935,
"text": null
},
{
"code": "// C# program to print how many// Ropes are Left After Every Cutusing System; class GFG { // function print how many Ropes are Left After // Every Cutting operation public static void cuttringRopes(int []Ropes, int n) { // sort all Ropes in increasing // order of their length Array.Sort(Ropes); int singleOperation = 0; // min length rope int cuttingLength = Ropes[0]; // now traverse through the given Ropes in // increase order of length for (int i = 1; i < n; i++) { // After cutting if current rope length // is greater than '0' that mean all // ropes to it's right side are also // greater than 0 if (Ropes[i] - cuttingLength > 0) { Console.Write(n - i + \" \"); // now current rope become // min length rope cuttingLength = Ropes[i]; singleOperation++; } } // after first operation all ropes // length become zero if (singleOperation == 0) Console.Write(\"0\"); } // Driver code public static void Main() { int[] Ropes = { 5, 1, 1, 2, 3, 5 }; int n = Ropes.Length; cuttringRopes(Ropes, n); }} // This code is contributed by vt_m.",
"e": 33370,
"s": 31992,
"text": null
},
{
"code": "<?php// PHP program to print how many// Ropes are Left After Every Cut // Function print how many Ropes are// Left AfterEvery Cutting operationfunction cuttringRopes($Ropes, $n){ // sort all Ropes in increase // of there length sort($Ropes); $singleOperation = 0; // min length rope $cuttingLength = $Ropes[0]; // now traverse through the given // Ropes in increase order of length for ($i = 1; $i < $n; $i++) { // After cutting if current rope length // is greater than '0' that mean all // ropes to it's right side are also // greater than 0 if ($Ropes[$i] - $cuttingLength > 0) { // print number of ropes remains echo ($n - $i). \" \"; // now current rope become // min length rope $cuttingLength = $Ropes[$i]; $singleOperation++; } } if ($singleOperation == 0) echo \"0 \";} // Driver Code $Ropes = array(5, 1, 1, 2, 3, 5); $n = count($Ropes); cuttringRopes($Ropes, $n); // This code is contributed by Sam007?>",
"e": 34482,
"s": 33370,
"text": null
},
{
"code": "<script> // JavaScript program to print how many// Ropes are Left After Every Cut // Function print how many Ropes are// Left After Every Cutting operationfunction cuttringRopes(Ropes, n){ // Sort all Ropes in increasing // order of their length Ropes.sort(); let singleOperation = 0; // min length rope let cuttingLength = Ropes[0]; // Now traverse through the given // Ropes in increase order of length for(let i = 1; i < n; i++) { // After cutting if current rope length // is greater than '0' that mean all // ropes to it's right side are also // greater than 0 if (Ropes[i] - cuttingLength > 0) { document.write(n - i + \" \"); // Now current rope become // min length rope cuttingLength = Ropes[i]; singleOperation++; } } // After first operation all ropes // length become zero if (singleOperation == 0) document.write(\"0\");} // Driver Codelet Ropes = [ 5, 1, 1, 2, 3, 5 ];let n = Ropes.length; cuttringRopes(Ropes, n); // This code is contributed by avijitmondal1998 </script>",
"e": 35666,
"s": 34482,
"text": null
},
{
"code": null,
"e": 35673,
"s": 35666,
"text": "4 3 2 "
},
{
"code": null,
"e": 35730,
"s": 35673,
"text": "Time Complexity : O(n long (n)) Space complexity : O(1) "
},
{
"code": null,
"e": 35737,
"s": 35730,
"text": "Sam007"
},
{
"code": null,
"e": 35751,
"s": 35737,
"text": "shubham_singh"
},
{
"code": null,
"e": 35768,
"s": 35751,
"text": "avijitmondal1998"
},
{
"code": null,
"e": 35777,
"s": 35768,
"text": "sweetyty"
},
{
"code": null,
"e": 35792,
"s": 35777,
"text": "varshagumber28"
},
{
"code": null,
"e": 35805,
"s": 35792,
"text": "shinjanpatra"
},
{
"code": null,
"e": 35812,
"s": 35805,
"text": "Arrays"
},
{
"code": null,
"e": 35820,
"s": 35812,
"text": "Sorting"
},
{
"code": null,
"e": 35827,
"s": 35820,
"text": "Arrays"
},
{
"code": null,
"e": 35835,
"s": 35827,
"text": "Sorting"
},
{
"code": null,
"e": 35933,
"s": 35835,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36001,
"s": 35933,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 36024,
"s": 36001,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 36056,
"s": 36024,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 36070,
"s": 36056,
"text": "Linear Search"
}
] |
How to pick which Angular Bundle to Preload ? - GeeksforGeeks | 23 Dec, 2020
Loading strategy in angular decides how to load the app modules when the application runs into the browser. In Angular, we have three types of loading: Eager loading, lazy loading, and preloading. By default, Angular follows eager loading i.e. as soon as the application starts downloading in the browser, the modules start to load within the browser. You can also set some modules to be lazy-loaded i.e. the modules will not start loading until they are explicitly called.Besides these two loading strategies, we have 3rd type of loading i.e. preloading strategy. Before determining which module to preload, let’s first understand what is preloading in angular.
In preloading, we explicitly tell Angular compiler which lazy loaded modules that we want to prerender first i.e. In preloading we define some modules to be preloaded as soon as the main modules finish loading to avoid the delay of the rendering of lazy loaded modules for better user experience.
There are various scenarios on which we decided which modules should be preloaded.
If the module size is too big, we generally decided to load such modules to preload because when the user calls such modules, they are either complete loading or complete partial loading so that the user doesn’t have to wait.
The modules which are frequently used in the application are also set to be preload to avoid the delay time.
So, these are some important conditions over which you can decide which lazy loaded modules should be loaded as preload.
Now, let’s understand how to implement preloading in the angular application.
There are two ways to do so first we can preload all the lazy loaded modules and second, we can define specific lazy modules to preload.
All lazy modules to load as preload (preloadingStrategy : PreloadAllModules):
AppRoute.ts:
Javascript
import { NgModule } from '@angular/core';import { Routes, RouterModule, PreloadAllModules } from '@angular/router'; const routes: Routes = [ { path: 'user', loadChildren: () => import('./user/user.module') .then(m => m.UserModule) }, { path: 'orders', loadChildren: () => import('./orders/orders.module') .then(m => m.OrdersModule) }, { path: '', redirectTo: '', pathMatch: 'full' }]; @NgModule({ imports: [ RouterModule.forRoot(routes, { prelaodingStrategy: PreloadAllModules }) ], exports: [RouterModule], providers: []})export class AppRoutingModule { } export class AppRoutingModule { }
UserComponent.ts:
Javascript
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-user', templateUrl: './user.component.html', styleUrls: ['./user.component.css']})export class UserComponent implements OnInit, OnDestroy { constructor() { } ngOnInit() { Console.log("Loading started......"); } ngOnDestroy() { } }
OrderComponent.ts:
Javascript
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-order', templateUrl: './order.component.html', styleUrls: ['./order.component.css']})export class OrderComponent implements OnInit { constructor() { } ngOnInit() { Console.log("Order Loading started......"); } }
Output: When you go to the network tab under the developer options, you will see that as soon as your bootstrap component gets loaded, all other modules both user and order also start loading, this is preloading of all the modules.
As you can see both orders and users module start loading
Specific lazy module to load as preload (data : {preload: true}):
AppRoute.ts:
Javascript
import { NgModule } from '@angular/core';import { Routes, RouterModule, PreloadAllModules } from '@angular/router'; const routes: Routes = [ { path: 'user', loadChildren: () => import('./user/user.module') .then(m => m.UserModule), data: { preload: true } }, { path: 'orders', loadChildren: () => import('./orders/orders.module') .then(m => m.OrdersModule) }, { path: '', redirectTo: '', pathMatch: 'full' }]; @NgModule({ imports: [ RouterModule.forRoot(routes) ], exports: [RouterModule], providers: []})export class AppRoutingModule { }
UserComponent.ts:
Javascript
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-user', templateUrl: './user.component.html', styleUrls: ['./user.component.css']})export class UserComponent implements OnInit, OnDestroy { constructor() { } ngOnInit() { Console.log("Loading started......"); } ngOnDestroy() { } }
OrderComponent.ts:
Javascript
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-order', templateUrl: './order.component.html', styleUrls: ['./order.component.css']})export class OrderComponent implements OnInit { constructor() { } ngOnInit() { Console.log("order Loading started......"); }}
Output: In the above example, we have set preload true for only the user component among all other lazy loaded components. Now if you go to network tab under developer option or in the below screenshot, you will see after bootstrap component gets loaded, only the user component starts loading but order Component doesn’t start loading until we go to that component explicitly. So, this is the preloading of custom component.
As you can see only the user module starts loading, the order module doesn’t.
So, in this way, we can load some or all of the lazy modules as preload.
AngularJS-Misc
Picked
Technical Scripter 2020
AngularJS
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Angular PrimeNG Dropdown Component
Angular PrimeNG Calendar Component
Angular 10 (blur) Event
Angular PrimeNG Messages Component
How to make a Bootstrap Modal Popup in Angular 9/8 ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills | [
{
"code": null,
"e": 26378,
"s": 26350,
"text": "\n23 Dec, 2020"
},
{
"code": null,
"e": 27041,
"s": 26378,
"text": "Loading strategy in angular decides how to load the app modules when the application runs into the browser. In Angular, we have three types of loading: Eager loading, lazy loading, and preloading. By default, Angular follows eager loading i.e. as soon as the application starts downloading in the browser, the modules start to load within the browser. You can also set some modules to be lazy-loaded i.e. the modules will not start loading until they are explicitly called.Besides these two loading strategies, we have 3rd type of loading i.e. preloading strategy. Before determining which module to preload, let’s first understand what is preloading in angular."
},
{
"code": null,
"e": 27338,
"s": 27041,
"text": "In preloading, we explicitly tell Angular compiler which lazy loaded modules that we want to prerender first i.e. In preloading we define some modules to be preloaded as soon as the main modules finish loading to avoid the delay of the rendering of lazy loaded modules for better user experience."
},
{
"code": null,
"e": 27421,
"s": 27338,
"text": "There are various scenarios on which we decided which modules should be preloaded."
},
{
"code": null,
"e": 27647,
"s": 27421,
"text": "If the module size is too big, we generally decided to load such modules to preload because when the user calls such modules, they are either complete loading or complete partial loading so that the user doesn’t have to wait."
},
{
"code": null,
"e": 27756,
"s": 27647,
"text": "The modules which are frequently used in the application are also set to be preload to avoid the delay time."
},
{
"code": null,
"e": 27877,
"s": 27756,
"text": "So, these are some important conditions over which you can decide which lazy loaded modules should be loaded as preload."
},
{
"code": null,
"e": 27955,
"s": 27877,
"text": "Now, let’s understand how to implement preloading in the angular application."
},
{
"code": null,
"e": 28092,
"s": 27955,
"text": "There are two ways to do so first we can preload all the lazy loaded modules and second, we can define specific lazy modules to preload."
},
{
"code": null,
"e": 28170,
"s": 28092,
"text": "All lazy modules to load as preload (preloadingStrategy : PreloadAllModules):"
},
{
"code": null,
"e": 28183,
"s": 28170,
"text": "AppRoute.ts:"
},
{
"code": null,
"e": 28194,
"s": 28183,
"text": "Javascript"
},
{
"code": "import { NgModule } from '@angular/core';import { Routes, RouterModule, PreloadAllModules } from '@angular/router'; const routes: Routes = [ { path: 'user', loadChildren: () => import('./user/user.module') .then(m => m.UserModule) }, { path: 'orders', loadChildren: () => import('./orders/orders.module') .then(m => m.OrdersModule) }, { path: '', redirectTo: '', pathMatch: 'full' }]; @NgModule({ imports: [ RouterModule.forRoot(routes, { prelaodingStrategy: PreloadAllModules }) ], exports: [RouterModule], providers: []})export class AppRoutingModule { } export class AppRoutingModule { }",
"e": 28922,
"s": 28194,
"text": null
},
{
"code": null,
"e": 28940,
"s": 28922,
"text": "UserComponent.ts:"
},
{
"code": null,
"e": 28951,
"s": 28940,
"text": "Javascript"
},
{
"code": "import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-user', templateUrl: './user.component.html', styleUrls: ['./user.component.css']})export class UserComponent implements OnInit, OnDestroy { constructor() { } ngOnInit() { Console.log(\"Loading started......\"); } ngOnDestroy() { } }",
"e": 29280,
"s": 28951,
"text": null
},
{
"code": null,
"e": 29299,
"s": 29280,
"text": "OrderComponent.ts:"
},
{
"code": null,
"e": 29310,
"s": 29299,
"text": "Javascript"
},
{
"code": "import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-order', templateUrl: './order.component.html', styleUrls: ['./order.component.css']})export class OrderComponent implements OnInit { constructor() { } ngOnInit() { Console.log(\"Order Loading started......\"); } }",
"e": 29618,
"s": 29310,
"text": null
},
{
"code": null,
"e": 29850,
"s": 29618,
"text": "Output: When you go to the network tab under the developer options, you will see that as soon as your bootstrap component gets loaded, all other modules both user and order also start loading, this is preloading of all the modules."
},
{
"code": null,
"e": 29908,
"s": 29850,
"text": "As you can see both orders and users module start loading"
},
{
"code": null,
"e": 29974,
"s": 29908,
"text": "Specific lazy module to load as preload (data : {preload: true}):"
},
{
"code": null,
"e": 29987,
"s": 29974,
"text": "AppRoute.ts:"
},
{
"code": null,
"e": 29998,
"s": 29987,
"text": "Javascript"
},
{
"code": "import { NgModule } from '@angular/core';import { Routes, RouterModule, PreloadAllModules } from '@angular/router'; const routes: Routes = [ { path: 'user', loadChildren: () => import('./user/user.module') .then(m => m.UserModule), data: { preload: true } }, { path: 'orders', loadChildren: () => import('./orders/orders.module') .then(m => m.OrdersModule) }, { path: '', redirectTo: '', pathMatch: 'full' }]; @NgModule({ imports: [ RouterModule.forRoot(routes) ], exports: [RouterModule], providers: []})export class AppRoutingModule { }",
"e": 30664,
"s": 29998,
"text": null
},
{
"code": null,
"e": 30682,
"s": 30664,
"text": "UserComponent.ts:"
},
{
"code": null,
"e": 30693,
"s": 30682,
"text": "Javascript"
},
{
"code": "import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-user', templateUrl: './user.component.html', styleUrls: ['./user.component.css']})export class UserComponent implements OnInit, OnDestroy { constructor() { } ngOnInit() { Console.log(\"Loading started......\"); } ngOnDestroy() { } }",
"e": 31022,
"s": 30693,
"text": null
},
{
"code": null,
"e": 31041,
"s": 31022,
"text": "OrderComponent.ts:"
},
{
"code": null,
"e": 31052,
"s": 31041,
"text": "Javascript"
},
{
"code": "import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-order', templateUrl: './order.component.html', styleUrls: ['./order.component.css']})export class OrderComponent implements OnInit { constructor() { } ngOnInit() { Console.log(\"order Loading started......\"); }}",
"e": 31356,
"s": 31052,
"text": null
},
{
"code": null,
"e": 31782,
"s": 31356,
"text": "Output: In the above example, we have set preload true for only the user component among all other lazy loaded components. Now if you go to network tab under developer option or in the below screenshot, you will see after bootstrap component gets loaded, only the user component starts loading but order Component doesn’t start loading until we go to that component explicitly. So, this is the preloading of custom component."
},
{
"code": null,
"e": 31860,
"s": 31782,
"text": "As you can see only the user module starts loading, the order module doesn’t."
},
{
"code": null,
"e": 31933,
"s": 31860,
"text": "So, in this way, we can load some or all of the lazy modules as preload."
},
{
"code": null,
"e": 31948,
"s": 31933,
"text": "AngularJS-Misc"
},
{
"code": null,
"e": 31955,
"s": 31948,
"text": "Picked"
},
{
"code": null,
"e": 31979,
"s": 31955,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 31989,
"s": 31979,
"text": "AngularJS"
},
{
"code": null,
"e": 32008,
"s": 31989,
"text": "Technical Scripter"
},
{
"code": null,
"e": 32025,
"s": 32008,
"text": "Web Technologies"
},
{
"code": null,
"e": 32123,
"s": 32025,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32158,
"s": 32123,
"text": "Angular PrimeNG Dropdown Component"
},
{
"code": null,
"e": 32193,
"s": 32158,
"text": "Angular PrimeNG Calendar Component"
},
{
"code": null,
"e": 32217,
"s": 32193,
"text": "Angular 10 (blur) Event"
},
{
"code": null,
"e": 32252,
"s": 32217,
"text": "Angular PrimeNG Messages Component"
},
{
"code": null,
"e": 32305,
"s": 32252,
"text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?"
},
{
"code": null,
"e": 32345,
"s": 32305,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 32378,
"s": 32345,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 32423,
"s": 32378,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 32466,
"s": 32423,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
How to concatenate unicode and variable in ReactJS ? - GeeksforGeeks | 12 Apr, 2021
Unicode: Unicode is an encoding standard for all characters in the universe. Every language code and symbol in this world is assigned by Unicode. There is no encoding standard that supports all languages, By using Unicode standard, we can retrieve and combine data with all language combinations.
Example:
U+2192
In the above example, a right-facing arrow is represented in Unicode by U+2192.
How to create React Application:
Step 1: Create a React application using the following command. npx create-react-app geeksforgeeks
Step 1: Create a React application using the following command.
npx create-react-app geeksforgeeks
Step 2: After creating your project folder i.e. geeksforgeeks, move to it using the following command.cd geeksforgeeksProject Structure:Folder structureHow to concatenate Unicode and variable in ReactJS: To concatenate we first convert Unicode into its numerical value and for that, we will use parseInt.parseInt(Unicode,base)Now, this numerical value needs to be converted into its character and for that, we can useString.fromCodePoint(numericalValue).Example: Make the following changes to your App.js fileApp.jsApp.jsimport React from 'react' const App = ({ unicode }) => { return( <h1> This is a Right arrow {String.fromCodePoint(parseInt(unicode,16))} </h1> )}export default App;Now import this App.js file in your index.js file(by default it is already being imported) and pass the value of Unicode in the App component.index.jsindex.jsimport React from 'react';import ReactDOM from 'react-dom';import App from './App'; ReactDOM.render( <React.StrictMode> <App unicode='2192'/> </React.StrictMode>, document.getElementById('root') );Now run the local server using the following command within the react-app directory npm startOutput:My Personal Notes
arrow_drop_upSave
Step 2: After creating your project folder i.e. geeksforgeeks, move to it using the following command.
cd geeksforgeeks
Project Structure:
Folder structure
How to concatenate Unicode and variable in ReactJS: To concatenate we first convert Unicode into its numerical value and for that, we will use parseInt.
parseInt(Unicode,base)
Now, this numerical value needs to be converted into its character and for that, we can use
String.fromCodePoint(numericalValue).
Example: Make the following changes to your App.js file
App.js
import React from 'react' const App = ({ unicode }) => { return( <h1> This is a Right arrow {String.fromCodePoint(parseInt(unicode,16))} </h1> )}export default App;
Now import this App.js file in your index.js file(by default it is already being imported) and pass the value of Unicode in the App component.
index.js
import React from 'react';import ReactDOM from 'react-dom';import App from './App'; ReactDOM.render( <React.StrictMode> <App unicode='2192'/> </React.StrictMode>, document.getElementById('root') );
Now run the local server using the following command within the react-app directory
npm start
Output:
Picked
React-Questions
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ReactJS useNavigate() Hook
How to set background images in ReactJS ?
Axios in React: A Guide for Beginners
How to create a table in ReactJS ?
How to navigate on path by button click in react router ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript | [
{
"code": null,
"e": 26095,
"s": 26067,
"text": "\n12 Apr, 2021"
},
{
"code": null,
"e": 26392,
"s": 26095,
"text": "Unicode: Unicode is an encoding standard for all characters in the universe. Every language code and symbol in this world is assigned by Unicode. There is no encoding standard that supports all languages, By using Unicode standard, we can retrieve and combine data with all language combinations."
},
{
"code": null,
"e": 26402,
"s": 26392,
"text": "Example: "
},
{
"code": null,
"e": 26409,
"s": 26402,
"text": "U+2192"
},
{
"code": null,
"e": 26489,
"s": 26409,
"text": "In the above example, a right-facing arrow is represented in Unicode by U+2192."
},
{
"code": null,
"e": 26522,
"s": 26489,
"text": "How to create React Application:"
},
{
"code": null,
"e": 26621,
"s": 26522,
"text": "Step 1: Create a React application using the following command. npx create-react-app geeksforgeeks"
},
{
"code": null,
"e": 26685,
"s": 26621,
"text": "Step 1: Create a React application using the following command."
},
{
"code": null,
"e": 26721,
"s": 26685,
"text": " npx create-react-app geeksforgeeks"
},
{
"code": null,
"e": 27968,
"s": 26721,
"text": "Step 2: After creating your project folder i.e. geeksforgeeks, move to it using the following command.cd geeksforgeeksProject Structure:Folder structureHow to concatenate Unicode and variable in ReactJS: To concatenate we first convert Unicode into its numerical value and for that, we will use parseInt.parseInt(Unicode,base)Now, this numerical value needs to be converted into its character and for that, we can useString.fromCodePoint(numericalValue).Example: Make the following changes to your App.js fileApp.jsApp.jsimport React from 'react' const App = ({ unicode }) => { return( <h1> This is a Right arrow {String.fromCodePoint(parseInt(unicode,16))} </h1> )}export default App;Now import this App.js file in your index.js file(by default it is already being imported) and pass the value of Unicode in the App component.index.jsindex.jsimport React from 'react';import ReactDOM from 'react-dom';import App from './App'; ReactDOM.render( <React.StrictMode> <App unicode='2192'/> </React.StrictMode>, document.getElementById('root') );Now run the local server using the following command within the react-app directory npm startOutput:My Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 28071,
"s": 27968,
"text": "Step 2: After creating your project folder i.e. geeksforgeeks, move to it using the following command."
},
{
"code": null,
"e": 28088,
"s": 28071,
"text": "cd geeksforgeeks"
},
{
"code": null,
"e": 28107,
"s": 28088,
"text": "Project Structure:"
},
{
"code": null,
"e": 28124,
"s": 28107,
"text": "Folder structure"
},
{
"code": null,
"e": 28277,
"s": 28124,
"text": "How to concatenate Unicode and variable in ReactJS: To concatenate we first convert Unicode into its numerical value and for that, we will use parseInt."
},
{
"code": null,
"e": 28300,
"s": 28277,
"text": "parseInt(Unicode,base)"
},
{
"code": null,
"e": 28392,
"s": 28300,
"text": "Now, this numerical value needs to be converted into its character and for that, we can use"
},
{
"code": null,
"e": 28430,
"s": 28392,
"text": "String.fromCodePoint(numericalValue)."
},
{
"code": null,
"e": 28486,
"s": 28430,
"text": "Example: Make the following changes to your App.js file"
},
{
"code": null,
"e": 28493,
"s": 28486,
"text": "App.js"
},
{
"code": "import React from 'react' const App = ({ unicode }) => { return( <h1> This is a Right arrow {String.fromCodePoint(parseInt(unicode,16))} </h1> )}export default App;",
"e": 28702,
"s": 28493,
"text": null
},
{
"code": null,
"e": 28845,
"s": 28702,
"text": "Now import this App.js file in your index.js file(by default it is already being imported) and pass the value of Unicode in the App component."
},
{
"code": null,
"e": 28854,
"s": 28845,
"text": "index.js"
},
{
"code": "import React from 'react';import ReactDOM from 'react-dom';import App from './App'; ReactDOM.render( <React.StrictMode> <App unicode='2192'/> </React.StrictMode>, document.getElementById('root') );",
"e": 29078,
"s": 28854,
"text": null
},
{
"code": null,
"e": 29164,
"s": 29078,
"text": "Now run the local server using the following command within the react-app directory "
},
{
"code": null,
"e": 29174,
"s": 29164,
"text": "npm start"
},
{
"code": null,
"e": 29182,
"s": 29174,
"text": "Output:"
},
{
"code": null,
"e": 29189,
"s": 29182,
"text": "Picked"
},
{
"code": null,
"e": 29205,
"s": 29189,
"text": "React-Questions"
},
{
"code": null,
"e": 29213,
"s": 29205,
"text": "ReactJS"
},
{
"code": null,
"e": 29230,
"s": 29213,
"text": "Web Technologies"
},
{
"code": null,
"e": 29328,
"s": 29230,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29355,
"s": 29328,
"text": "ReactJS useNavigate() Hook"
},
{
"code": null,
"e": 29397,
"s": 29355,
"text": "How to set background images in ReactJS ?"
},
{
"code": null,
"e": 29435,
"s": 29397,
"text": "Axios in React: A Guide for Beginners"
},
{
"code": null,
"e": 29470,
"s": 29435,
"text": "How to create a table in ReactJS ?"
},
{
"code": null,
"e": 29528,
"s": 29470,
"text": "How to navigate on path by button click in react router ?"
},
{
"code": null,
"e": 29568,
"s": 29528,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29601,
"s": 29568,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 29646,
"s": 29601,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29696,
"s": 29646,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Print first n numbers with exactly two set bits - GeeksforGeeks | 03 Nov, 2021
Given a number n, print first n positive integers with exactly two set bits in their binary representation.Examples :
Input: n = 3
Output: 3 5 6
The first 3 numbers with two set bits are 3 (0011),
5 (0101) and 6 (0110)
Input: n = 5
Output: 3 5 6 9 10 12
A Simple Solution is to consider all positive integers one by one starting from 1. For every number, check if it has exactly two sets bits. If a number has exactly two set bits, print it and increment count of such numbers.An Efficient Solution is to directly generate such numbers. If we clearly observe the numbers, we can rewrite them as given below pow(2,1)+pow(2,0), pow(2,2)+pow(2,0), pow(2,2)+pow(2,1), pow(2,3)+pow(2,0), pow(2,3)+pow(2,1), pow(2,3)+pow(2,2), .........All numbers can be generated in increasing order according to higher of two set bits. The idea is to fix higher of two bits one by one. For current higher set bit, consider all lower bits and print the formed numbers.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to print first n numbers// with exactly two set bits#include <iostream>using namespace std; // Prints first n numbers with two set bitsvoid printTwoSetBitNums(int n){ // Initialize higher of two sets bits int x = 1; // Keep reducing n for every number // with two set bits. while (n > 0) { // Consider all lower set bits for // current higher set bit int y = 0; while (y < x) { // Print current number cout << (1 << x) + (1 << y) << " "; // If we have found n numbers n--; if (n == 0) return; // Consider next lower bit for current // higher bit. y++; } // Increment higher set bit x++; }} // Driver codeint main(){ printTwoSetBitNums(4); return 0;}
// Java program to print first n numbers// with exactly two set bitsimport java.io.*; class GFG{ // Function to print first n numbers with two set bits static void printTwoSetBitNums(int n) { // Initialize higher of two sets bits int x = 1; // Keep reducing n for every number // with two set bits while (n > 0) { // Consider all lower set bits for // current higher set bit int y = 0; while (y < x) { // Print current number System.out.print(((1 << x) + (1 << y)) +" "); // If we have found n numbers n--; if (n == 0) return; // Consider next lower bit for current // higher bit. y++; } // Increment higher set bit x++; } } // Driver program public static void main (String[] args) { int n = 4; printTwoSetBitNums(n); }} // This code is contributed by Pramod Kumar
# Python3 program to print first n# numbers with exactly two set bits # Prints first n numbers# with two set bitsdef printTwoSetBitNums(n) : # Initialize higher of # two sets bits x = 1 # Keep reducing n for every # number with two set bits. while (n > 0) : # Consider all lower set bits # for current higher set bit y = 0 while (y < x) : # Print current number print((1 << x) + (1 << y), end = " " ) # If we have found n numbers n -= 1 if (n == 0) : return # Consider next lower bit # for current higher bit. y += 1 # Increment higher set bit x += 1 # Driver codeprintTwoSetBitNums(4) # This code is contributed# by Smitha
// C# program to print first n numbers// with exactly two set bitsusing System; class GFG { // Function to print first n // numbers with two set bits static void printTwoSetBitNums(int n) { // Initialize higher of // two sets bits int x = 1; // Keep reducing n for every // number with two set bits while (n > 0) { // Consider all lower set bits // for current higher set bit int y = 0; while (y < x) { // Print current number Console.Write(((1 << x) + (1 << y)) +" "); // If we have found n numbers n--; if (n == 0) return; // Consider next lower bit // for current higher bit. y++; } // Increment higher set bit x++; } } // Driver program public static void Main() { int n = 4; printTwoSetBitNums(n); }} // This code is contributed by Anant Agarwal.
<?php// PHP program to print// first n numbers with// exactly two set bits // Prints first n numbers// with two set bitsfunction printTwoSetBitNums($n){ // Initialize higher of // two sets bits $x = 1; // Keep reducing n for // every number with // two set bits. while ($n > 0) { // Consider all lower set // bits for current higher // set bit $y = 0; while ($y < $x) { // Print current number echo (1 << $x) + (1 << $y), " "; // If we have found n numbers $n--; if ($n == 0) return; // Consider next lower // bit for current // higher bit. $y++; } // Increment higher set bit $x++; }} // Driver codeprintTwoSetBitNums(4); // This code is contributed by Ajit?>
<script> // Javascript program to print first n numbers// with exactly two set bits // Prints first n numbers with two set bitsfunction printTwoSetBitNums(n){ // Initialize higher of two sets bits let x = 1; // Keep reducing n for every number // with two set bits. while (n > 0) { // Consider all lower set bits for // current higher set bit let y = 0; while (y < x) { // Print current number document.write((1 << x) + (1 << y) + " "); // If we have found n numbers n--; if (n == 0) return; // Consider next lower bit for current // higher bit. y++; } // Increment higher set bit x++; }} // Driver codeprintTwoSetBitNums(4); // This code is contributed by Mayank Tyagi</script>
Output :
3 5 6 9
Time Complexity : O(n)
Auxiliary Space: O(1)This article is contributed by Bharath Reddy Appareddy. 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
Smitha Dinesh Semwal
mayanktyagi1709
subhammahato348
Bit Magic
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Set, Clear and Toggle a given bit of a number in C
Write an Efficient Method to Check if a Number is Multiple of 3
Swap two nibbles in a byte
Highest power of 2 less than or equal to given number
Swap bits in a given number
Check for Integer Overflow
Reverse actual bits of the given number
Find one extra character in a string
Bit Tricks for Competitive Programming
Count total bits in a number | [
{
"code": null,
"e": 26279,
"s": 26251,
"text": "\n03 Nov, 2021"
},
{
"code": null,
"e": 26399,
"s": 26279,
"text": "Given a number n, print first n positive integers with exactly two set bits in their binary representation.Examples : "
},
{
"code": null,
"e": 26536,
"s": 26399,
"text": "Input: n = 3\nOutput: 3 5 6\nThe first 3 numbers with two set bits are 3 (0011),\n5 (0101) and 6 (0110)\n\nInput: n = 5\nOutput: 3 5 6 9 10 12"
},
{
"code": null,
"e": 27233,
"s": 26538,
"text": "A Simple Solution is to consider all positive integers one by one starting from 1. For every number, check if it has exactly two sets bits. If a number has exactly two set bits, print it and increment count of such numbers.An Efficient Solution is to directly generate such numbers. If we clearly observe the numbers, we can rewrite them as given below pow(2,1)+pow(2,0), pow(2,2)+pow(2,0), pow(2,2)+pow(2,1), pow(2,3)+pow(2,0), pow(2,3)+pow(2,1), pow(2,3)+pow(2,2), .........All numbers can be generated in increasing order according to higher of two set bits. The idea is to fix higher of two bits one by one. For current higher set bit, consider all lower bits and print the formed numbers. "
},
{
"code": null,
"e": 27237,
"s": 27233,
"text": "C++"
},
{
"code": null,
"e": 27242,
"s": 27237,
"text": "Java"
},
{
"code": null,
"e": 27250,
"s": 27242,
"text": "Python3"
},
{
"code": null,
"e": 27253,
"s": 27250,
"text": "C#"
},
{
"code": null,
"e": 27257,
"s": 27253,
"text": "PHP"
},
{
"code": null,
"e": 27268,
"s": 27257,
"text": "Javascript"
},
{
"code": "// C++ program to print first n numbers// with exactly two set bits#include <iostream>using namespace std; // Prints first n numbers with two set bitsvoid printTwoSetBitNums(int n){ // Initialize higher of two sets bits int x = 1; // Keep reducing n for every number // with two set bits. while (n > 0) { // Consider all lower set bits for // current higher set bit int y = 0; while (y < x) { // Print current number cout << (1 << x) + (1 << y) << \" \"; // If we have found n numbers n--; if (n == 0) return; // Consider next lower bit for current // higher bit. y++; } // Increment higher set bit x++; }} // Driver codeint main(){ printTwoSetBitNums(4); return 0;}",
"e": 28124,
"s": 27268,
"text": null
},
{
"code": "// Java program to print first n numbers// with exactly two set bitsimport java.io.*; class GFG{ // Function to print first n numbers with two set bits static void printTwoSetBitNums(int n) { // Initialize higher of two sets bits int x = 1; // Keep reducing n for every number // with two set bits while (n > 0) { // Consider all lower set bits for // current higher set bit int y = 0; while (y < x) { // Print current number System.out.print(((1 << x) + (1 << y)) +\" \"); // If we have found n numbers n--; if (n == 0) return; // Consider next lower bit for current // higher bit. y++; } // Increment higher set bit x++; } } // Driver program public static void main (String[] args) { int n = 4; printTwoSetBitNums(n); }} // This code is contributed by Pramod Kumar",
"e": 29217,
"s": 28124,
"text": null
},
{
"code": "# Python3 program to print first n# numbers with exactly two set bits # Prints first n numbers# with two set bitsdef printTwoSetBitNums(n) : # Initialize higher of # two sets bits x = 1 # Keep reducing n for every # number with two set bits. while (n > 0) : # Consider all lower set bits # for current higher set bit y = 0 while (y < x) : # Print current number print((1 << x) + (1 << y), end = \" \" ) # If we have found n numbers n -= 1 if (n == 0) : return # Consider next lower bit # for current higher bit. y += 1 # Increment higher set bit x += 1 # Driver codeprintTwoSetBitNums(4) # This code is contributed# by Smitha",
"e": 30060,
"s": 29217,
"text": null
},
{
"code": "// C# program to print first n numbers// with exactly two set bitsusing System; class GFG { // Function to print first n // numbers with two set bits static void printTwoSetBitNums(int n) { // Initialize higher of // two sets bits int x = 1; // Keep reducing n for every // number with two set bits while (n > 0) { // Consider all lower set bits // for current higher set bit int y = 0; while (y < x) { // Print current number Console.Write(((1 << x) + (1 << y)) +\" \"); // If we have found n numbers n--; if (n == 0) return; // Consider next lower bit // for current higher bit. y++; } // Increment higher set bit x++; } } // Driver program public static void Main() { int n = 4; printTwoSetBitNums(n); }} // This code is contributed by Anant Agarwal.",
"e": 31237,
"s": 30060,
"text": null
},
{
"code": "<?php// PHP program to print// first n numbers with// exactly two set bits // Prints first n numbers// with two set bitsfunction printTwoSetBitNums($n){ // Initialize higher of // two sets bits $x = 1; // Keep reducing n for // every number with // two set bits. while ($n > 0) { // Consider all lower set // bits for current higher // set bit $y = 0; while ($y < $x) { // Print current number echo (1 << $x) + (1 << $y), \" \"; // If we have found n numbers $n--; if ($n == 0) return; // Consider next lower // bit for current // higher bit. $y++; } // Increment higher set bit $x++; }} // Driver codeprintTwoSetBitNums(4); // This code is contributed by Ajit?>",
"e": 32106,
"s": 31237,
"text": null
},
{
"code": "<script> // Javascript program to print first n numbers// with exactly two set bits // Prints first n numbers with two set bitsfunction printTwoSetBitNums(n){ // Initialize higher of two sets bits let x = 1; // Keep reducing n for every number // with two set bits. while (n > 0) { // Consider all lower set bits for // current higher set bit let y = 0; while (y < x) { // Print current number document.write((1 << x) + (1 << y) + \" \"); // If we have found n numbers n--; if (n == 0) return; // Consider next lower bit for current // higher bit. y++; } // Increment higher set bit x++; }} // Driver codeprintTwoSetBitNums(4); // This code is contributed by Mayank Tyagi</script>",
"e": 32984,
"s": 32106,
"text": null
},
{
"code": null,
"e": 32995,
"s": 32984,
"text": "Output : "
},
{
"code": null,
"e": 33003,
"s": 32995,
"text": "3 5 6 9"
},
{
"code": null,
"e": 33026,
"s": 33003,
"text": "Time Complexity : O(n)"
},
{
"code": null,
"e": 33479,
"s": 33026,
"text": "Auxiliary Space: O(1)This article is contributed by Bharath Reddy Appareddy. 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": 33485,
"s": 33479,
"text": "jit_t"
},
{
"code": null,
"e": 33506,
"s": 33485,
"text": "Smitha Dinesh Semwal"
},
{
"code": null,
"e": 33522,
"s": 33506,
"text": "mayanktyagi1709"
},
{
"code": null,
"e": 33538,
"s": 33522,
"text": "subhammahato348"
},
{
"code": null,
"e": 33548,
"s": 33538,
"text": "Bit Magic"
},
{
"code": null,
"e": 33558,
"s": 33548,
"text": "Bit Magic"
},
{
"code": null,
"e": 33656,
"s": 33558,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33707,
"s": 33656,
"text": "Set, Clear and Toggle a given bit of a number in C"
},
{
"code": null,
"e": 33771,
"s": 33707,
"text": "Write an Efficient Method to Check if a Number is Multiple of 3"
},
{
"code": null,
"e": 33798,
"s": 33771,
"text": "Swap two nibbles in a byte"
},
{
"code": null,
"e": 33852,
"s": 33798,
"text": "Highest power of 2 less than or equal to given number"
},
{
"code": null,
"e": 33880,
"s": 33852,
"text": "Swap bits in a given number"
},
{
"code": null,
"e": 33907,
"s": 33880,
"text": "Check for Integer Overflow"
},
{
"code": null,
"e": 33947,
"s": 33907,
"text": "Reverse actual bits of the given number"
},
{
"code": null,
"e": 33984,
"s": 33947,
"text": "Find one extra character in a string"
},
{
"code": null,
"e": 34023,
"s": 33984,
"text": "Bit Tricks for Competitive Programming"
}
] |
JQuery | now() method - GeeksforGeeks | 27 Apr, 2020
This now() Method in jQuery is used to return a number representing the current time.
Syntax:
jQuery.now()
Parameters: The now() method does not accept any parameter.
Return Value: It returns the number representing the current time.
Example 1: In this example, the now() Method a display the number of milliseconds with innerHTML function.
<!DOCTYPE html><html><head><meta charset="utf-8"><title>JQuery | now() method</title> <script src="https://code.jquery.com/jquery-3.4.1.js"></script> </head><body style="text-align:center;"> <h1 style="color: green"> GeeksForGeeks </h1> <h3>JQuery | now() method</h3> <button onclick="geek()">Try it</button> <p id="demo"></p> <script> function geek() { var n = jQuery.now(); document.getElementById("demo").innerHTML = n/3600; } </script></body></html>
Output:Before Click:After Click:
Example 2: In this example, the now() Method a display the number of milliseconds with alertfunction.
<!DOCTYPE html><html><head><meta charset="utf-8"><title>JQuery | now() method</title> <script src="https://code.jquery.com/jquery-3.4.1.js"></script> </head><body style="text-align:center;"> <h1 style="color: green"> GeeksForGeeks </h1> <h3>JQuery | now() method</h3> <button onclick="geek()">Try it</button> <script> function geek() { var n = jQuery.now(); alert("Number of milliseconds : " + n); } </script></body></html>
Output:Before Click:After Click:
jQuery-Methods
JQuery
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Show and Hide div elements using radio buttons?
How to prevent Body from scrolling when a modal is opened using jQuery ?
jQuery | ajax() Method
jQuery | removeAttr() with Examples
How to get the value in an input text box using jQuery ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 26954,
"s": 26926,
"text": "\n27 Apr, 2020"
},
{
"code": null,
"e": 27040,
"s": 26954,
"text": "This now() Method in jQuery is used to return a number representing the current time."
},
{
"code": null,
"e": 27048,
"s": 27040,
"text": "Syntax:"
},
{
"code": null,
"e": 27062,
"s": 27048,
"text": "jQuery.now()\n"
},
{
"code": null,
"e": 27122,
"s": 27062,
"text": "Parameters: The now() method does not accept any parameter."
},
{
"code": null,
"e": 27189,
"s": 27122,
"text": "Return Value: It returns the number representing the current time."
},
{
"code": null,
"e": 27296,
"s": 27189,
"text": "Example 1: In this example, the now() Method a display the number of milliseconds with innerHTML function."
},
{
"code": "<!DOCTYPE html><html><head><meta charset=\"utf-8\"><title>JQuery | now() method</title> <script src=\"https://code.jquery.com/jquery-3.4.1.js\"></script> </head><body style=\"text-align:center;\"> <h1 style=\"color: green\"> GeeksForGeeks </h1> <h3>JQuery | now() method</h3> <button onclick=\"geek()\">Try it</button> <p id=\"demo\"></p> <script> function geek() { var n = jQuery.now(); document.getElementById(\"demo\").innerHTML = n/3600; } </script></body></html> ",
"e": 27911,
"s": 27296,
"text": null
},
{
"code": null,
"e": 27944,
"s": 27911,
"text": "Output:Before Click:After Click:"
},
{
"code": null,
"e": 28046,
"s": 27944,
"text": "Example 2: In this example, the now() Method a display the number of milliseconds with alertfunction."
},
{
"code": "<!DOCTYPE html><html><head><meta charset=\"utf-8\"><title>JQuery | now() method</title> <script src=\"https://code.jquery.com/jquery-3.4.1.js\"></script> </head><body style=\"text-align:center;\"> <h1 style=\"color: green\"> GeeksForGeeks </h1> <h3>JQuery | now() method</h3> <button onclick=\"geek()\">Try it</button> <script> function geek() { var n = jQuery.now(); alert(\"Number of milliseconds : \" + n); } </script></body></html> ",
"e": 28574,
"s": 28046,
"text": null
},
{
"code": null,
"e": 28607,
"s": 28574,
"text": "Output:Before Click:After Click:"
},
{
"code": null,
"e": 28622,
"s": 28607,
"text": "jQuery-Methods"
},
{
"code": null,
"e": 28629,
"s": 28622,
"text": "JQuery"
},
{
"code": null,
"e": 28646,
"s": 28629,
"text": "Web Technologies"
},
{
"code": null,
"e": 28744,
"s": 28646,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28799,
"s": 28744,
"text": "How to Show and Hide div elements using radio buttons?"
},
{
"code": null,
"e": 28872,
"s": 28799,
"text": "How to prevent Body from scrolling when a modal is opened using jQuery ?"
},
{
"code": null,
"e": 28895,
"s": 28872,
"text": "jQuery | ajax() Method"
},
{
"code": null,
"e": 28931,
"s": 28895,
"text": "jQuery | removeAttr() with Examples"
},
{
"code": null,
"e": 28988,
"s": 28931,
"text": "How to get the value in an input text box using jQuery ?"
},
{
"code": null,
"e": 29028,
"s": 28988,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29061,
"s": 29028,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 29106,
"s": 29061,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29149,
"s": 29106,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Count pairs in an array whose absolute difference is divisible by K - GeeksforGeeks | 24 Feb, 2022
Given an array arr[] and a positive integer K. The task is to count the total number of pairs in the array whose absolute difference is divisible by K.
Examples:
Input: arr[] = {1, 2, 3, 4}, K = 2 Output: 2 Explanation: Total 2 pairs exists in the array with absolute difference divisible by 2. The pairs are: (1, 3), (2, 4).
Input: arr[] = {3, 3, 3}, K = 3 Output: 3 Explanation: Total 3 pairs exists in this array with absolute difference divisible by 3. The pairs are: (3, 3), (3, 3), (3, 3).
Naive Approach: The idea is to check for each pair of the array one by one and count the total number pairs whose absolute difference is divisible by K.
C++
Java
Python3
C#
Javascript
#include <bits/stdc++.h>using namespace std; // function to count pairs in an array// whose absolute difference is// divisible by kvoid countPairs(int arr[], int n, int k){ // initialize count as zero. int i, j, cnt = 0; // loop to count the valid pair for (i = 0; i < n - 1; i++) { for (j = i + 1; j < n; j++) { if ((arr[i] - arr[j] + k) % k == 0) cnt += 1; } } cout << cnt << endl;} // Driver codeint main(){ // input array int arr[] = {3, 3, 3}; int k = 3; // calculate the size of array int n = sizeof(arr) / sizeof(arr[0]); // function to count the valid pair countPairs(arr, n, k); return 0;}
import java.util.*; class GFG{ // function to count pairs in an array// whose absolute difference is// divisible by kstatic void countPairs(int arr[], int n, int k){ // initialize count as zero. int i, j, cnt = 0; // loop to count the valid pair for (i = 0; i < n - 1; i++) { for (j = i + 1; j < n; j++) { if ((arr[i] - arr[j] + k) % k == 0) cnt += 1; } } System.out.print(cnt +"\n");} // Driver codepublic static void main(String[] args){ // input array int arr[] = {3, 3, 3}; int k = 3; // calculate the size of array int n = arr.length; // function to count the valid pair countPairs(arr, n, k);}} // This code is contributed by 29AjayKumar
# Python3 Code implementation of the above approach # function to count pairs in an array# whose absolute difference is# divisible by kdef countPairs(arr, n, k) : # initialize count as zero. cnt = 0; # loop to count the valid pair for i in range(n - 1) : for j in range(i + 1, n) : if ((arr[i] - arr[j] + k) % k == 0) : cnt += 1; print(cnt) ; # Driver codeif __name__ == "__main__" : # input array arr = [3, 3, 3]; k = 3; # calculate the size of array n = len(arr); # function to count the valid pair countPairs(arr, n, k); # This code is contributed by AnkitRai01
using System; class GFG{ // function to count pairs in an array// whose absolute difference is// divisible by kstatic void countPairs(int []arr, int n, int k){ // initialize count as zero. int i, j, cnt = 0; // loop to count the valid pair for (i = 0; i < n - 1; i++) { for (j = i + 1; j < n; j++) { if ((arr[i] - arr[j] + k) % k == 0) cnt += 1; } } Console.Write(cnt +"\n");} // Driver codepublic static void Main(String[] args){ // input array int []arr = {3, 3, 3}; int k = 3; // calculate the size of array int n = arr.Length; // function to count the valid pair countPairs(arr, n, k);}} // This code is contributed by 29AjayKumar
<script> // Function to count pairs in an array// whose absolute difference is// divisible by kfunction countPairs(arr, n, k){ // Initialize count as zero. var i, j, cnt = 0; // Loop to count the valid pair for(i = 0; i < n - 1; i++) { for(j = i + 1; j < n; j++) { if ((arr[i] - arr[j] + k) % k == 0) cnt += 1; } } document.write(cnt + "\n");} // Driver code // Input arrayvar arr = [ 3, 3, 3 ];var k = 3; // Calculate the size of arrayvar n = arr.length; // Function to count the valid paircountPairs(arr, n, k); // This code is contributed by umadevi9616 </script>
3
Time Complexity: O(N2) Space Complexity:O(1)
Efficient Approach:
Algorithm:
Convert each elements (A[i]) of the array to ((A[i]+K)%K)Use hashing teching technique to store the number of times (A[i]%K) occurs in the arrayNow, if an element A[i] occurs x times in the array then add x*(x-1)/2 (choosing any 2 elements out of x elements ) in the count pair where 1<=i<=n .This is because value of each elements of the array lies between 0 to K-1 so the absolute difference is divisible only if value of both the elements of a pair are equal
Convert each elements (A[i]) of the array to ((A[i]+K)%K)
Use hashing teching technique to store the number of times (A[i]%K) occurs in the array
Now, if an element A[i] occurs x times in the array then add x*(x-1)/2 (choosing any 2 elements out of x elements ) in the count pair where 1<=i<=n .This is because value of each elements of the array lies between 0 to K-1 so the absolute difference is divisible only if value of both the elements of a pair are equal
C++
Java
Python3
C#
Javascript
// Write CPP code here#include <bits/stdc++.h>using namespace std; // function to Count pairs in an array whose// absolute difference is divisible by kvoid countPair(int arr[], int n, int k){ // initialize the count int cnt = 0; // making every element of arr in // range 0 to k - 1 for (int i = 0; i < n; i++) { arr[i] = (arr[i] + k) % k; } // create an array hash[] int hash[k] = { 0 }; // store to count of element of arr // in hash[] for (int i = 0; i < n; i++) { hash[arr[i]]++; } // count the pair whose absolute // difference is divisible by k for (int i = 0; i < k; i++) { cnt += (hash[i] * (hash[i] - 1)) / 2; } // print the value of count cout << cnt << endl;} // Driver Codeint main(){ // input array int arr[] = {1, 2, 3, 4}; int k = 2; // calculate the size of array int n = sizeof(arr) / sizeof(arr[0]); countPair(arr, n, k); return 0;}
// JAVA Implementation of above approachimport java.util.*; class GFG{ // function to Count pairs in an array whose// absolute difference is divisible by kstatic void countPair(int arr[], int n, int k){ // initialize the count int cnt = 0; // making every element of arr in // range 0 to k - 1 for (int i = 0; i < n; i++) { arr[i] = (arr[i] + k) % k; } // create an array hash[] int hash[] = new int[k]; // store to count of element of arr // in hash[] for (int i = 0; i < n; i++) { hash[arr[i]]++; } // count the pair whose absolute // difference is divisible by k for (int i = 0; i < k; i++) { cnt += (hash[i] * (hash[i] - 1)) / 2; } // print the value of count System.out.print(cnt +"\n");} // Driver Codepublic static void main(String[] args){ // input array int arr[] = {1, 2, 3, 4}; int k = 2; // calculate the size of array int n = arr.length; countPair(arr, n, k);}} // This code is contributed by PrinciRaj1992
# Python3 Implementation of above approach # function to Count pairs in an array whose# absolute difference is divisible by kdef countPair(arr, n, k): # initialize the count cnt = 0; # making every element of arr in # range 0 to k - 1 for i in range(n): arr[i] = (arr[i] + k) % k; # create an array hash hash = [0]*k; # store to count of element of arr # in hash for i in range(n): hash[arr[i]] += 1; # count the pair whose absolute # difference is divisible by k for i in range(k): cnt += (hash[i] * (hash[i] - 1)) / 2; # print value of count print(int(cnt)); # Driver Codeif __name__ == '__main__': # input array arr = [1, 2, 3, 4]; k = 2; # calculate the size of array n = len(arr); countPair(arr, n, k); # This code is contributed by 29AjayKumar
// C# Implementation of above approachusing System; class GFG{ // function to Count pairs in an array whose// absolute difference is divisible by kstatic void countPair(int []arr, int n, int k){ // initialize the count int cnt = 0; // making every element of arr in // range 0 to k - 1 for (int i = 0; i < n; i++) { arr[i] = (arr[i] + k) % k; } // create an array hash[] int []hash = new int[k]; // store to count of element of arr // in hash[] for (int i = 0; i < n; i++) { hash[arr[i]]++; } // count the pair whose absolute // difference is divisible by k for (int i = 0; i < k; i++) { cnt += (hash[i] * (hash[i] - 1)) / 2; } // print the value of count Console.Write(cnt +"\n");} // Driver Codepublic static void Main(String[] args){ // input array int []arr = {1, 2, 3, 4}; int k = 2; // calculate the size of array int n = arr.Length; countPair(arr, n, k);}} // This code is contributed by 29AjayKumar
<script> // Javascript Implementation of above approach // function to Count pairs in an array whose// absolute difference is divisible by kfunction countPair(arr, n, k){ // let initialize the count let cnt = 0; // making every element of arr in // range 0 to k - 1 for (let i = 0; i < n; i++) { arr[i] = (arr[i] + k) % k; } // create an array hash[] let hash = Array.from({length: k}, (_, i) => 0); // store to count of element of arr // in hash[] for (let i = 0; i < n; i++) { hash[arr[i]]++; } // count the pair whose absolute // difference is divisible by k for (let i = 0; i < k; i++) { cnt += (hash[i] * (hash[i] - 1)) / 2; } // print the value of count document.write(cnt +"<br/>");} // Driver code // input array let arr = [1, 2, 3, 4]; let k = 2; // calculate the size of array let n = arr.length; countPair(arr, n, k); </script>
2
Time Complexity: O(n+k) Auxiliary Space: O(k)
29AjayKumar
princiraj1992
ankthon
umadevi9616
susmitakundugoaldanga
arorakashish0911
simmytarika5
khushboogoyal499
simranarora5sos
Technical Scripter 2019
Arrays
Hash
Arrays
Hash
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Chocolate Distribution Problem
Count pairs with given sum
Window Sliding Technique
Reversal algorithm for array rotation
Next Greater Element
Internal Working of HashMap in Java
Count pairs with given sum
Hashing | Set 1 (Introduction)
Hashing | Set 3 (Open Addressing)
Hashing | Set 2 (Separate Chaining) | [
{
"code": null,
"e": 26067,
"s": 26039,
"text": "\n24 Feb, 2022"
},
{
"code": null,
"e": 26220,
"s": 26067,
"text": "Given an array arr[] and a positive integer K. The task is to count the total number of pairs in the array whose absolute difference is divisible by K. "
},
{
"code": null,
"e": 26231,
"s": 26220,
"text": "Examples: "
},
{
"code": null,
"e": 26395,
"s": 26231,
"text": "Input: arr[] = {1, 2, 3, 4}, K = 2 Output: 2 Explanation: Total 2 pairs exists in the array with absolute difference divisible by 2. The pairs are: (1, 3), (2, 4)."
},
{
"code": null,
"e": 26567,
"s": 26395,
"text": "Input: arr[] = {3, 3, 3}, K = 3 Output: 3 Explanation: Total 3 pairs exists in this array with absolute difference divisible by 3. The pairs are: (3, 3), (3, 3), (3, 3). "
},
{
"code": null,
"e": 26722,
"s": 26567,
"text": "Naive Approach: The idea is to check for each pair of the array one by one and count the total number pairs whose absolute difference is divisible by K. "
},
{
"code": null,
"e": 26726,
"s": 26722,
"text": "C++"
},
{
"code": null,
"e": 26731,
"s": 26726,
"text": "Java"
},
{
"code": null,
"e": 26739,
"s": 26731,
"text": "Python3"
},
{
"code": null,
"e": 26742,
"s": 26739,
"text": "C#"
},
{
"code": null,
"e": 26753,
"s": 26742,
"text": "Javascript"
},
{
"code": "#include <bits/stdc++.h>using namespace std; // function to count pairs in an array// whose absolute difference is// divisible by kvoid countPairs(int arr[], int n, int k){ // initialize count as zero. int i, j, cnt = 0; // loop to count the valid pair for (i = 0; i < n - 1; i++) { for (j = i + 1; j < n; j++) { if ((arr[i] - arr[j] + k) % k == 0) cnt += 1; } } cout << cnt << endl;} // Driver codeint main(){ // input array int arr[] = {3, 3, 3}; int k = 3; // calculate the size of array int n = sizeof(arr) / sizeof(arr[0]); // function to count the valid pair countPairs(arr, n, k); return 0;}",
"e": 27438,
"s": 26753,
"text": null
},
{
"code": "import java.util.*; class GFG{ // function to count pairs in an array// whose absolute difference is// divisible by kstatic void countPairs(int arr[], int n, int k){ // initialize count as zero. int i, j, cnt = 0; // loop to count the valid pair for (i = 0; i < n - 1; i++) { for (j = i + 1; j < n; j++) { if ((arr[i] - arr[j] + k) % k == 0) cnt += 1; } } System.out.print(cnt +\"\\n\");} // Driver codepublic static void main(String[] args){ // input array int arr[] = {3, 3, 3}; int k = 3; // calculate the size of array int n = arr.length; // function to count the valid pair countPairs(arr, n, k);}} // This code is contributed by 29AjayKumar",
"e": 28175,
"s": 27438,
"text": null
},
{
"code": "# Python3 Code implementation of the above approach # function to count pairs in an array# whose absolute difference is# divisible by kdef countPairs(arr, n, k) : # initialize count as zero. cnt = 0; # loop to count the valid pair for i in range(n - 1) : for j in range(i + 1, n) : if ((arr[i] - arr[j] + k) % k == 0) : cnt += 1; print(cnt) ; # Driver codeif __name__ == \"__main__\" : # input array arr = [3, 3, 3]; k = 3; # calculate the size of array n = len(arr); # function to count the valid pair countPairs(arr, n, k); # This code is contributed by AnkitRai01",
"e": 28823,
"s": 28175,
"text": null
},
{
"code": "using System; class GFG{ // function to count pairs in an array// whose absolute difference is// divisible by kstatic void countPairs(int []arr, int n, int k){ // initialize count as zero. int i, j, cnt = 0; // loop to count the valid pair for (i = 0; i < n - 1; i++) { for (j = i + 1; j < n; j++) { if ((arr[i] - arr[j] + k) % k == 0) cnt += 1; } } Console.Write(cnt +\"\\n\");} // Driver codepublic static void Main(String[] args){ // input array int []arr = {3, 3, 3}; int k = 3; // calculate the size of array int n = arr.Length; // function to count the valid pair countPairs(arr, n, k);}} // This code is contributed by 29AjayKumar",
"e": 29551,
"s": 28823,
"text": null
},
{
"code": "<script> // Function to count pairs in an array// whose absolute difference is// divisible by kfunction countPairs(arr, n, k){ // Initialize count as zero. var i, j, cnt = 0; // Loop to count the valid pair for(i = 0; i < n - 1; i++) { for(j = i + 1; j < n; j++) { if ((arr[i] - arr[j] + k) % k == 0) cnt += 1; } } document.write(cnt + \"\\n\");} // Driver code // Input arrayvar arr = [ 3, 3, 3 ];var k = 3; // Calculate the size of arrayvar n = arr.length; // Function to count the valid paircountPairs(arr, n, k); // This code is contributed by umadevi9616 </script>",
"e": 30192,
"s": 29551,
"text": null
},
{
"code": null,
"e": 30194,
"s": 30192,
"text": "3"
},
{
"code": null,
"e": 30241,
"s": 30196,
"text": "Time Complexity: O(N2) Space Complexity:O(1)"
},
{
"code": null,
"e": 30263,
"s": 30241,
"text": "Efficient Approach: "
},
{
"code": null,
"e": 30276,
"s": 30263,
"text": "Algorithm: "
},
{
"code": null,
"e": 30738,
"s": 30276,
"text": "Convert each elements (A[i]) of the array to ((A[i]+K)%K)Use hashing teching technique to store the number of times (A[i]%K) occurs in the arrayNow, if an element A[i] occurs x times in the array then add x*(x-1)/2 (choosing any 2 elements out of x elements ) in the count pair where 1<=i<=n .This is because value of each elements of the array lies between 0 to K-1 so the absolute difference is divisible only if value of both the elements of a pair are equal"
},
{
"code": null,
"e": 30796,
"s": 30738,
"text": "Convert each elements (A[i]) of the array to ((A[i]+K)%K)"
},
{
"code": null,
"e": 30884,
"s": 30796,
"text": "Use hashing teching technique to store the number of times (A[i]%K) occurs in the array"
},
{
"code": null,
"e": 31202,
"s": 30884,
"text": "Now, if an element A[i] occurs x times in the array then add x*(x-1)/2 (choosing any 2 elements out of x elements ) in the count pair where 1<=i<=n .This is because value of each elements of the array lies between 0 to K-1 so the absolute difference is divisible only if value of both the elements of a pair are equal"
},
{
"code": null,
"e": 31206,
"s": 31202,
"text": "C++"
},
{
"code": null,
"e": 31211,
"s": 31206,
"text": "Java"
},
{
"code": null,
"e": 31219,
"s": 31211,
"text": "Python3"
},
{
"code": null,
"e": 31222,
"s": 31219,
"text": "C#"
},
{
"code": null,
"e": 31233,
"s": 31222,
"text": "Javascript"
},
{
"code": "// Write CPP code here#include <bits/stdc++.h>using namespace std; // function to Count pairs in an array whose// absolute difference is divisible by kvoid countPair(int arr[], int n, int k){ // initialize the count int cnt = 0; // making every element of arr in // range 0 to k - 1 for (int i = 0; i < n; i++) { arr[i] = (arr[i] + k) % k; } // create an array hash[] int hash[k] = { 0 }; // store to count of element of arr // in hash[] for (int i = 0; i < n; i++) { hash[arr[i]]++; } // count the pair whose absolute // difference is divisible by k for (int i = 0; i < k; i++) { cnt += (hash[i] * (hash[i] - 1)) / 2; } // print the value of count cout << cnt << endl;} // Driver Codeint main(){ // input array int arr[] = {1, 2, 3, 4}; int k = 2; // calculate the size of array int n = sizeof(arr) / sizeof(arr[0]); countPair(arr, n, k); return 0;}",
"e": 32187,
"s": 31233,
"text": null
},
{
"code": "// JAVA Implementation of above approachimport java.util.*; class GFG{ // function to Count pairs in an array whose// absolute difference is divisible by kstatic void countPair(int arr[], int n, int k){ // initialize the count int cnt = 0; // making every element of arr in // range 0 to k - 1 for (int i = 0; i < n; i++) { arr[i] = (arr[i] + k) % k; } // create an array hash[] int hash[] = new int[k]; // store to count of element of arr // in hash[] for (int i = 0; i < n; i++) { hash[arr[i]]++; } // count the pair whose absolute // difference is divisible by k for (int i = 0; i < k; i++) { cnt += (hash[i] * (hash[i] - 1)) / 2; } // print the value of count System.out.print(cnt +\"\\n\");} // Driver Codepublic static void main(String[] args){ // input array int arr[] = {1, 2, 3, 4}; int k = 2; // calculate the size of array int n = arr.length; countPair(arr, n, k);}} // This code is contributed by PrinciRaj1992",
"e": 33216,
"s": 32187,
"text": null
},
{
"code": "# Python3 Implementation of above approach # function to Count pairs in an array whose# absolute difference is divisible by kdef countPair(arr, n, k): # initialize the count cnt = 0; # making every element of arr in # range 0 to k - 1 for i in range(n): arr[i] = (arr[i] + k) % k; # create an array hash hash = [0]*k; # store to count of element of arr # in hash for i in range(n): hash[arr[i]] += 1; # count the pair whose absolute # difference is divisible by k for i in range(k): cnt += (hash[i] * (hash[i] - 1)) / 2; # print value of count print(int(cnt)); # Driver Codeif __name__ == '__main__': # input array arr = [1, 2, 3, 4]; k = 2; # calculate the size of array n = len(arr); countPair(arr, n, k); # This code is contributed by 29AjayKumar",
"e": 34058,
"s": 33216,
"text": null
},
{
"code": "// C# Implementation of above approachusing System; class GFG{ // function to Count pairs in an array whose// absolute difference is divisible by kstatic void countPair(int []arr, int n, int k){ // initialize the count int cnt = 0; // making every element of arr in // range 0 to k - 1 for (int i = 0; i < n; i++) { arr[i] = (arr[i] + k) % k; } // create an array hash[] int []hash = new int[k]; // store to count of element of arr // in hash[] for (int i = 0; i < n; i++) { hash[arr[i]]++; } // count the pair whose absolute // difference is divisible by k for (int i = 0; i < k; i++) { cnt += (hash[i] * (hash[i] - 1)) / 2; } // print the value of count Console.Write(cnt +\"\\n\");} // Driver Codepublic static void Main(String[] args){ // input array int []arr = {1, 2, 3, 4}; int k = 2; // calculate the size of array int n = arr.Length; countPair(arr, n, k);}} // This code is contributed by 29AjayKumar",
"e": 35074,
"s": 34058,
"text": null
},
{
"code": "<script> // Javascript Implementation of above approach // function to Count pairs in an array whose// absolute difference is divisible by kfunction countPair(arr, n, k){ // let initialize the count let cnt = 0; // making every element of arr in // range 0 to k - 1 for (let i = 0; i < n; i++) { arr[i] = (arr[i] + k) % k; } // create an array hash[] let hash = Array.from({length: k}, (_, i) => 0); // store to count of element of arr // in hash[] for (let i = 0; i < n; i++) { hash[arr[i]]++; } // count the pair whose absolute // difference is divisible by k for (let i = 0; i < k; i++) { cnt += (hash[i] * (hash[i] - 1)) / 2; } // print the value of count document.write(cnt +\"<br/>\");} // Driver code // input array let arr = [1, 2, 3, 4]; let k = 2; // calculate the size of array let n = arr.length; countPair(arr, n, k); </script>",
"e": 36126,
"s": 35074,
"text": null
},
{
"code": null,
"e": 36128,
"s": 36126,
"text": "2"
},
{
"code": null,
"e": 36177,
"s": 36130,
"text": "Time Complexity: O(n+k) Auxiliary Space: O(k) "
},
{
"code": null,
"e": 36189,
"s": 36177,
"text": "29AjayKumar"
},
{
"code": null,
"e": 36203,
"s": 36189,
"text": "princiraj1992"
},
{
"code": null,
"e": 36211,
"s": 36203,
"text": "ankthon"
},
{
"code": null,
"e": 36223,
"s": 36211,
"text": "umadevi9616"
},
{
"code": null,
"e": 36245,
"s": 36223,
"text": "susmitakundugoaldanga"
},
{
"code": null,
"e": 36262,
"s": 36245,
"text": "arorakashish0911"
},
{
"code": null,
"e": 36275,
"s": 36262,
"text": "simmytarika5"
},
{
"code": null,
"e": 36292,
"s": 36275,
"text": "khushboogoyal499"
},
{
"code": null,
"e": 36308,
"s": 36292,
"text": "simranarora5sos"
},
{
"code": null,
"e": 36332,
"s": 36308,
"text": "Technical Scripter 2019"
},
{
"code": null,
"e": 36339,
"s": 36332,
"text": "Arrays"
},
{
"code": null,
"e": 36344,
"s": 36339,
"text": "Hash"
},
{
"code": null,
"e": 36351,
"s": 36344,
"text": "Arrays"
},
{
"code": null,
"e": 36356,
"s": 36351,
"text": "Hash"
},
{
"code": null,
"e": 36454,
"s": 36356,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36485,
"s": 36454,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 36512,
"s": 36485,
"text": "Count pairs with given sum"
},
{
"code": null,
"e": 36537,
"s": 36512,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 36575,
"s": 36537,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 36596,
"s": 36575,
"text": "Next Greater Element"
},
{
"code": null,
"e": 36632,
"s": 36596,
"text": "Internal Working of HashMap in Java"
},
{
"code": null,
"e": 36659,
"s": 36632,
"text": "Count pairs with given sum"
},
{
"code": null,
"e": 36690,
"s": 36659,
"text": "Hashing | Set 1 (Introduction)"
},
{
"code": null,
"e": 36724,
"s": 36690,
"text": "Hashing | Set 3 (Open Addressing)"
}
] |
Dart Programming - List - GeeksforGeeks | 29 Oct, 2021
In Dart programming, List datatype is similar to arrays in other programming languages. List is used to represent a collection of objects. It is an ordered group of objects. The core libraries in Dart are responsible for the existence of List class, its creation and manipulation.Logical Representation of List:
Index of the element represents the position of the specific data and when the list item of that index is called the element is displayed. Generally, the list item is called from its index.Types of List – There are broadly two types of list on the basis of its length:
Fixed Length ListGrowable List
Fixed Length List
Growable List
Here, the size of the list is declared initially and can’t be changed during runtime.Syntax:
Example:
Java
void main(){ var gfg = new List(3); gfg[0] = 'Geeks'; gfg[1] = 'For'; gfg[2] = 'Geeks'; // Printing all the values in List print(gfg); // Printing value at specific position print(gfg[2]);}
Output:
[Geeks, For, Geeks]
Geeks
This type of list is declared without declaring size of the list. Its length can be changed during runtime.Syntax:
Adding a value to growable list –
Java
void main(){ var gfg = [ 'Geeks', 'For' ]; // Printing all the values in List print(gfg); // Adding new value in List and printing it gfg.add('Geeks'); // list_name.add(value); print(gfg);}
Output:
[Geeks, For]
[Geeks, For, Geeks]
Adding multiple value to growable list –
Java
void main(){ var gfg = [ 'Geeks' ]; // Printing all the values in List print(gfg); // Adding multiple values in List and printing it // list_name.addAll([val 1, val 2, ...]); gfg.addAll([ 'For', 'Geeks' ]); print(gfg);}
Output:
[Geeks]
[Geeks, For, Geeks]
Adding a value to growable list at specific index –
Java
void main(){ var gfg = [ 'Geeks', 'Geeks' ]; // Printing all the values in List print(gfg); // Adding new value in List at specific index and printing it // list_name.insert(index, value); gfg.insert(1, 'For'); print(gfg);
Output:
[Geeks, Geeks]
[Geeks, For, Geeks]
Adding multiple value to growable list at specific indexes –
Java
void main(){ var gfg = [ 'Geeks' ]; // Printing all the values in List print(gfg); // Adding new value in List at specific index and printing it // list_name.insertAll(index, list_of_values); gfg.insertAll(1, [ 'For', 'Geeks' ]); print(gfg); // Element at index 1 in list print(gfg[1]);}
Output:
[Geeks]
[Geeks, For, Geeks]
For
Types of List (Basis of its Dimensions) : There is a various number of the list based on dimension, but most popular among them are:
1-Dimensional (1-D) List2-Dimensional (2-D) List3-Dimensional (3-D) ListMultidimension List
1-Dimensional (1-D) List
2-Dimensional (2-D) List
3-Dimensional (3-D) List
Multidimension List
Here, we have already discussed the 1-D list.
Here, the list is defined in two dimensions and thus forming the look of the table.Creating 2-D List –
Java
void main(){ int a = 3; int b = 3; // Creating two dimensional list var gfg = List.generate(a, (i) = > List(b), growable: false); // Printing its value print(gfg); // Inserting values for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { gfg[i][j] = i + j; } } // Printing its value print(gfg);}
Output:
[[null, null, null], [null, null, null], [null, null, null]]
[[0, 1, 2], [1, 2, 3], [2, 3, 4]]
Another way of creating 2-D List –
Java
void main(){ // Creating three dimensional list var gfg = List.generate(3, (i) = > List.generate(3, (j) = > i + j)); // Printing its value print(gfg);}
Output:
[[0, 1, 2], [1, 2, 3], [2, 3, 4]]
There is also another way of creating 2-D list, i.e give the values associated with the indexes and it will lead to the creation of the 2-D list.
The representation of 3-D list is quiet difficult but its creation is similar to that of the 2-D list.Example:
Java
void main(){ // Creating three dimensional list var gfg = List.generate(3, (i) = > List.generate(3, (j) = > List.generate(3, (k) = > i + j + k))); // Printing its value print(gfg);}
Output:
[[[0, 1, 2], [1, 2, 3], [2, 3, 4]], [[1, 2, 3], [2, 3, 4], [3, 4, 5]], [[2, 3, 4], [3, 4, 5], [4, 5, 6]]]
Note: In the similar fashion one can create n-dimensional List i.e by using “List.generate()” method.
sooda367
sagar0719kumar
Dart Data-types
Dart-List
GBlog
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
DSA Sheet by Love Babbar
GET and POST requests using Python
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Types of Software Testing
Working with csv files in Python
Supervised and Unsupervised learning
How to Start Learning DSA?
Differences between Procedural and Object Oriented Programming
7 Things You Didn’t Know About Java
Top 10 System Design Interview Questions and Answers | [
{
"code": null,
"e": 25603,
"s": 25575,
"text": "\n29 Oct, 2021"
},
{
"code": null,
"e": 25917,
"s": 25603,
"text": "In Dart programming, List datatype is similar to arrays in other programming languages. List is used to represent a collection of objects. It is an ordered group of objects. The core libraries in Dart are responsible for the existence of List class, its creation and manipulation.Logical Representation of List: "
},
{
"code": null,
"e": 26188,
"s": 25917,
"text": "Index of the element represents the position of the specific data and when the list item of that index is called the element is displayed. Generally, the list item is called from its index.Types of List – There are broadly two types of list on the basis of its length: "
},
{
"code": null,
"e": 26219,
"s": 26188,
"text": "Fixed Length ListGrowable List"
},
{
"code": null,
"e": 26237,
"s": 26219,
"text": "Fixed Length List"
},
{
"code": null,
"e": 26251,
"s": 26237,
"text": "Growable List"
},
{
"code": null,
"e": 26348,
"s": 26253,
"text": "Here, the size of the list is declared initially and can’t be changed during runtime.Syntax: "
},
{
"code": null,
"e": 26361,
"s": 26350,
"text": "Example: "
},
{
"code": null,
"e": 26366,
"s": 26361,
"text": "Java"
},
{
"code": "void main(){ var gfg = new List(3); gfg[0] = 'Geeks'; gfg[1] = 'For'; gfg[2] = 'Geeks'; // Printing all the values in List print(gfg); // Printing value at specific position print(gfg[2]);}",
"e": 26582,
"s": 26366,
"text": null
},
{
"code": null,
"e": 26592,
"s": 26582,
"text": "Output: "
},
{
"code": null,
"e": 26618,
"s": 26592,
"text": "[Geeks, For, Geeks]\nGeeks"
},
{
"code": null,
"e": 26737,
"s": 26620,
"text": "This type of list is declared without declaring size of the list. Its length can be changed during runtime.Syntax: "
},
{
"code": null,
"e": 26775,
"s": 26739,
"text": "Adding a value to growable list – "
},
{
"code": null,
"e": 26780,
"s": 26775,
"text": "Java"
},
{
"code": "void main(){ var gfg = [ 'Geeks', 'For' ]; // Printing all the values in List print(gfg); // Adding new value in List and printing it gfg.add('Geeks'); // list_name.add(value); print(gfg);}",
"e": 26990,
"s": 26780,
"text": null
},
{
"code": null,
"e": 27000,
"s": 26990,
"text": "Output: "
},
{
"code": null,
"e": 27033,
"s": 27000,
"text": "[Geeks, For]\n[Geeks, For, Geeks]"
},
{
"code": null,
"e": 27077,
"s": 27033,
"text": " Adding multiple value to growable list – "
},
{
"code": null,
"e": 27082,
"s": 27077,
"text": "Java"
},
{
"code": "void main(){ var gfg = [ 'Geeks' ]; // Printing all the values in List print(gfg); // Adding multiple values in List and printing it // list_name.addAll([val 1, val 2, ...]); gfg.addAll([ 'For', 'Geeks' ]); print(gfg);}",
"e": 27326,
"s": 27082,
"text": null
},
{
"code": null,
"e": 27336,
"s": 27326,
"text": "Output: "
},
{
"code": null,
"e": 27364,
"s": 27336,
"text": "[Geeks]\n[Geeks, For, Geeks]"
},
{
"code": null,
"e": 27419,
"s": 27364,
"text": " Adding a value to growable list at specific index – "
},
{
"code": null,
"e": 27424,
"s": 27419,
"text": "Java"
},
{
"code": "void main(){ var gfg = [ 'Geeks', 'Geeks' ]; // Printing all the values in List print(gfg); // Adding new value in List at specific index and printing it // list_name.insert(index, value); gfg.insert(1, 'For'); print(gfg);",
"e": 27671,
"s": 27424,
"text": null
},
{
"code": null,
"e": 27681,
"s": 27671,
"text": "Output: "
},
{
"code": null,
"e": 27716,
"s": 27681,
"text": "[Geeks, Geeks]\n[Geeks, For, Geeks]"
},
{
"code": null,
"e": 27780,
"s": 27716,
"text": " Adding multiple value to growable list at specific indexes – "
},
{
"code": null,
"e": 27785,
"s": 27780,
"text": "Java"
},
{
"code": "void main(){ var gfg = [ 'Geeks' ]; // Printing all the values in List print(gfg); // Adding new value in List at specific index and printing it // list_name.insertAll(index, list_of_values); gfg.insertAll(1, [ 'For', 'Geeks' ]); print(gfg); // Element at index 1 in list print(gfg[1]);}",
"e": 28104,
"s": 27785,
"text": null
},
{
"code": null,
"e": 28114,
"s": 28104,
"text": "Output: "
},
{
"code": null,
"e": 28146,
"s": 28114,
"text": "[Geeks]\n[Geeks, For, Geeks]\nFor"
},
{
"code": null,
"e": 28282,
"s": 28146,
"text": " Types of List (Basis of its Dimensions) : There is a various number of the list based on dimension, but most popular among them are: "
},
{
"code": null,
"e": 28374,
"s": 28282,
"text": "1-Dimensional (1-D) List2-Dimensional (2-D) List3-Dimensional (3-D) ListMultidimension List"
},
{
"code": null,
"e": 28399,
"s": 28374,
"text": "1-Dimensional (1-D) List"
},
{
"code": null,
"e": 28424,
"s": 28399,
"text": "2-Dimensional (2-D) List"
},
{
"code": null,
"e": 28449,
"s": 28424,
"text": "3-Dimensional (3-D) List"
},
{
"code": null,
"e": 28469,
"s": 28449,
"text": "Multidimension List"
},
{
"code": null,
"e": 28516,
"s": 28469,
"text": "Here, we have already discussed the 1-D list. "
},
{
"code": null,
"e": 28621,
"s": 28516,
"text": "Here, the list is defined in two dimensions and thus forming the look of the table.Creating 2-D List – "
},
{
"code": null,
"e": 28626,
"s": 28621,
"text": "Java"
},
{
"code": "void main(){ int a = 3; int b = 3; // Creating two dimensional list var gfg = List.generate(a, (i) = > List(b), growable: false); // Printing its value print(gfg); // Inserting values for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { gfg[i][j] = i + j; } } // Printing its value print(gfg);}",
"e": 28989,
"s": 28626,
"text": null
},
{
"code": null,
"e": 28999,
"s": 28989,
"text": "Output: "
},
{
"code": null,
"e": 29094,
"s": 28999,
"text": "[[null, null, null], [null, null, null], [null, null, null]]\n[[0, 1, 2], [1, 2, 3], [2, 3, 4]]"
},
{
"code": null,
"e": 29131,
"s": 29094,
"text": "Another way of creating 2-D List – "
},
{
"code": null,
"e": 29136,
"s": 29131,
"text": "Java"
},
{
"code": "void main(){ // Creating three dimensional list var gfg = List.generate(3, (i) = > List.generate(3, (j) = > i + j)); // Printing its value print(gfg);}",
"e": 29301,
"s": 29136,
"text": null
},
{
"code": null,
"e": 29311,
"s": 29301,
"text": "Output: "
},
{
"code": null,
"e": 29345,
"s": 29311,
"text": "[[0, 1, 2], [1, 2, 3], [2, 3, 4]]"
},
{
"code": null,
"e": 29492,
"s": 29345,
"text": "There is also another way of creating 2-D list, i.e give the values associated with the indexes and it will lead to the creation of the 2-D list. "
},
{
"code": null,
"e": 29605,
"s": 29492,
"text": "The representation of 3-D list is quiet difficult but its creation is similar to that of the 2-D list.Example: "
},
{
"code": null,
"e": 29610,
"s": 29605,
"text": "Java"
},
{
"code": "void main(){ // Creating three dimensional list var gfg = List.generate(3, (i) = > List.generate(3, (j) = > List.generate(3, (k) = > i + j + k))); // Printing its value print(gfg);}",
"e": 29865,
"s": 29610,
"text": null
},
{
"code": null,
"e": 29875,
"s": 29865,
"text": "Output: "
},
{
"code": null,
"e": 29981,
"s": 29875,
"text": "[[[0, 1, 2], [1, 2, 3], [2, 3, 4]], [[1, 2, 3], [2, 3, 4], [3, 4, 5]], [[2, 3, 4], [3, 4, 5], [4, 5, 6]]]"
},
{
"code": null,
"e": 30084,
"s": 29981,
"text": "Note: In the similar fashion one can create n-dimensional List i.e by using “List.generate()” method. "
},
{
"code": null,
"e": 30093,
"s": 30084,
"text": "sooda367"
},
{
"code": null,
"e": 30108,
"s": 30093,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 30124,
"s": 30108,
"text": "Dart Data-types"
},
{
"code": null,
"e": 30134,
"s": 30124,
"text": "Dart-List"
},
{
"code": null,
"e": 30140,
"s": 30134,
"text": "GBlog"
},
{
"code": null,
"e": 30238,
"s": 30140,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30263,
"s": 30238,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 30298,
"s": 30263,
"text": "GET and POST requests using Python"
},
{
"code": null,
"e": 30360,
"s": 30298,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 30386,
"s": 30360,
"text": "Types of Software Testing"
},
{
"code": null,
"e": 30419,
"s": 30386,
"text": "Working with csv files in Python"
},
{
"code": null,
"e": 30456,
"s": 30419,
"text": "Supervised and Unsupervised learning"
},
{
"code": null,
"e": 30483,
"s": 30456,
"text": "How to Start Learning DSA?"
},
{
"code": null,
"e": 30546,
"s": 30483,
"text": "Differences between Procedural and Object Oriented Programming"
},
{
"code": null,
"e": 30582,
"s": 30546,
"text": "7 Things You Didn’t Know About Java"
}
] |
Python String casefold() Method - GeeksforGeeks | 03 May, 2022
Python String casefold() method is used to implement caseless string matching. It is similar to lower() string method but case removes all the case distinctions present in a string. i.e ignore cases when comparing.
Syntax:
string.casefold()
Parameters:
The casefold() method doesn’t take any parameters.
Return value:
It returns the case folded string the string converted to lower case.
Python3
# Python program to convert string in lower casestring = "GEEKSFORGEEKS" # print lowercase stringprint("lowercase string: ",string.casefold())
Output:
lowercase string: geeksforgeeks
Python3
# Program to check if a string# is palindrome or not # change this value for a different outputstr = 'geeksforgeeks' # make it suitable for caseless comparisonstr = str.casefold() # reverse the stringrev_str = "".join(reversed(str))# check if the string is equal to its reverseif str == rev_str: print("palindrome")else: print("not palindrome")
Output:
not palindrome
Python3
# Program to count# the number of each# vowel in a string # string of vowelsv = 'aeiou' # change this value for a different resultstr = 'Hello, have you try geeksforgeeks?' # input from the user# str = input("Enter a string: ") # caseless comparisonstr = str.casefold() # make a dictionary with# each vowel a key and value 0c = {}.fromkeys(v,0) # count the vowelsfor char in str: if char in c: c[char] += 1print(c)
Output:
{'a': 1, 'e': 6, 'i': 0, 'o': 3, 'u': 1}
Anamitra Musib
AmiyaRanjanRout
sroy84766
simmytarika5
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
Python Dictionary
Read a file line by line in Python
Taking input in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe | [
{
"code": null,
"e": 25041,
"s": 25013,
"text": "\n03 May, 2022"
},
{
"code": null,
"e": 25257,
"s": 25041,
"text": "Python String casefold() method is used to implement caseless string matching. It is similar to lower() string method but case removes all the case distinctions present in a string. i.e ignore cases when comparing. "
},
{
"code": null,
"e": 25266,
"s": 25257,
"text": "Syntax: "
},
{
"code": null,
"e": 25284,
"s": 25266,
"text": "string.casefold()"
},
{
"code": null,
"e": 25296,
"s": 25284,
"text": "Parameters:"
},
{
"code": null,
"e": 25347,
"s": 25296,
"text": "The casefold() method doesn’t take any parameters."
},
{
"code": null,
"e": 25361,
"s": 25347,
"text": "Return value:"
},
{
"code": null,
"e": 25431,
"s": 25361,
"text": "It returns the case folded string the string converted to lower case."
},
{
"code": null,
"e": 25439,
"s": 25431,
"text": "Python3"
},
{
"code": "# Python program to convert string in lower casestring = \"GEEKSFORGEEKS\" # print lowercase stringprint(\"lowercase string: \",string.casefold())",
"e": 25582,
"s": 25439,
"text": null
},
{
"code": null,
"e": 25590,
"s": 25582,
"text": "Output:"
},
{
"code": null,
"e": 25622,
"s": 25590,
"text": "lowercase string: geeksforgeeks"
},
{
"code": null,
"e": 25630,
"s": 25622,
"text": "Python3"
},
{
"code": "# Program to check if a string# is palindrome or not # change this value for a different outputstr = 'geeksforgeeks' # make it suitable for caseless comparisonstr = str.casefold() # reverse the stringrev_str = \"\".join(reversed(str))# check if the string is equal to its reverseif str == rev_str: print(\"palindrome\")else: print(\"not palindrome\")",
"e": 25986,
"s": 25630,
"text": null
},
{
"code": null,
"e": 25994,
"s": 25986,
"text": "Output:"
},
{
"code": null,
"e": 26009,
"s": 25994,
"text": "not palindrome"
},
{
"code": null,
"e": 26017,
"s": 26009,
"text": "Python3"
},
{
"code": "# Program to count# the number of each# vowel in a string # string of vowelsv = 'aeiou' # change this value for a different resultstr = 'Hello, have you try geeksforgeeks?' # input from the user# str = input(\"Enter a string: \") # caseless comparisonstr = str.casefold() # make a dictionary with# each vowel a key and value 0c = {}.fromkeys(v,0) # count the vowelsfor char in str: if char in c: c[char] += 1print(c)",
"e": 26458,
"s": 26017,
"text": null
},
{
"code": null,
"e": 26466,
"s": 26458,
"text": "Output:"
},
{
"code": null,
"e": 26507,
"s": 26466,
"text": "{'a': 1, 'e': 6, 'i': 0, 'o': 3, 'u': 1}"
},
{
"code": null,
"e": 26522,
"s": 26507,
"text": "Anamitra Musib"
},
{
"code": null,
"e": 26538,
"s": 26522,
"text": "AmiyaRanjanRout"
},
{
"code": null,
"e": 26548,
"s": 26538,
"text": "sroy84766"
},
{
"code": null,
"e": 26561,
"s": 26548,
"text": "simmytarika5"
},
{
"code": null,
"e": 26568,
"s": 26561,
"text": "Python"
},
{
"code": null,
"e": 26666,
"s": 26568,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26694,
"s": 26666,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 26744,
"s": 26694,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 26766,
"s": 26744,
"text": "Python map() function"
},
{
"code": null,
"e": 26810,
"s": 26766,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 26828,
"s": 26810,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26863,
"s": 26828,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 26886,
"s": 26863,
"text": "Taking input in Python"
},
{
"code": null,
"e": 26918,
"s": 26886,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26940,
"s": 26918,
"text": "Enumerate() in Python"
}
] |
Material Design EditText in Android with Example - GeeksforGeeks | 26 Dec, 2020
EditText is one of the important UI elements. Edittext refers to the widget that displays an empty text field in which a user can enter the required text and this text is further used inside the application. In this article its been discussed to implement the special type of text fields, those are called Material Design EditText. Have a look at the normal edit text in android and Material design Text fields in android. The design and the easy to use implementation makes them different from normal EditText fields.
In this example, we are going to demonstrate two important types of Material Design EditText:
Filled EditTextOutlined EditText
Filled EditText
Outlined EditText
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio.
Select either Java or Kotlin as the programming language.
Step 2: Invoke the dependency to the app level gradle file
Invoke the Material Design dependency to app-level gradle file as:
implementation ‘com.google.android.material:material:1.3.0-alpha03’
Get the app level gradle file by going to app > build.gradle file. And click on the “Sync Now” button. And make sure the system should be connected to the network.
Refer to the following image to locate and invoke the dependency in-app level gradle file (Under project hierarchy view).
Step 3: Change the base theme of the application
We need to change the base theme of the application because we are using the material design components. Otherwise, the application crashes immediately after it is launched.
To change the base theme of the application open app > src > main > res > values > styles.xml.
XML
<resources> <!-- Base application theme. --> <style name="AppTheme" parent="Theme.MaterialComponents.Light.DarkActionBar"> <!-- Customize your theme here. --> <item name="colorPrimary">@color/colorPrimary</item> <item name="colorPrimaryDark">@color/colorPrimaryDark</item> <item name="colorAccent">@color/colorAccent</item> </style> </resources>
Refer to the following image to locate the styles.xml file and change the base theme of the application.
Step 4: Working with the activity_main.xml file
Invoke the following code to implement the filled EditText.
Below is the code for the activity_main.xml file.
Comments are added inside the code to understand the code in more detail.
XML
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity" tools:ignore="HardcodedText"> <!--this is the filled layout box for the edit text--> <!--this layout must be used to reposition or change the height and width of the edit text--> <com.google.android.material.textfield.TextInputLayout android:id="@+id/filledTextField" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="32dp" android:layout_marginTop="64dp" android:layout_marginEnd="32dp" android:hint="Enter something"> <!--this is the actual edit text which takes the input--> <com.google.android.material.textfield.TextInputEditText android:id="@+id/edit_text" android:layout_width="match_parent" android:layout_height="wrap_content" /> </com.google.android.material.textfield.TextInputLayout> <!--sample button to submit entered data inside from edit text--> <Button android:id="@+id/submit_button" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="32dp" android:layout_marginTop="8dp" android:layout_marginEnd="32dp" android:text="Submit" /> <!--text view which previews the entered data by user--> <TextView android:id="@+id/text_preview" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginTop="32dp" android:text="You Entered : " android:textSize="18sp" /> </LinearLayout>
In the above code the “com.google.android.material.textfield.TextInputLayout” makes the filled box for the EditText field.
And “com.google.android.material.textfield.TextInputEditText” which is the actual edit text which takes input from the user and this must be used to handle all the inputs in the MainActivity file.
Output UI is produced as:
Step 5: Working with the MainActivity file
Now invoke the following java code to handle the material design EditText.
Below is the code for the MainActivity file.
Comments are added inside the code to understand the code in more detail.
Java
Kotlin
import android.annotation.SuppressLint;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.TextView;import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { // UI widgets to handle Button bSubmit; EditText mEditText; TextView tvTextPreview; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Register the UI widgets // with their appropriate IDs. bSubmit = findViewById(R.id.submit_button); mEditText = findViewById(R.id.edit_text); tvTextPreview = findViewById(R.id.text_preview); // handle submit button to preview the entered data bSubmit.setOnClickListener(new View.OnClickListener() { @SuppressLint("SetTextI18n") @Override public void onClick(View v) { // set the entered data to text preview tvTextPreview.setText("You Entered : " + mEditText.getText().toString()); } }); }}
import android.annotation.SuppressLintimport android.os.Bundleimport android.widget.Buttonimport android.widget.EditTextimport android.widget.TextViewimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { @SuppressLint("SetTextI18n") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Register the UI widgets with their appropriate IDs. val bSubmit = findViewById<Button>(R.id.submit_button) val mEditText = findViewById<EditText>(R.id.edit_text) val tvTextPreview = findViewById<TextView>(R.id.text_preview) // handle submit button to // preview the entered data bSubmit.setOnClickListener { tvTextPreview.text = "You Entered : " + mEditText.text.toString() } }}
Step 6: Working with the activity_main.xml file
Invoke the following code to implement the filled edit text.
Only difference is the style attribute in the “com.google.android.material.textfield.TextInputLayout” to be invoked.
Comments are added inside the code to understand the code in more detail.
XML
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity" tools:ignore="HardcodedText"> <!--this is the outlined layout box for the edit text--> <!--this layout must be used to reposition or change the height and width of the edit text--> <!--to get the outlined edit text the style attribute as following must be invoked--> <com.google.android.material.textfield.TextInputLayout android:id="@+id/filledTextField" style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="32dp" android:layout_marginTop="64dp" android:layout_marginEnd="32dp" android:hint="Enter something"> <!--this is the actual edit text which takes the input--> <com.google.android.material.textfield.TextInputEditText android:id="@+id/edit_text" android:layout_width="match_parent" android:layout_height="wrap_content" /> </com.google.android.material.textfield.TextInputLayout> <!--sample button to submit entered data inside from edit text--> <Button android:id="@+id/submit_button" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="32dp" android:layout_marginTop="8dp" android:layout_marginEnd="32dp" android:text="Submit" /> <!--text view which previews the entered data by user--> <TextView android:id="@+id/text_preview" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginTop="32dp" android:text="You Entered : " android:textSize="18sp" /> </LinearLayout>
Following output UI is produced:
Step 7: Same as Step 5
Refer to Step 5
aashaypawar
android
Android
Java
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Resource Raw Folder in Android Studio
Flutter - Custom Bottom Navigation Bar
How to Read Data from SQLite Database in Android?
Retrofit with Kotlin Coroutine in Android
How to Post Data to API using Retrofit in Android?
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples | [
{
"code": null,
"e": 26405,
"s": 26377,
"text": "\n26 Dec, 2020"
},
{
"code": null,
"e": 26924,
"s": 26405,
"text": "EditText is one of the important UI elements. Edittext refers to the widget that displays an empty text field in which a user can enter the required text and this text is further used inside the application. In this article its been discussed to implement the special type of text fields, those are called Material Design EditText. Have a look at the normal edit text in android and Material design Text fields in android. The design and the easy to use implementation makes them different from normal EditText fields."
},
{
"code": null,
"e": 27018,
"s": 26924,
"text": "In this example, we are going to demonstrate two important types of Material Design EditText:"
},
{
"code": null,
"e": 27051,
"s": 27018,
"text": "Filled EditTextOutlined EditText"
},
{
"code": null,
"e": 27067,
"s": 27051,
"text": "Filled EditText"
},
{
"code": null,
"e": 27085,
"s": 27067,
"text": "Outlined EditText"
},
{
"code": null,
"e": 27114,
"s": 27085,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 27225,
"s": 27114,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio."
},
{
"code": null,
"e": 27283,
"s": 27225,
"text": "Select either Java or Kotlin as the programming language."
},
{
"code": null,
"e": 27342,
"s": 27283,
"text": "Step 2: Invoke the dependency to the app level gradle file"
},
{
"code": null,
"e": 27409,
"s": 27342,
"text": "Invoke the Material Design dependency to app-level gradle file as:"
},
{
"code": null,
"e": 27478,
"s": 27409,
"text": "implementation ‘com.google.android.material:material:1.3.0-alpha03’ "
},
{
"code": null,
"e": 27642,
"s": 27478,
"text": "Get the app level gradle file by going to app > build.gradle file. And click on the “Sync Now” button. And make sure the system should be connected to the network."
},
{
"code": null,
"e": 27764,
"s": 27642,
"text": "Refer to the following image to locate and invoke the dependency in-app level gradle file (Under project hierarchy view)."
},
{
"code": null,
"e": 27813,
"s": 27764,
"text": "Step 3: Change the base theme of the application"
},
{
"code": null,
"e": 27987,
"s": 27813,
"text": "We need to change the base theme of the application because we are using the material design components. Otherwise, the application crashes immediately after it is launched."
},
{
"code": null,
"e": 28083,
"s": 27987,
"text": "To change the base theme of the application open app > src > main > res > values > styles.xml. "
},
{
"code": null,
"e": 28087,
"s": 28083,
"text": "XML"
},
{
"code": "<resources> <!-- Base application theme. --> <style name=\"AppTheme\" parent=\"Theme.MaterialComponents.Light.DarkActionBar\"> <!-- Customize your theme here. --> <item name=\"colorPrimary\">@color/colorPrimary</item> <item name=\"colorPrimaryDark\">@color/colorPrimaryDark</item> <item name=\"colorAccent\">@color/colorAccent</item> </style> </resources>",
"e": 28471,
"s": 28087,
"text": null
},
{
"code": null,
"e": 28577,
"s": 28471,
"text": "Refer to the following image to locate the styles.xml file and change the base theme of the application."
},
{
"code": null,
"e": 28625,
"s": 28577,
"text": "Step 4: Working with the activity_main.xml file"
},
{
"code": null,
"e": 28685,
"s": 28625,
"text": "Invoke the following code to implement the filled EditText."
},
{
"code": null,
"e": 28735,
"s": 28685,
"text": "Below is the code for the activity_main.xml file."
},
{
"code": null,
"e": 28809,
"s": 28735,
"text": "Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 28813,
"s": 28809,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\" tools:context=\".MainActivity\" tools:ignore=\"HardcodedText\"> <!--this is the filled layout box for the edit text--> <!--this layout must be used to reposition or change the height and width of the edit text--> <com.google.android.material.textfield.TextInputLayout android:id=\"@+id/filledTextField\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"32dp\" android:layout_marginTop=\"64dp\" android:layout_marginEnd=\"32dp\" android:hint=\"Enter something\"> <!--this is the actual edit text which takes the input--> <com.google.android.material.textfield.TextInputEditText android:id=\"@+id/edit_text\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" /> </com.google.android.material.textfield.TextInputLayout> <!--sample button to submit entered data inside from edit text--> <Button android:id=\"@+id/submit_button\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"32dp\" android:layout_marginTop=\"8dp\" android:layout_marginEnd=\"32dp\" android:text=\"Submit\" /> <!--text view which previews the entered data by user--> <TextView android:id=\"@+id/text_preview\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_gravity=\"center\" android:layout_marginTop=\"32dp\" android:text=\"You Entered : \" android:textSize=\"18sp\" /> </LinearLayout>",
"e": 30719,
"s": 28813,
"text": null
},
{
"code": null,
"e": 30843,
"s": 30719,
"text": "In the above code the “com.google.android.material.textfield.TextInputLayout” makes the filled box for the EditText field."
},
{
"code": null,
"e": 31040,
"s": 30843,
"text": "And “com.google.android.material.textfield.TextInputEditText” which is the actual edit text which takes input from the user and this must be used to handle all the inputs in the MainActivity file."
},
{
"code": null,
"e": 31067,
"s": 31040,
"text": "Output UI is produced as: "
},
{
"code": null,
"e": 31111,
"s": 31067,
"text": "Step 5: Working with the MainActivity file "
},
{
"code": null,
"e": 31186,
"s": 31111,
"text": "Now invoke the following java code to handle the material design EditText."
},
{
"code": null,
"e": 31231,
"s": 31186,
"text": "Below is the code for the MainActivity file."
},
{
"code": null,
"e": 31305,
"s": 31231,
"text": "Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 31310,
"s": 31305,
"text": "Java"
},
{
"code": null,
"e": 31317,
"s": 31310,
"text": "Kotlin"
},
{
"code": "import android.annotation.SuppressLint;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.TextView;import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { // UI widgets to handle Button bSubmit; EditText mEditText; TextView tvTextPreview; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Register the UI widgets // with their appropriate IDs. bSubmit = findViewById(R.id.submit_button); mEditText = findViewById(R.id.edit_text); tvTextPreview = findViewById(R.id.text_preview); // handle submit button to preview the entered data bSubmit.setOnClickListener(new View.OnClickListener() { @SuppressLint(\"SetTextI18n\") @Override public void onClick(View v) { // set the entered data to text preview tvTextPreview.setText(\"You Entered : \" + mEditText.getText().toString()); } }); }}",
"e": 32487,
"s": 31317,
"text": null
},
{
"code": "import android.annotation.SuppressLintimport android.os.Bundleimport android.widget.Buttonimport android.widget.EditTextimport android.widget.TextViewimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { @SuppressLint(\"SetTextI18n\") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Register the UI widgets with their appropriate IDs. val bSubmit = findViewById<Button>(R.id.submit_button) val mEditText = findViewById<EditText>(R.id.edit_text) val tvTextPreview = findViewById<TextView>(R.id.text_preview) // handle submit button to // preview the entered data bSubmit.setOnClickListener { tvTextPreview.text = \"You Entered : \" + mEditText.text.toString() } }}",
"e": 33361,
"s": 32487,
"text": null
},
{
"code": null,
"e": 33409,
"s": 33361,
"text": "Step 6: Working with the activity_main.xml file"
},
{
"code": null,
"e": 33470,
"s": 33409,
"text": "Invoke the following code to implement the filled edit text."
},
{
"code": null,
"e": 33587,
"s": 33470,
"text": "Only difference is the style attribute in the “com.google.android.material.textfield.TextInputLayout” to be invoked."
},
{
"code": null,
"e": 33661,
"s": 33587,
"text": "Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 33665,
"s": 33661,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\" tools:context=\".MainActivity\" tools:ignore=\"HardcodedText\"> <!--this is the outlined layout box for the edit text--> <!--this layout must be used to reposition or change the height and width of the edit text--> <!--to get the outlined edit text the style attribute as following must be invoked--> <com.google.android.material.textfield.TextInputLayout android:id=\"@+id/filledTextField\" style=\"@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"32dp\" android:layout_marginTop=\"64dp\" android:layout_marginEnd=\"32dp\" android:hint=\"Enter something\"> <!--this is the actual edit text which takes the input--> <com.google.android.material.textfield.TextInputEditText android:id=\"@+id/edit_text\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" /> </com.google.android.material.textfield.TextInputLayout> <!--sample button to submit entered data inside from edit text--> <Button android:id=\"@+id/submit_button\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"32dp\" android:layout_marginTop=\"8dp\" android:layout_marginEnd=\"32dp\" android:text=\"Submit\" /> <!--text view which previews the entered data by user--> <TextView android:id=\"@+id/text_preview\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_gravity=\"center\" android:layout_marginTop=\"32dp\" android:text=\"You Entered : \" android:textSize=\"18sp\" /> </LinearLayout>",
"e": 35740,
"s": 33665,
"text": null
},
{
"code": null,
"e": 35773,
"s": 35740,
"text": "Following output UI is produced:"
},
{
"code": null,
"e": 35796,
"s": 35773,
"text": "Step 7: Same as Step 5"
},
{
"code": null,
"e": 35812,
"s": 35796,
"text": "Refer to Step 5"
},
{
"code": null,
"e": 35824,
"s": 35812,
"text": "aashaypawar"
},
{
"code": null,
"e": 35832,
"s": 35824,
"text": "android"
},
{
"code": null,
"e": 35840,
"s": 35832,
"text": "Android"
},
{
"code": null,
"e": 35845,
"s": 35840,
"text": "Java"
},
{
"code": null,
"e": 35850,
"s": 35845,
"text": "Java"
},
{
"code": null,
"e": 35858,
"s": 35850,
"text": "Android"
},
{
"code": null,
"e": 35956,
"s": 35858,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35994,
"s": 35956,
"text": "Resource Raw Folder in Android Studio"
},
{
"code": null,
"e": 36033,
"s": 35994,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 36083,
"s": 36033,
"text": "How to Read Data from SQLite Database in Android?"
},
{
"code": null,
"e": 36125,
"s": 36083,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 36176,
"s": 36125,
"text": "How to Post Data to API using Retrofit in Android?"
},
{
"code": null,
"e": 36191,
"s": 36176,
"text": "Arrays in Java"
},
{
"code": null,
"e": 36235,
"s": 36191,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 36257,
"s": 36235,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 36308,
"s": 36257,
"text": "Object Oriented Programming (OOPs) Concept in Java"
}
] |
Variability in R Programming - GeeksforGeeks | 10 May, 2020
Variability (also known as Statistical Dispersion) is another feature of descriptive statistics. Measures of central tendency and variability together comprise of descriptive statistics. Variability shows the spread of a data set around a point.
Example: Suppose, there exist 2 data sets with the same mean value:
A = 4, 4, 5, 6, 6Mean(A) = 5
B = 1, 1, 5, 9, 9Mean(B) = 5
So, to differentiate among the two data sets, R offers various measures of variability.
Following are some of the measures of variablity that R offers to differentiate between data sets:
Variance
Standard Deviation
Range
Mean Deviation
Interquartile Range
Variance is a measure that shows how far is each value from a particular point, preferably mean value. Mathematically, it is defined as the average of squared differences from the mean value.
Formula:
where,
specifies variance of the data set specifies value in data set specifies the mean of data setn specifies total number of observations
In the R language, there is a standard built-in function to calculate the variance of a data set.
Syntax: var(x)
Parameter:x: It is data vector
Example:
# Defining vectorx <- c(5, 5, 8, 12, 15, 16) # Print variance of xprint(var(x))
Output:
[1] 23.76667
Standard deviation in statistics measures the spreaness of data values with respect to mean and mathematically, is calculated as square root of variance.
Formula:
where,
specifies standard deviation of the data set specifies value in data set specifies the mean of data setn specifies total number of observations
In R language, there is no standard built-in function to calculate the standard deviation of a data set. So, modifying the code to find the standard deviation of data set.
Example:
# Defining vectorx <- c(5, 5, 8, 12, 15, 16) # Standard deviationd <- sqrt(var(x)) # Print standard deviation of xprint(d)
Output:
[1] 4.875107
Range is the difference between maximum and minimum value of a data set. In R language, max() and min() is used to find the same, unlike range() function that returns the minimum and maximum value of data set.
Example:
# Defining vectorx <- c(5, 5, 8, 12, 15, 16) # range() function outputprint(range(x)) # Using max() and min() function# to calculate the range of data setprint(max(x)-min(x))
Output:
[1] 5 16
[1] 11
Mean deviation is a measure calculated by taking an average of the arithmetic mean of the absolute difference of each value from the central value. Central value can be mean, median, or mode.
Formula:
where,
specifies value in data set specifies the mean of data setn specifies total number of observations
In R language, there is no standard built-in function to calculate mean deviation. So, modifying the code to find mean deviation of the data set.
Example:
# Defining vectorx <- c(5, 5, 8, 12, 15, 16) # Mean deviationmd <- sum(abs(x-mean(x)))/length(x) # Print mean deviationprint(md)
Output:
[1] 4.166667
Interquartile Range is based on splitting a data set into parts called as quartiles. There are 3 quartile values (Q1, Q2, Q3) that divide the whole data set into 4 equal parts. Q2 specifies the median of the whole data set.
Mathematically, the interquartile range is depicted as:
IQR = Q3 – Q1
where,
Q3 specifies the median of n largest valuesQ1 specifies the median of n smallest values
In R language, there is built-in function to calculate the interquartile range of data set.
Syntax: IQR(x)
Parameter:x: It specifies the data set
Example:
# Defining vectorx <- c(5, 5, 8, 12, 15, 16) # Print Interquartile rangeprint(IQR(x))
Output:
[1] 8.5
R-Statistics
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
How to import an Excel File into R ?
Time Series Analysis in R
R - if statement
How to filter R dataframe by multiple conditions? | [
{
"code": null,
"e": 26487,
"s": 26459,
"text": "\n10 May, 2020"
},
{
"code": null,
"e": 26733,
"s": 26487,
"text": "Variability (also known as Statistical Dispersion) is another feature of descriptive statistics. Measures of central tendency and variability together comprise of descriptive statistics. Variability shows the spread of a data set around a point."
},
{
"code": null,
"e": 26801,
"s": 26733,
"text": "Example: Suppose, there exist 2 data sets with the same mean value:"
},
{
"code": null,
"e": 26830,
"s": 26801,
"text": "A = 4, 4, 5, 6, 6Mean(A) = 5"
},
{
"code": null,
"e": 26859,
"s": 26830,
"text": "B = 1, 1, 5, 9, 9Mean(B) = 5"
},
{
"code": null,
"e": 26947,
"s": 26859,
"text": "So, to differentiate among the two data sets, R offers various measures of variability."
},
{
"code": null,
"e": 27046,
"s": 26947,
"text": "Following are some of the measures of variablity that R offers to differentiate between data sets:"
},
{
"code": null,
"e": 27055,
"s": 27046,
"text": "Variance"
},
{
"code": null,
"e": 27074,
"s": 27055,
"text": "Standard Deviation"
},
{
"code": null,
"e": 27080,
"s": 27074,
"text": "Range"
},
{
"code": null,
"e": 27095,
"s": 27080,
"text": "Mean Deviation"
},
{
"code": null,
"e": 27115,
"s": 27095,
"text": "Interquartile Range"
},
{
"code": null,
"e": 27307,
"s": 27115,
"text": "Variance is a measure that shows how far is each value from a particular point, preferably mean value. Mathematically, it is defined as the average of squared differences from the mean value."
},
{
"code": null,
"e": 27316,
"s": 27307,
"text": "Formula:"
},
{
"code": null,
"e": 27323,
"s": 27316,
"text": "where,"
},
{
"code": null,
"e": 27459,
"s": 27323,
"text": " specifies variance of the data set specifies value in data set specifies the mean of data setn specifies total number of observations"
},
{
"code": null,
"e": 27557,
"s": 27459,
"text": "In the R language, there is a standard built-in function to calculate the variance of a data set."
},
{
"code": null,
"e": 27572,
"s": 27557,
"text": "Syntax: var(x)"
},
{
"code": null,
"e": 27603,
"s": 27572,
"text": "Parameter:x: It is data vector"
},
{
"code": null,
"e": 27612,
"s": 27603,
"text": "Example:"
},
{
"code": "# Defining vectorx <- c(5, 5, 8, 12, 15, 16) # Print variance of xprint(var(x))",
"e": 27693,
"s": 27612,
"text": null
},
{
"code": null,
"e": 27701,
"s": 27693,
"text": "Output:"
},
{
"code": null,
"e": 27715,
"s": 27701,
"text": "[1] 23.76667\n"
},
{
"code": null,
"e": 27869,
"s": 27715,
"text": "Standard deviation in statistics measures the spreaness of data values with respect to mean and mathematically, is calculated as square root of variance."
},
{
"code": null,
"e": 27878,
"s": 27869,
"text": "Formula:"
},
{
"code": null,
"e": 27885,
"s": 27878,
"text": "where,"
},
{
"code": null,
"e": 28031,
"s": 27885,
"text": " specifies standard deviation of the data set specifies value in data set specifies the mean of data setn specifies total number of observations"
},
{
"code": null,
"e": 28203,
"s": 28031,
"text": "In R language, there is no standard built-in function to calculate the standard deviation of a data set. So, modifying the code to find the standard deviation of data set."
},
{
"code": null,
"e": 28212,
"s": 28203,
"text": "Example:"
},
{
"code": "# Defining vectorx <- c(5, 5, 8, 12, 15, 16) # Standard deviationd <- sqrt(var(x)) # Print standard deviation of xprint(d)",
"e": 28337,
"s": 28212,
"text": null
},
{
"code": null,
"e": 28345,
"s": 28337,
"text": "Output:"
},
{
"code": null,
"e": 28359,
"s": 28345,
"text": "[1] 4.875107\n"
},
{
"code": null,
"e": 28569,
"s": 28359,
"text": "Range is the difference between maximum and minimum value of a data set. In R language, max() and min() is used to find the same, unlike range() function that returns the minimum and maximum value of data set."
},
{
"code": null,
"e": 28578,
"s": 28569,
"text": "Example:"
},
{
"code": "# Defining vectorx <- c(5, 5, 8, 12, 15, 16) # range() function outputprint(range(x)) # Using max() and min() function# to calculate the range of data setprint(max(x)-min(x))",
"e": 28755,
"s": 28578,
"text": null
},
{
"code": null,
"e": 28763,
"s": 28755,
"text": "Output:"
},
{
"code": null,
"e": 28781,
"s": 28763,
"text": "[1] 5 16\n[1] 11\n"
},
{
"code": null,
"e": 28973,
"s": 28781,
"text": "Mean deviation is a measure calculated by taking an average of the arithmetic mean of the absolute difference of each value from the central value. Central value can be mean, median, or mode."
},
{
"code": null,
"e": 28982,
"s": 28973,
"text": "Formula:"
},
{
"code": null,
"e": 28989,
"s": 28982,
"text": "where,"
},
{
"code": null,
"e": 29090,
"s": 28989,
"text": " specifies value in data set specifies the mean of data setn specifies total number of observations"
},
{
"code": null,
"e": 29236,
"s": 29090,
"text": "In R language, there is no standard built-in function to calculate mean deviation. So, modifying the code to find mean deviation of the data set."
},
{
"code": null,
"e": 29245,
"s": 29236,
"text": "Example:"
},
{
"code": "# Defining vectorx <- c(5, 5, 8, 12, 15, 16) # Mean deviationmd <- sum(abs(x-mean(x)))/length(x) # Print mean deviationprint(md)",
"e": 29376,
"s": 29245,
"text": null
},
{
"code": null,
"e": 29384,
"s": 29376,
"text": "Output:"
},
{
"code": null,
"e": 29398,
"s": 29384,
"text": "[1] 4.166667\n"
},
{
"code": null,
"e": 29622,
"s": 29398,
"text": "Interquartile Range is based on splitting a data set into parts called as quartiles. There are 3 quartile values (Q1, Q2, Q3) that divide the whole data set into 4 equal parts. Q2 specifies the median of the whole data set."
},
{
"code": null,
"e": 29678,
"s": 29622,
"text": "Mathematically, the interquartile range is depicted as:"
},
{
"code": null,
"e": 29692,
"s": 29678,
"text": "IQR = Q3 – Q1"
},
{
"code": null,
"e": 29699,
"s": 29692,
"text": "where,"
},
{
"code": null,
"e": 29787,
"s": 29699,
"text": "Q3 specifies the median of n largest valuesQ1 specifies the median of n smallest values"
},
{
"code": null,
"e": 29879,
"s": 29787,
"text": "In R language, there is built-in function to calculate the interquartile range of data set."
},
{
"code": null,
"e": 29894,
"s": 29879,
"text": "Syntax: IQR(x)"
},
{
"code": null,
"e": 29933,
"s": 29894,
"text": "Parameter:x: It specifies the data set"
},
{
"code": null,
"e": 29942,
"s": 29933,
"text": "Example:"
},
{
"code": "# Defining vectorx <- c(5, 5, 8, 12, 15, 16) # Print Interquartile rangeprint(IQR(x))",
"e": 30029,
"s": 29942,
"text": null
},
{
"code": null,
"e": 30037,
"s": 30029,
"text": "Output:"
},
{
"code": null,
"e": 30046,
"s": 30037,
"text": "[1] 8.5\n"
},
{
"code": null,
"e": 30059,
"s": 30046,
"text": "R-Statistics"
},
{
"code": null,
"e": 30070,
"s": 30059,
"text": "R Language"
},
{
"code": null,
"e": 30168,
"s": 30070,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30220,
"s": 30168,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 30255,
"s": 30220,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 30293,
"s": 30255,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 30351,
"s": 30293,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 30394,
"s": 30351,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 30443,
"s": 30394,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 30480,
"s": 30443,
"text": "How to import an Excel File into R ?"
},
{
"code": null,
"e": 30506,
"s": 30480,
"text": "Time Series Analysis in R"
},
{
"code": null,
"e": 30523,
"s": 30506,
"text": "R - if statement"
}
] |
Find the missing digit x from the given expression | 06 May, 2022
Given an alphanumeric string, consisting of a single alphabet X, which represents an expression of the form:
A operator B = C where A, B and C denotes integers and the operator can be either of +, -, * or /
The task is to evaluate the missing digit X present in any of the integers A, B and C such that the given expression holds to be valid.
Examples:
Input: S = “3x + 12 = 46”Output: 4Explanation:If we subtract 12 from 46, we will get 34.So, on comparing 3x and 34. the value of x = 4
Input: S = “4 – 2 = x”Output: 2Explanation:After solving the equation, the value of x = 2.
Approach: Follow the steps below to solve the problem:
Split the string to extract the two operands, operator and the resultant.
Check if X is present in the resultant or not. If so, then compute the value of the resultant by applying operations on the first operand and second operand with the operator.
Otherwise, if X is not present in the resultant. Then check if X is present in the first operand. If so, then apply the operation on the second operand and resultant with the operator.
Otherwise, if X is not present in the first operand also. Then check if X is present in the second operand. If so, then apply the operation on the first operand and resultant with the operator.
Below is the implementation of the above approach:
Python3
Javascript
# Python3 program to find missing# digit x in expression def MissingDigit(exp): # Split the expression to # extract operands, operator # and resultant exp = list(exp.split()) first_operand = exp[0] operator = exp[1] second_operand = exp[2] resultant = exp[-1] # If x is present in resultant if 'x' in resultant: x = resultant first_operand = int(first_operand) second_operand = int(second_operand) if operator == '+': res = first_operand + second_operand elif operator == '-': res = first_operand - second_operand elif operator == '*': res = first_operand * second_operand else: res = first_operand // second_operand # If x in present in operands else: resultant = int(resultant) # If x in the first operand if 'x' in first_operand: x = first_operand second_operand = int(second_operand) if operator == '+': res = resultant - second_operand elif operator == '-': res = resultant + second_operand elif operator == '*': res = resultant // second_operand else: res = resultant * second_operand # If x is in the second operand else: x = second_operand first_operand = int(first_operand) if operator == '+': res = resultant-first_operand elif operator == '-': res = first_operand - resultant elif operator == '*': res = resultant // first_operand else: res = first_operand // resultant res = str(res) k = 0 for i in x: if i == 'x': result = res[k] break else: k = k + 1 return result # Driver Codeif __name__ == '__main__': # input expression exp = "3x + 12 = 46" print(MissingDigit(exp))
<script> // JavaScript program to find missing// digit x in expression let res = 0,x;let result = ""; function MissingDigit(exp){ // Split the expression to // extract operands, operator // and resultant exp = exp.split(' ') let first_operand = exp[0] let operator = exp[1] let second_operand = exp[2] let resultant = exp[exp.length-1] // If x is present in resultant if(resultant.indexOf('x') != -1){ x = resultant first_operand = parseInt(first_operand) second_operand = parseInt(second_operand) if(operator == '+') res = first_operand + second_operand else if(operator == '-') res = first_operand - second_operand else if(operator == '*') res = first_operand * second_operand else res = Math.floor(first_operand / second_operand) } // If x in present in operands else{ resultant = parseInt(resultant) // If x in the first operand if(first_operand.indexOf('x') != -1){ x = first_operand second_operand = parseInt(second_operand) if(operator == '+') res = resultant - second_operand else if(operator == '-') res = resultant + second_operand else if(operator == '*') res = Math.floor(resultant / second_operand) else res = resultant * second_operand } // If x is in the second operand else{ let x = second_operand first_operand = parseInt(first_operand) if(operator == '+') res = resultant-first_operand else if(operator == '-') res = first_operand - resultant else if(operator == '*') res = Math.floor(resultant / first_operand) else res = Math.floor(first_operand / resultant) } } res = res.toString() let k = 0 for(let i of x){ if(i == 'x'){ result = res[k] break } else k = k + 1 } return result} // Driver Code // input expressionlet exp = "3x + 12 = 46" document.write(MissingDigit(exp)) // This code is contributed by shinjanpatra </script>
4
Time Complexity: O(L), where is the length of the equation.Auxiliary Space: O(1)
shinjanpatra
Mathematical
School Programming
Searching
Strings
Searching
Strings
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Operators in C / C++
Sieve of Eratosthenes
Prime Numbers
Program to find GCD or HCF of two numbers
Python Dictionary
Reverse a string in Java
Arrays in C/C++
Introduction To PYTHON
Interfaces in Java | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n06 May, 2022"
},
{
"code": null,
"e": 161,
"s": 52,
"text": "Given an alphanumeric string, consisting of a single alphabet X, which represents an expression of the form:"
},
{
"code": null,
"e": 259,
"s": 161,
"text": "A operator B = C where A, B and C denotes integers and the operator can be either of +, -, * or /"
},
{
"code": null,
"e": 395,
"s": 259,
"text": "The task is to evaluate the missing digit X present in any of the integers A, B and C such that the given expression holds to be valid."
},
{
"code": null,
"e": 405,
"s": 395,
"text": "Examples:"
},
{
"code": null,
"e": 540,
"s": 405,
"text": "Input: S = “3x + 12 = 46”Output: 4Explanation:If we subtract 12 from 46, we will get 34.So, on comparing 3x and 34. the value of x = 4"
},
{
"code": null,
"e": 631,
"s": 540,
"text": "Input: S = “4 – 2 = x”Output: 2Explanation:After solving the equation, the value of x = 2."
},
{
"code": null,
"e": 686,
"s": 631,
"text": "Approach: Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 760,
"s": 686,
"text": "Split the string to extract the two operands, operator and the resultant."
},
{
"code": null,
"e": 936,
"s": 760,
"text": "Check if X is present in the resultant or not. If so, then compute the value of the resultant by applying operations on the first operand and second operand with the operator."
},
{
"code": null,
"e": 1121,
"s": 936,
"text": "Otherwise, if X is not present in the resultant. Then check if X is present in the first operand. If so, then apply the operation on the second operand and resultant with the operator."
},
{
"code": null,
"e": 1315,
"s": 1121,
"text": "Otherwise, if X is not present in the first operand also. Then check if X is present in the second operand. If so, then apply the operation on the first operand and resultant with the operator."
},
{
"code": null,
"e": 1366,
"s": 1315,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 1374,
"s": 1366,
"text": "Python3"
},
{
"code": null,
"e": 1385,
"s": 1374,
"text": "Javascript"
},
{
"code": "# Python3 program to find missing# digit x in expression def MissingDigit(exp): # Split the expression to # extract operands, operator # and resultant exp = list(exp.split()) first_operand = exp[0] operator = exp[1] second_operand = exp[2] resultant = exp[-1] # If x is present in resultant if 'x' in resultant: x = resultant first_operand = int(first_operand) second_operand = int(second_operand) if operator == '+': res = first_operand + second_operand elif operator == '-': res = first_operand - second_operand elif operator == '*': res = first_operand * second_operand else: res = first_operand // second_operand # If x in present in operands else: resultant = int(resultant) # If x in the first operand if 'x' in first_operand: x = first_operand second_operand = int(second_operand) if operator == '+': res = resultant - second_operand elif operator == '-': res = resultant + second_operand elif operator == '*': res = resultant // second_operand else: res = resultant * second_operand # If x is in the second operand else: x = second_operand first_operand = int(first_operand) if operator == '+': res = resultant-first_operand elif operator == '-': res = first_operand - resultant elif operator == '*': res = resultant // first_operand else: res = first_operand // resultant res = str(res) k = 0 for i in x: if i == 'x': result = res[k] break else: k = k + 1 return result # Driver Codeif __name__ == '__main__': # input expression exp = \"3x + 12 = 46\" print(MissingDigit(exp))",
"e": 3373,
"s": 1385,
"text": null
},
{
"code": "<script> // JavaScript program to find missing// digit x in expression let res = 0,x;let result = \"\"; function MissingDigit(exp){ // Split the expression to // extract operands, operator // and resultant exp = exp.split(' ') let first_operand = exp[0] let operator = exp[1] let second_operand = exp[2] let resultant = exp[exp.length-1] // If x is present in resultant if(resultant.indexOf('x') != -1){ x = resultant first_operand = parseInt(first_operand) second_operand = parseInt(second_operand) if(operator == '+') res = first_operand + second_operand else if(operator == '-') res = first_operand - second_operand else if(operator == '*') res = first_operand * second_operand else res = Math.floor(first_operand / second_operand) } // If x in present in operands else{ resultant = parseInt(resultant) // If x in the first operand if(first_operand.indexOf('x') != -1){ x = first_operand second_operand = parseInt(second_operand) if(operator == '+') res = resultant - second_operand else if(operator == '-') res = resultant + second_operand else if(operator == '*') res = Math.floor(resultant / second_operand) else res = resultant * second_operand } // If x is in the second operand else{ let x = second_operand first_operand = parseInt(first_operand) if(operator == '+') res = resultant-first_operand else if(operator == '-') res = first_operand - resultant else if(operator == '*') res = Math.floor(resultant / first_operand) else res = Math.floor(first_operand / resultant) } } res = res.toString() let k = 0 for(let i of x){ if(i == 'x'){ result = res[k] break } else k = k + 1 } return result} // Driver Code // input expressionlet exp = \"3x + 12 = 46\" document.write(MissingDigit(exp)) // This code is contributed by shinjanpatra </script>",
"e": 5648,
"s": 3373,
"text": null
},
{
"code": null,
"e": 5650,
"s": 5648,
"text": "4"
},
{
"code": null,
"e": 5731,
"s": 5650,
"text": "Time Complexity: O(L), where is the length of the equation.Auxiliary Space: O(1)"
},
{
"code": null,
"e": 5744,
"s": 5731,
"text": "shinjanpatra"
},
{
"code": null,
"e": 5757,
"s": 5744,
"text": "Mathematical"
},
{
"code": null,
"e": 5776,
"s": 5757,
"text": "School Programming"
},
{
"code": null,
"e": 5786,
"s": 5776,
"text": "Searching"
},
{
"code": null,
"e": 5794,
"s": 5786,
"text": "Strings"
},
{
"code": null,
"e": 5804,
"s": 5794,
"text": "Searching"
},
{
"code": null,
"e": 5812,
"s": 5804,
"text": "Strings"
},
{
"code": null,
"e": 5825,
"s": 5812,
"text": "Mathematical"
},
{
"code": null,
"e": 5923,
"s": 5825,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5947,
"s": 5923,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 5968,
"s": 5947,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 5990,
"s": 5968,
"text": "Sieve of Eratosthenes"
},
{
"code": null,
"e": 6004,
"s": 5990,
"text": "Prime Numbers"
},
{
"code": null,
"e": 6046,
"s": 6004,
"text": "Program to find GCD or HCF of two numbers"
},
{
"code": null,
"e": 6064,
"s": 6046,
"text": "Python Dictionary"
},
{
"code": null,
"e": 6089,
"s": 6064,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 6105,
"s": 6089,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 6128,
"s": 6105,
"text": "Introduction To PYTHON"
}
] |
Working with Headers And Footers in Python .docx Module | 08 Mar, 2022
Prerequisite: Working with .docx module
Word documents contain formatted text wrapped within three object levels. The Lowest level-run objects, middle level-paragraph objects, and highest level-document objects. So, we cannot work with these documents using normal text editors. But, we can manipulate these word documents in python using the python-docx module. Pip command to install this module is:
pip install python-docx
Python docx module allows users to manipulate docs by either manipulating the existing one or creating a new empty document and manipulating it. It is a powerful tool as it helps you to manipulate the document to a very large extend. Both header and footer are a part of a section so that each section can have a different header and footer. The header is an important part of the document as it contains important information regarding the document which the publisher wants to display on each page.
A header object is always present on the top of the section or page and can be called by the use of section.header. Each new header contains an empty paragraph and it can be edited like the rest of the document. To add content we use the .text method of the paragraph.
Example 1: Adding a header in the Word document.
Python3
# Import docx NOT python-docximport docx # Create an instance of a word documentdoc = docx.Document() # Choosing the top most section of the pagesection = doc.sections[0] # Calling the headerheader = section.header # Calling the paragraph already present in# the header sectionheader_para = header.paragraphs[0] # Adding text in the headerheader_para.text = "This is a header..." # Add a Title to the documentdoc.add_heading('GeeksForGeeks', 0) # Now save the document to a locationdoc.save('gfg.docx')
Output:
By using this module you can also add a zoned header in the Word document. To add a zoned header we use tabs i.e ‘\t‘. There are three zones left, Centre and right. The text is by default in zone left, if we use a single ‘\t‘ on the text then it will shift to the center zone and with one more ‘\t‘ to the right zone respectively.
Example 2: Adding a left zoned header to a Word document.
Python3
# Import docx NOT python-docximport docx # Create an instance of a word documentdoc = docx.Document() # Choosing the top most section of the pagesection = doc.sections[0] # Selecting the headerheader = section.header # Selecting the paragraph already present in# the header sectionheader_para = header.paragraphs[0] # Adding the left zoned headerheader_para.text = "This is Left Zoned Header..." # Add a Title to the documentdoc.add_heading('GeeksForGeeks', 0) # Now save the document to a locationdoc.save('gfg.docx')
Output:
Example 3: Adding a centered zoned header to a Word document.
Python3
# Import docx NOT python-docximport docx # Create an instance of a word documentdoc = docx.Document() # Choosing the top most section of the pagesection = doc.sections[0] # Selecting the headerheader = section.header # Selecting the paragraph already present in# the header sectionheader_para = header.paragraphs[0] # Adding the centred zoned headerheader_para.text = "\tThis is Centred Zoned Header..." # Add a Title to the documentdoc.add_heading('GeeksForGeeks', 0) # Now save the document to a locationdoc.save('gfg.docx')
Output:
Example 4: Adding a right zoned header to a Word document.
Python3
# Import docx NOT python-docximport docx # Create an instance of a word documentdoc = docx.Document() # Choosing the top most section of the pagesection = doc.sections[0] # Selecting the headerheader = section.header # Selecting the paragraph already present in# the header sectionheader_para = header.paragraphs[0] # Adding the right zoned headerheader_para.text = "\t\tThis is Right Zoned Header..." # Add a Title to the documentdoc.add_heading('GeeksForGeeks', 0) # Now save the document to a locationdoc.save('gfg.docx')
Output:
A footer object is always present at the bottom of the section or page and can be called by the use of section.footer. Each new footer contains an empty paragraph and it can be edited like the rest of the document. To add content we make use of the .text method of the paragraph.
Example 1: Adding a footer to a Word document.
Python3
# Import docx NOT python-docximport docx # Create an instance of a word documentdoc = docx.Document() # Choosing the top most section of the pagesection = doc.sections[0] # Calling the footerfooter = section.footer # Calling the paragraph already present in# the footer sectionfooter_para = footer.paragraphs[0] # Adding text in the footerfooter_para.text = "This is a footer..." # Add a Title to the documentdoc.add_heading('GeeksForGeeks', 0) # Now save the document to a locationdoc.save('gfg.docx')
Output:
To add a zoned footer we will use tabs i.e ‘\t‘. There are three zones left, Centre and right. The text is by default in zone left, if we use single ‘\t‘ on the text then it will shift to the center zone and with one more ‘\t‘ to the right zone respectively.
Example 2: Adding a left zoned footer to a Word document.
Python3
# Import docx NOT python-docximport docx # Create an instance of a word documentdoc = docx.Document() # Choosing the top most section of the pagesection = doc.sections[0] # Calling the footerfooter = section.footer # Calling the paragraph already present in# the footer sectionfooter_para = footer.paragraphs[0] # Adding the left zoned footerfooter_para.text = "This is the left zoned footer..." # Add a Title to the documentdoc.add_heading('GeeksForGeeks', 0) # Now save the document to a locationdoc.save('gfg.docx')
Output:
Example 3: Adding a center zoned footer to a Word document.
Python3
# Import docx NOT python-docximport docx # Create an instance of a word documentdoc = docx.Document() # Choosing the top most section of the pagesection = doc.sections[0] # Calling the footerfooter = section.footer # Calling the paragraph already present in# the footer sectionfooter_para = footer.paragraphs[0] # Adding the centered zoned footerfooter_para.text = "\tThis is the centered zoned footer..." # Add a Title to the documentdoc.add_heading('GeeksForGeeks', 0) # Now save the document to a locationdoc.save('gfg.docx')
Output:
Example 4: Adding a right zoned footer to a Word document.
Python3
# Import docx NOT python-docximport docx # Create an instance of a word documentdoc = docx.Document() # Choosing the top most section of the pagesection = doc.sections[0] # Calling the footerfooter = section.footer # Calling the paragraph already present in# the footer sectionfooter_para = footer.paragraphs[0] # Adding the right zoned footerfooter_para.text = "\t\tThis is the right zoned footer..." # Add a Title to the documentdoc.add_heading('GeeksForGeeks', 0) # Now save the document to a locationdoc.save('gfg.docx')
Output:
anikakapoor
sagar0719kumar
kothavvsaakash
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Convert integer to string in Python
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n08 Mar, 2022"
},
{
"code": null,
"e": 93,
"s": 53,
"text": "Prerequisite: Working with .docx module"
},
{
"code": null,
"e": 455,
"s": 93,
"text": "Word documents contain formatted text wrapped within three object levels. The Lowest level-run objects, middle level-paragraph objects, and highest level-document objects. So, we cannot work with these documents using normal text editors. But, we can manipulate these word documents in python using the python-docx module. Pip command to install this module is:"
},
{
"code": null,
"e": 479,
"s": 455,
"text": "pip install python-docx"
},
{
"code": null,
"e": 980,
"s": 479,
"text": "Python docx module allows users to manipulate docs by either manipulating the existing one or creating a new empty document and manipulating it. It is a powerful tool as it helps you to manipulate the document to a very large extend. Both header and footer are a part of a section so that each section can have a different header and footer. The header is an important part of the document as it contains important information regarding the document which the publisher wants to display on each page."
},
{
"code": null,
"e": 1249,
"s": 980,
"text": "A header object is always present on the top of the section or page and can be called by the use of section.header. Each new header contains an empty paragraph and it can be edited like the rest of the document. To add content we use the .text method of the paragraph."
},
{
"code": null,
"e": 1298,
"s": 1249,
"text": "Example 1: Adding a header in the Word document."
},
{
"code": null,
"e": 1306,
"s": 1298,
"text": "Python3"
},
{
"code": "# Import docx NOT python-docximport docx # Create an instance of a word documentdoc = docx.Document() # Choosing the top most section of the pagesection = doc.sections[0] # Calling the headerheader = section.header # Calling the paragraph already present in# the header sectionheader_para = header.paragraphs[0] # Adding text in the headerheader_para.text = \"This is a header...\" # Add a Title to the documentdoc.add_heading('GeeksForGeeks', 0) # Now save the document to a locationdoc.save('gfg.docx')",
"e": 1809,
"s": 1306,
"text": null
},
{
"code": null,
"e": 1819,
"s": 1809,
"text": " Output:"
},
{
"code": null,
"e": 2150,
"s": 1819,
"text": "By using this module you can also add a zoned header in the Word document. To add a zoned header we use tabs i.e ‘\\t‘. There are three zones left, Centre and right. The text is by default in zone left, if we use a single ‘\\t‘ on the text then it will shift to the center zone and with one more ‘\\t‘ to the right zone respectively."
},
{
"code": null,
"e": 2210,
"s": 2152,
"text": "Example 2: Adding a left zoned header to a Word document."
},
{
"code": null,
"e": 2218,
"s": 2210,
"text": "Python3"
},
{
"code": "# Import docx NOT python-docximport docx # Create an instance of a word documentdoc = docx.Document() # Choosing the top most section of the pagesection = doc.sections[0] # Selecting the headerheader = section.header # Selecting the paragraph already present in# the header sectionheader_para = header.paragraphs[0] # Adding the left zoned headerheader_para.text = \"This is Left Zoned Header...\" # Add a Title to the documentdoc.add_heading('GeeksForGeeks', 0) # Now save the document to a locationdoc.save('gfg.docx')",
"e": 2737,
"s": 2218,
"text": null
},
{
"code": null,
"e": 2745,
"s": 2737,
"text": "Output:"
},
{
"code": null,
"e": 2809,
"s": 2747,
"text": "Example 3: Adding a centered zoned header to a Word document."
},
{
"code": null,
"e": 2817,
"s": 2809,
"text": "Python3"
},
{
"code": "# Import docx NOT python-docximport docx # Create an instance of a word documentdoc = docx.Document() # Choosing the top most section of the pagesection = doc.sections[0] # Selecting the headerheader = section.header # Selecting the paragraph already present in# the header sectionheader_para = header.paragraphs[0] # Adding the centred zoned headerheader_para.text = \"\\tThis is Centred Zoned Header...\" # Add a Title to the documentdoc.add_heading('GeeksForGeeks', 0) # Now save the document to a locationdoc.save('gfg.docx')",
"e": 3344,
"s": 2817,
"text": null
},
{
"code": null,
"e": 3354,
"s": 3346,
"text": "Output:"
},
{
"code": null,
"e": 3413,
"s": 3354,
"text": "Example 4: Adding a right zoned header to a Word document."
},
{
"code": null,
"e": 3423,
"s": 3415,
"text": "Python3"
},
{
"code": "# Import docx NOT python-docximport docx # Create an instance of a word documentdoc = docx.Document() # Choosing the top most section of the pagesection = doc.sections[0] # Selecting the headerheader = section.header # Selecting the paragraph already present in# the header sectionheader_para = header.paragraphs[0] # Adding the right zoned headerheader_para.text = \"\\t\\tThis is Right Zoned Header...\" # Add a Title to the documentdoc.add_heading('GeeksForGeeks', 0) # Now save the document to a locationdoc.save('gfg.docx')",
"e": 3948,
"s": 3423,
"text": null
},
{
"code": null,
"e": 3956,
"s": 3948,
"text": "Output:"
},
{
"code": null,
"e": 4236,
"s": 3956,
"text": "A footer object is always present at the bottom of the section or page and can be called by the use of section.footer. Each new footer contains an empty paragraph and it can be edited like the rest of the document. To add content we make use of the .text method of the paragraph."
},
{
"code": null,
"e": 4283,
"s": 4236,
"text": "Example 1: Adding a footer to a Word document."
},
{
"code": null,
"e": 4291,
"s": 4283,
"text": "Python3"
},
{
"code": "# Import docx NOT python-docximport docx # Create an instance of a word documentdoc = docx.Document() # Choosing the top most section of the pagesection = doc.sections[0] # Calling the footerfooter = section.footer # Calling the paragraph already present in# the footer sectionfooter_para = footer.paragraphs[0] # Adding text in the footerfooter_para.text = \"This is a footer...\" # Add a Title to the documentdoc.add_heading('GeeksForGeeks', 0) # Now save the document to a locationdoc.save('gfg.docx')",
"e": 4794,
"s": 4291,
"text": null
},
{
"code": null,
"e": 4802,
"s": 4794,
"text": "Output:"
},
{
"code": null,
"e": 5061,
"s": 4802,
"text": "To add a zoned footer we will use tabs i.e ‘\\t‘. There are three zones left, Centre and right. The text is by default in zone left, if we use single ‘\\t‘ on the text then it will shift to the center zone and with one more ‘\\t‘ to the right zone respectively."
},
{
"code": null,
"e": 5121,
"s": 5063,
"text": "Example 2: Adding a left zoned footer to a Word document."
},
{
"code": null,
"e": 5129,
"s": 5121,
"text": "Python3"
},
{
"code": "# Import docx NOT python-docximport docx # Create an instance of a word documentdoc = docx.Document() # Choosing the top most section of the pagesection = doc.sections[0] # Calling the footerfooter = section.footer # Calling the paragraph already present in# the footer sectionfooter_para = footer.paragraphs[0] # Adding the left zoned footerfooter_para.text = \"This is the left zoned footer...\" # Add a Title to the documentdoc.add_heading('GeeksForGeeks', 0) # Now save the document to a locationdoc.save('gfg.docx')",
"e": 5648,
"s": 5129,
"text": null
},
{
"code": null,
"e": 5659,
"s": 5651,
"text": "Output:"
},
{
"code": null,
"e": 5725,
"s": 5665,
"text": "Example 3: Adding a center zoned footer to a Word document."
},
{
"code": null,
"e": 5735,
"s": 5727,
"text": "Python3"
},
{
"code": "# Import docx NOT python-docximport docx # Create an instance of a word documentdoc = docx.Document() # Choosing the top most section of the pagesection = doc.sections[0] # Calling the footerfooter = section.footer # Calling the paragraph already present in# the footer sectionfooter_para = footer.paragraphs[0] # Adding the centered zoned footerfooter_para.text = \"\\tThis is the centered zoned footer...\" # Add a Title to the documentdoc.add_heading('GeeksForGeeks', 0) # Now save the document to a locationdoc.save('gfg.docx')",
"e": 6264,
"s": 5735,
"text": null
},
{
"code": null,
"e": 6275,
"s": 6267,
"text": "Output:"
},
{
"code": null,
"e": 6336,
"s": 6277,
"text": "Example 4: Adding a right zoned footer to a Word document."
},
{
"code": null,
"e": 6346,
"s": 6338,
"text": "Python3"
},
{
"code": "# Import docx NOT python-docximport docx # Create an instance of a word documentdoc = docx.Document() # Choosing the top most section of the pagesection = doc.sections[0] # Calling the footerfooter = section.footer # Calling the paragraph already present in# the footer sectionfooter_para = footer.paragraphs[0] # Adding the right zoned footerfooter_para.text = \"\\t\\tThis is the right zoned footer...\" # Add a Title to the documentdoc.add_heading('GeeksForGeeks', 0) # Now save the document to a locationdoc.save('gfg.docx')",
"e": 6871,
"s": 6346,
"text": null
},
{
"code": null,
"e": 6882,
"s": 6874,
"text": "Output:"
},
{
"code": null,
"e": 6898,
"s": 6886,
"text": "anikakapoor"
},
{
"code": null,
"e": 6913,
"s": 6898,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 6928,
"s": 6913,
"text": "kothavvsaakash"
},
{
"code": null,
"e": 6952,
"s": 6928,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 6959,
"s": 6952,
"text": "Python"
},
{
"code": null,
"e": 6978,
"s": 6959,
"text": "Technical Scripter"
},
{
"code": null,
"e": 7076,
"s": 6978,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7094,
"s": 7076,
"text": "Python Dictionary"
},
{
"code": null,
"e": 7136,
"s": 7094,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 7158,
"s": 7136,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 7190,
"s": 7158,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 7219,
"s": 7190,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 7246,
"s": 7219,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 7267,
"s": 7246,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 7303,
"s": 7267,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 7326,
"s": 7303,
"text": "Introduction To PYTHON"
}
] |
C# SingleorDefault() Method | The method returns a single specific element of a sequence. If the element is not present in the sequence, then the default value is returned.
We have two string arrays here.
string[] str1 = { "one" };
string[] str2 = { };
First array is checked for a single element, whereas the second array is empty and checked using SingleorDefault.
str2.AsQueryable().SingleOrDefault();
The following is an example showing the usage of SingleorDefault() method.
Live Demo
using System;
using System.Linq;
using System.Collections.Generic;
public class Demo {
public static void Main() {
string[] str1 = { "one" };
string[] str2 = { };
string res1 = str1.AsQueryable().Single();
Console.WriteLine("String found: "+res1);
string res2 = str2.AsQueryable().SingleOrDefault();
Console.WriteLine(String.IsNullOrEmpty(res2) ? "String not found" : res2);
}
}
String found: one
String not found | [
{
"code": null,
"e": 1330,
"s": 1187,
"text": "The method returns a single specific element of a sequence. If the element is not present in the sequence, then the default value is returned."
},
{
"code": null,
"e": 1362,
"s": 1330,
"text": "We have two string arrays here."
},
{
"code": null,
"e": 1410,
"s": 1362,
"text": "string[] str1 = { \"one\" };\nstring[] str2 = { };"
},
{
"code": null,
"e": 1524,
"s": 1410,
"text": "First array is checked for a single element, whereas the second array is empty and checked using SingleorDefault."
},
{
"code": null,
"e": 1562,
"s": 1524,
"text": "str2.AsQueryable().SingleOrDefault();"
},
{
"code": null,
"e": 1637,
"s": 1562,
"text": "The following is an example showing the usage of SingleorDefault() method."
},
{
"code": null,
"e": 1648,
"s": 1637,
"text": " Live Demo"
},
{
"code": null,
"e": 2069,
"s": 1648,
"text": "using System;\nusing System.Linq;\nusing System.Collections.Generic;\npublic class Demo {\n public static void Main() {\n string[] str1 = { \"one\" };\n string[] str2 = { };\n string res1 = str1.AsQueryable().Single();\n Console.WriteLine(\"String found: \"+res1);\n string res2 = str2.AsQueryable().SingleOrDefault();\n Console.WriteLine(String.IsNullOrEmpty(res2) ? \"String not found\" : res2);\n }\n}"
},
{
"code": null,
"e": 2104,
"s": 2069,
"text": "String found: one\nString not found"
}
] |
max_element in C++ | 11 Jun, 2022
We have std::max to find maximum of 2 or more elements, but what if we want to find the largest element in an array or vector or list or in a sub-section. To serve this purpose, we have std::max_element in C++. std::max_element is defined inside the header file and it returns an iterator pointing to the element with the largest value in the range [first, last). std::max_element can be used in two ways. The comparisons can be performed either usingoperator < (first version), or using a pre-defined function (second version). If more than one element satisfies the condition of being the largest, the iterator returned points to the first of such elements.
The two versions are defined as given below:
For comparing elements using “<“:
For comparing elements using “<“:
Syntax:
template
ForwardIterator max_element (ForwardIterator first, ForwardIterator last);
first: Forward iterator pointing to the beginning of the range.
last: Forward iterator pointing to the end of the range.
Return Value: It returns a pointer to the largest
element in the range, and in case if there are more than
one such element, then it points to the first one.
It points to the last in case the range is empty.
CPP
// C++ program to demonstrate the use of std::max_element#include <iostream>#include <algorithm>using namespace std;int main(){ int v[] = { 'a', 'c', 'k', 'd', 'e', 'f', 'h' }; // Finding the maximum value between the first and the // fourth element int* i1; i1 = std::max_element(v, v + 4); cout << char(*i1) << "\n"; return 0;}
k
Time Complexity: O(n)
Auxiliary Space: O(1)
2. For comparison based on a pre-defined function:
Syntax:
template
ForwardIterator max_element (ForwardIterator first, ForwardIterator last,
Compare comp);
Here, first and last are the same as previous case.
comp: Binary function that accepts two elements
in the range as arguments, and returns a value convertible to bool.
The value returned indicates whether the element passed as first argument
is considered less than the second.
The function shall not modify any of its arguments.
This can either be a function pointer or a function object.
Return Value: It returns a pointer to the largest element
in the range, and in case if there are more than one such element,
then it points to the first one.
It points to the last in case the range is empty.
CPP
// C++ program to demonstrate the use of std::max_element#include <iostream>#include <algorithm>using namespace std; // Defining the BinaryFunctionbool comp(int a, int b){ return (a < b);} int main(){ int v[] = { 9, 4, 7, 2, 5, 10, 11, 12, 1, 3, 6 }; // Finding the maximum value between the third and the // ninth element int* i1; i1 = std::max_element(v + 2, v + 9, comp); cout << *i1 << "\n"; return 0;}
Output:
12
Time complexity: O(n)
Auxiliary Space: O(1)
Related Articles:
std::max
std::min
std::equal
std::min_element in C++
This article is contributed by Mrigendra Singh. 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.
surbhikumaridav
cpp-algorithm-library
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Bitwise Operators in C/C++
Set in C++ Standard Template Library (STL)
unordered_map in C++ STL
Inheritance in C++
vector erase() and clear() in C++
Substring in C++
C++ Classes and Objects
Object Oriented Programming in C++
Priority Queue in C++ Standard Template Library (STL)
Sorting a vector in C++ | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n11 Jun, 2022"
},
{
"code": null,
"e": 715,
"s": 54,
"text": "We have std::max to find maximum of 2 or more elements, but what if we want to find the largest element in an array or vector or list or in a sub-section. To serve this purpose, we have std::max_element in C++. std::max_element is defined inside the header file and it returns an iterator pointing to the element with the largest value in the range [first, last). std::max_element can be used in two ways. The comparisons can be performed either usingoperator < (first version), or using a pre-defined function (second version). If more than one element satisfies the condition of being the largest, the iterator returned points to the first of such elements. "
},
{
"code": null,
"e": 760,
"s": 715,
"text": "The two versions are defined as given below:"
},
{
"code": null,
"e": 795,
"s": 760,
"text": "For comparing elements using “<“: "
},
{
"code": null,
"e": 830,
"s": 795,
"text": "For comparing elements using “<“: "
},
{
"code": null,
"e": 850,
"s": 830,
"text": " Syntax:"
},
{
"code": null,
"e": 1313,
"s": 850,
"text": " template \n ForwardIterator max_element (ForwardIterator first, ForwardIterator last);\n\n first: Forward iterator pointing to the beginning of the range.\n last: Forward iterator pointing to the end of the range.\n\n Return Value: It returns a pointer to the largest \n element in the range, and in case if there are more than \n one such element, then it points to the first one.\n\n It points to the last in case the range is empty."
},
{
"code": null,
"e": 1317,
"s": 1313,
"text": "CPP"
},
{
"code": "// C++ program to demonstrate the use of std::max_element#include <iostream>#include <algorithm>using namespace std;int main(){ int v[] = { 'a', 'c', 'k', 'd', 'e', 'f', 'h' }; // Finding the maximum value between the first and the // fourth element int* i1; i1 = std::max_element(v, v + 4); cout << char(*i1) << \"\\n\"; return 0;}",
"e": 1650,
"s": 1317,
"text": null
},
{
"code": null,
"e": 1653,
"s": 1650,
"text": "k\n"
},
{
"code": null,
"e": 1675,
"s": 1653,
"text": "Time Complexity: O(n)"
},
{
"code": null,
"e": 1697,
"s": 1675,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 1759,
"s": 1697,
"text": " 2. For comparison based on a pre-defined function: "
},
{
"code": null,
"e": 1767,
"s": 1759,
"text": "Syntax:"
},
{
"code": null,
"e": 2498,
"s": 1767,
"text": "template \nForwardIterator max_element (ForwardIterator first, ForwardIterator last,\n Compare comp);\nHere, first and last are the same as previous case.\ncomp: Binary function that accepts two elements \nin the range as arguments, and returns a value convertible to bool.\n\nThe value returned indicates whether the element passed as first argument \nis considered less than the second.\nThe function shall not modify any of its arguments.\nThis can either be a function pointer or a function object.\n\nReturn Value: It returns a pointer to the largest element \nin the range, and in case if there are more than one such element,\nthen it points to the first one.\nIt points to the last in case the range is empty."
},
{
"code": null,
"e": 2502,
"s": 2498,
"text": "CPP"
},
{
"code": "// C++ program to demonstrate the use of std::max_element#include <iostream>#include <algorithm>using namespace std; // Defining the BinaryFunctionbool comp(int a, int b){ return (a < b);} int main(){ int v[] = { 9, 4, 7, 2, 5, 10, 11, 12, 1, 3, 6 }; // Finding the maximum value between the third and the // ninth element int* i1; i1 = std::max_element(v + 2, v + 9, comp); cout << *i1 << \"\\n\"; return 0;}",
"e": 2912,
"s": 2502,
"text": null
},
{
"code": null,
"e": 2920,
"s": 2912,
"text": "Output:"
},
{
"code": null,
"e": 2923,
"s": 2920,
"text": "12"
},
{
"code": null,
"e": 2945,
"s": 2923,
"text": "Time complexity: O(n)"
},
{
"code": null,
"e": 2967,
"s": 2945,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 2985,
"s": 2967,
"text": "Related Articles:"
},
{
"code": null,
"e": 2994,
"s": 2985,
"text": "std::max"
},
{
"code": null,
"e": 3003,
"s": 2994,
"text": "std::min"
},
{
"code": null,
"e": 3014,
"s": 3003,
"text": "std::equal"
},
{
"code": null,
"e": 3038,
"s": 3014,
"text": "std::min_element in C++"
},
{
"code": null,
"e": 3462,
"s": 3038,
"text": "This article is contributed by Mrigendra Singh. 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": 3478,
"s": 3462,
"text": "surbhikumaridav"
},
{
"code": null,
"e": 3500,
"s": 3478,
"text": "cpp-algorithm-library"
},
{
"code": null,
"e": 3504,
"s": 3500,
"text": "STL"
},
{
"code": null,
"e": 3508,
"s": 3504,
"text": "C++"
},
{
"code": null,
"e": 3512,
"s": 3508,
"text": "STL"
},
{
"code": null,
"e": 3516,
"s": 3512,
"text": "CPP"
},
{
"code": null,
"e": 3614,
"s": 3516,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3641,
"s": 3614,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 3684,
"s": 3641,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 3709,
"s": 3684,
"text": "unordered_map in C++ STL"
},
{
"code": null,
"e": 3728,
"s": 3709,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 3762,
"s": 3728,
"text": "vector erase() and clear() in C++"
},
{
"code": null,
"e": 3779,
"s": 3762,
"text": "Substring in C++"
},
{
"code": null,
"e": 3803,
"s": 3779,
"text": "C++ Classes and Objects"
},
{
"code": null,
"e": 3838,
"s": 3803,
"text": "Object Oriented Programming in C++"
},
{
"code": null,
"e": 3892,
"s": 3838,
"text": "Priority Queue in C++ Standard Template Library (STL)"
}
] |
JavaTuples getKey() method | 27 Aug, 2018
The getKey() method in org.javatuples is used to fetch the key from the TupleClassObject from the KeyValue Class. This method can be used with only KeyValue class object of javatuples library. It returns a Key which is the element present at the index 0 of the KeyValueClassObject. The returned Key is ensures the type-safety.
Method Declaration:
public A getKey()
Syntax:
KeyValue<A, B> KeyValueClassObject = KeyValue.with(A a, B b);
A val = KeyValueClassObject.getKey()
Return Value: This method returns a Key which is the element present at the index 0 of the KeyValueClassObject.
Below programs illustrate the various ways to use getKey() method:
Example 1:
// Below is a Java program to get// a KeyValue value import java.util.*;import org.javatuples.KeyValue; class GfG { public static void main(String[] args) { // Creating a KeyValue object KeyValue<Integer, String> kv = KeyValue.with(Integer.valueOf(1), "GeeksforGeeks"); // Using getKey() method int key = kv.getKey(); // Printing the Key System.out.println(key); }}
Output:
1
Example 2:
// Below is a Java program to get// a KeyValue value import java.util.*;import org.javatuples.KeyValue; class GfG { public static void main(String[] args) { // Creating a KeyValue object KeyValue<String, String> kv = KeyValue.with("GeeksforGeeks", "A Computer Science Portal for Geeks"); // Using getKey() method String key = kv.getKey(); // Printing the Key System.out.println(key); }}
Output:
GeeksforGeeks
Java-Functions
JavaTuples
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 Aug, 2018"
},
{
"code": null,
"e": 355,
"s": 28,
"text": "The getKey() method in org.javatuples is used to fetch the key from the TupleClassObject from the KeyValue Class. This method can be used with only KeyValue class object of javatuples library. It returns a Key which is the element present at the index 0 of the KeyValueClassObject. The returned Key is ensures the type-safety."
},
{
"code": null,
"e": 375,
"s": 355,
"text": "Method Declaration:"
},
{
"code": null,
"e": 393,
"s": 375,
"text": "public A getKey()"
},
{
"code": null,
"e": 401,
"s": 393,
"text": "Syntax:"
},
{
"code": null,
"e": 500,
"s": 401,
"text": "KeyValue<A, B> KeyValueClassObject = KeyValue.with(A a, B b);\nA val = KeyValueClassObject.getKey()"
},
{
"code": null,
"e": 612,
"s": 500,
"text": "Return Value: This method returns a Key which is the element present at the index 0 of the KeyValueClassObject."
},
{
"code": null,
"e": 679,
"s": 612,
"text": "Below programs illustrate the various ways to use getKey() method:"
},
{
"code": null,
"e": 690,
"s": 679,
"text": "Example 1:"
},
{
"code": "// Below is a Java program to get// a KeyValue value import java.util.*;import org.javatuples.KeyValue; class GfG { public static void main(String[] args) { // Creating a KeyValue object KeyValue<Integer, String> kv = KeyValue.with(Integer.valueOf(1), \"GeeksforGeeks\"); // Using getKey() method int key = kv.getKey(); // Printing the Key System.out.println(key); }}",
"e": 1151,
"s": 690,
"text": null
},
{
"code": null,
"e": 1159,
"s": 1151,
"text": "Output:"
},
{
"code": null,
"e": 1162,
"s": 1159,
"text": "1\n"
},
{
"code": null,
"e": 1173,
"s": 1162,
"text": "Example 2:"
},
{
"code": "// Below is a Java program to get// a KeyValue value import java.util.*;import org.javatuples.KeyValue; class GfG { public static void main(String[] args) { // Creating a KeyValue object KeyValue<String, String> kv = KeyValue.with(\"GeeksforGeeks\", \"A Computer Science Portal for Geeks\"); // Using getKey() method String key = kv.getKey(); // Printing the Key System.out.println(key); }}",
"e": 1655,
"s": 1173,
"text": null
},
{
"code": null,
"e": 1663,
"s": 1655,
"text": "Output:"
},
{
"code": null,
"e": 1678,
"s": 1663,
"text": "GeeksforGeeks\n"
},
{
"code": null,
"e": 1693,
"s": 1678,
"text": "Java-Functions"
},
{
"code": null,
"e": 1704,
"s": 1693,
"text": "JavaTuples"
},
{
"code": null,
"e": 1709,
"s": 1704,
"text": "Java"
},
{
"code": null,
"e": 1714,
"s": 1709,
"text": "Java"
}
] |
Program to print 2D shapes in C++ | In this tutorial, we will be discussing a program to print out 2D shapes.
For this we will be provided with the various parameters required to make a shape such as radius, side length and side breadth, etc. And our task is to print a shape accordingly with no thickness.
Live Demo
#include <bits/stdc++.h>
using namespace std;
void print_circle(int radius){
for (int i = 0; i <= 2 * radius; i++){
for (int j = 0; j <= 2 * radius; j++){
double distance = sqrt((double)(i - radius) * (i -
radius) + (j - radius) * (j - radius));
if (distance > radius - 0.5 &&
distance < radius + 0.5)
printf("*");
else
printf(" ");
}
printf("\n");
}
}
void print_rectangle(int l, int b){
int i, j;
for (i = 1; i <= l; i++){
for (j = 1; j <= b; j++)
if (i == 1 || i == l || j == 1 || j == b)
printf("*");
else
printf(" ");
printf("\n");
}
}
void print_triangle(int side){
int i, j;
for (i = 1; i <= side; i++){
for (j = i; j < side; j++)
printf(" ");
for (j = 1; j <= (2 * i - 1); j++){
if (i == side || j == 1 || j == (2 * i - 1))
printf("*");
else
printf(" ");
}
printf("\n");
}
}
void print_hexagon(int length){
int l, j, i, k;
for (i = 1, k = length, l = 2 * length - 1; i < length;
i++, k--, l++){
for (j = 0; j < 3 * length; j++)
if (j >= k && j <= l)
printf("*");
else
printf(" ");
printf("\n");
}
for (i = 0, k = 1, l = 3 * length - 2; i < length; i++,
k++, l--){
for (j = 0; j < 3 * length; j++)
if (j >= k && j <= l)
printf("*");
else
printf(" ");
printf("\n");
}
}
void calc_pattern(int choice){
int radius, length, breadth, side;
switch (choice){
case 1:
radius = 4;
print_circle(radius);
break;
case 2:
length = 3, breadth = 8;
print_rectangle(length, breadth);
break;
case 3:
side = 6;
print_triangle(side);
break;
case 4:
side = 4;
print_hexagon(side);
break;
default:
printf("Invalid choice\n");
}
}
int main(){
int choice = 1;
calc_pattern(choice);
return 0;
}
*****
** **
** **
* *
* *
* *
** **
** **
***** | [
{
"code": null,
"e": 1261,
"s": 1187,
"text": "In this tutorial, we will be discussing a program to print out 2D shapes."
},
{
"code": null,
"e": 1458,
"s": 1261,
"text": "For this we will be provided with the various parameters required to make a shape such as radius, side length and side breadth, etc. And our task is to print a shape accordingly with no thickness."
},
{
"code": null,
"e": 1469,
"s": 1458,
"text": " Live Demo"
},
{
"code": null,
"e": 3671,
"s": 1469,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nvoid print_circle(int radius){\n for (int i = 0; i <= 2 * radius; i++){\n for (int j = 0; j <= 2 * radius; j++){\n double distance = sqrt((double)(i - radius) * (i -\n radius) + (j - radius) * (j - radius));\n if (distance > radius - 0.5 &&\n distance < radius + 0.5)\n printf(\"*\");\n else\n printf(\" \");\n }\n printf(\"\\n\");\n }\n}\nvoid print_rectangle(int l, int b){\n int i, j;\n for (i = 1; i <= l; i++){\n for (j = 1; j <= b; j++)\n if (i == 1 || i == l || j == 1 || j == b)\n printf(\"*\");\n else\n printf(\" \");\n printf(\"\\n\");\n }\n}\nvoid print_triangle(int side){\n int i, j;\n for (i = 1; i <= side; i++){\n for (j = i; j < side; j++)\n printf(\" \");\n for (j = 1; j <= (2 * i - 1); j++){\n if (i == side || j == 1 || j == (2 * i - 1))\n printf(\"*\");\n else\n printf(\" \");\n }\n printf(\"\\n\");\n }\n}\nvoid print_hexagon(int length){\n int l, j, i, k;\n for (i = 1, k = length, l = 2 * length - 1; i < length;\n i++, k--, l++){\n for (j = 0; j < 3 * length; j++)\n if (j >= k && j <= l)\n printf(\"*\");\n else\n printf(\" \");\n printf(\"\\n\");\n }\n for (i = 0, k = 1, l = 3 * length - 2; i < length; i++,\n k++, l--){\n for (j = 0; j < 3 * length; j++)\n if (j >= k && j <= l)\n printf(\"*\");\n else\n printf(\" \");\n printf(\"\\n\");\n }\n }\n void calc_pattern(int choice){\n int radius, length, breadth, side;\n switch (choice){\n case 1:\n radius = 4;\n print_circle(radius);\n break;\n case 2:\n length = 3, breadth = 8;\n print_rectangle(length, breadth);\n break;\n case 3:\n side = 6;\n print_triangle(side);\n break;\n case 4:\n side = 4;\n print_hexagon(side);\n break;\n default:\n printf(\"Invalid choice\\n\");\n }\n}\nint main(){\n int choice = 1;\n calc_pattern(choice);\n return 0;\n}"
},
{
"code": null,
"e": 3783,
"s": 3671,
"text": " *****\n ** **\n ** **\n * *\n * *\n * *\n ** **\n ** **\n *****"
}
] |
GATE | GATE-CS-2016 (Set 1) | Question 35 | 28 Jun, 2021
Which of the following is/are example(s) of stateful application layer protocols?
(i) HTTP
(ii) FTP
(iii) TCP
(iv) POP3
(A) (i) and (ii) only
(B) (ii) and (iii) only(C) (ii) and (iv) only(D) (iv) onlyAnswer: (C)Explanation: In computing, a stateless protocol is a communications protocol that treats each request as an independent transaction that is unrelated to any previous request so that the communication consists of independent pairs of request and response.
Examples of stateless protocols (IP) and (HTTP)
Source: https://en.wikipedia.org/wiki/Stateless_protocol
TCP is stateful as it maintains connection information across multiple transfers, but TCP is not an application layer protocol.
Of the given protocols, only FTP and POP3 are stateful application layer protocols. Quiz of this Question
GATE-CS-2016 (Set 1)
GATE-GATE-CS-2016 (Set 1)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2014-(Set-2) | Question 65
GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33
GATE | GATE-CS-2014-(Set-3) | Question 20
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE CS 2008 | Question 46
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 1996 | Question 63
GATE | GATE CS 2008 | Question 40
GATE | GATE-CS-2014-(Set-1) | Question 51
GATE | GATE-CS-2001 | Question 50 | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 110,
"s": 28,
"text": "Which of the following is/are example(s) of stateful application layer protocols?"
},
{
"code": null,
"e": 150,
"s": 110,
"text": "(i) HTTP\n(ii) FTP\n(iii) TCP\n(iv) POP3 "
},
{
"code": null,
"e": 172,
"s": 150,
"text": "(A) (i) and (ii) only"
},
{
"code": null,
"e": 496,
"s": 172,
"text": "(B) (ii) and (iii) only(C) (ii) and (iv) only(D) (iv) onlyAnswer: (C)Explanation: In computing, a stateless protocol is a communications protocol that treats each request as an independent transaction that is unrelated to any previous request so that the communication consists of independent pairs of request and response."
},
{
"code": null,
"e": 544,
"s": 496,
"text": "Examples of stateless protocols (IP) and (HTTP)"
},
{
"code": null,
"e": 601,
"s": 544,
"text": "Source: https://en.wikipedia.org/wiki/Stateless_protocol"
},
{
"code": null,
"e": 729,
"s": 601,
"text": "TCP is stateful as it maintains connection information across multiple transfers, but TCP is not an application layer protocol."
},
{
"code": null,
"e": 835,
"s": 729,
"text": "Of the given protocols, only FTP and POP3 are stateful application layer protocols. Quiz of this Question"
},
{
"code": null,
"e": 856,
"s": 835,
"text": "GATE-CS-2016 (Set 1)"
},
{
"code": null,
"e": 882,
"s": 856,
"text": "GATE-GATE-CS-2016 (Set 1)"
},
{
"code": null,
"e": 887,
"s": 882,
"text": "GATE"
},
{
"code": null,
"e": 985,
"s": 887,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1027,
"s": 985,
"text": "GATE | GATE-CS-2014-(Set-2) | Question 65"
},
{
"code": null,
"e": 1089,
"s": 1027,
"text": "GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33"
},
{
"code": null,
"e": 1131,
"s": 1089,
"text": "GATE | GATE-CS-2014-(Set-3) | Question 20"
},
{
"code": null,
"e": 1173,
"s": 1131,
"text": "GATE | GATE-CS-2015 (Set 3) | Question 65"
},
{
"code": null,
"e": 1207,
"s": 1173,
"text": "GATE | GATE CS 2008 | Question 46"
},
{
"code": null,
"e": 1249,
"s": 1207,
"text": "GATE | GATE-CS-2014-(Set-3) | Question 65"
},
{
"code": null,
"e": 1283,
"s": 1249,
"text": "GATE | GATE CS 1996 | Question 63"
},
{
"code": null,
"e": 1317,
"s": 1283,
"text": "GATE | GATE CS 2008 | Question 40"
},
{
"code": null,
"e": 1359,
"s": 1317,
"text": "GATE | GATE-CS-2014-(Set-1) | Question 51"
}
] |
Upcasting Vs Downcasting in Java | 11 Oct, 2021
Typecasting is one of the most important concepts which basically deals with the conversion of one data type to another datatype implicitly or explicitly. In this article, the concept of typecasting for objects is discussed. Just like the data types, the objects can also be typecasted. However, in objects, there are only two types of objects, i.e. parent object and child object. Therefore, typecasting of objects basically means that one type of object (i.e.) child or parent to another. There are two types of typecasting. They are:
Upcasting: Upcasting is the typecasting of a child object to a parent object. Upcasting can be done implicitly. Upcasting gives us the flexibility to access the parent class members but it is not possible to access all the child class members using this feature. Instead of all the members, we can access some specified members of the child class. For instance, we can access the overridden methods.Downcasting: Similarly, downcasting means the typecasting of a parent object to a child object. Downcasting cannot be implicit.
Upcasting: Upcasting is the typecasting of a child object to a parent object. Upcasting can be done implicitly. Upcasting gives us the flexibility to access the parent class members but it is not possible to access all the child class members using this feature. Instead of all the members, we can access some specified members of the child class. For instance, we can access the overridden methods.
Downcasting: Similarly, downcasting means the typecasting of a parent object to a child object. Downcasting cannot be implicit.
The following image illustrates the concept of upcasting and downcasting:
Example: Let there be a parent class. There can be many children of a parent. Let’s take one of the children into consideration. The child inherits the properties of the parent. Therefore, there is an “is-a” relationship between the child and parent. Therefore, the child can be implicitly upcasted to the parent. However, a parent may or may not inherits the child’s properties. However, we can forcefully cast a parent to a child which is known as downcasting. After we define this type of casting explicitly, the compiler checks in the background if this type of casting is possible or not. If it’s not possible, the compiler throws a ClassCastException. Let’s understand the following code to understand the difference:
Java
// Java program to demonstrate// Upcasting Vs Downcasting // Parent classclass Parent { String name; // A method which prints the // signature of the parent class void method() { System.out.println("Method from Parent"); }} // Child classclass Child extends Parent { int id; // Overriding the parent method // to print the signature of the // child class @Override void method() { System.out.println("Method from Child"); }} // Demo class to see the difference// between upcasting and downcastingpublic class GFG { // Driver code public static void main(String[] args) { // Upcasting Parent p = new Child(); p.name = "GeeksforGeeks"; //Printing the parentclass name System.out.println(p.name); //parent class method is overriden method hence this will be executed p.method(); // Trying to Downcasting Implicitly // Child c = new Parent(); - > compile time error // Downcasting Explicitly Child c = (Child)p; c.id = 1; System.out.println(c.name); System.out.println(c.id); c.method(); }}
GeeksforGeeks
Method from Child
GeeksforGeeks
1
Method from Child
An illustrative figure of the above program:
From the above example we can observe the following points:
Syntax of Upcasting:
Syntax of Upcasting:
Parent p = new Child();
Upcasting will be done internally and due to upcasting the object is allowed to access only parent class members and child class specified members (overridden methods, etc.) but not all members.
Upcasting will be done internally and due to upcasting the object is allowed to access only parent class members and child class specified members (overridden methods, etc.) but not all members.
// This variable is not
// accessible
p.id = 1;
Syntax of Downcasting:
Syntax of Downcasting:
Child c = (Child)p;
Downcasting has to be done externally and due to downcasting a child object can acquire the properties of the parent object.
Downcasting has to be done externally and due to downcasting a child object can acquire the properties of the parent object.
c.name = p.name;
i.e., c.name = "GeeksforGeeks"
satvik99
zack_aayush
rkumarpatra
Java
Write From Home
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
Stream In Java
ArrayList 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": 53,
"s": 25,
"text": "\n11 Oct, 2021"
},
{
"code": null,
"e": 592,
"s": 53,
"text": "Typecasting is one of the most important concepts which basically deals with the conversion of one data type to another datatype implicitly or explicitly. In this article, the concept of typecasting for objects is discussed. Just like the data types, the objects can also be typecasted. However, in objects, there are only two types of objects, i.e. parent object and child object. Therefore, typecasting of objects basically means that one type of object (i.e.) child or parent to another. There are two types of typecasting. They are: "
},
{
"code": null,
"e": 1119,
"s": 592,
"text": "Upcasting: Upcasting is the typecasting of a child object to a parent object. Upcasting can be done implicitly. Upcasting gives us the flexibility to access the parent class members but it is not possible to access all the child class members using this feature. Instead of all the members, we can access some specified members of the child class. For instance, we can access the overridden methods.Downcasting: Similarly, downcasting means the typecasting of a parent object to a child object. Downcasting cannot be implicit."
},
{
"code": null,
"e": 1519,
"s": 1119,
"text": "Upcasting: Upcasting is the typecasting of a child object to a parent object. Upcasting can be done implicitly. Upcasting gives us the flexibility to access the parent class members but it is not possible to access all the child class members using this feature. Instead of all the members, we can access some specified members of the child class. For instance, we can access the overridden methods."
},
{
"code": null,
"e": 1647,
"s": 1519,
"text": "Downcasting: Similarly, downcasting means the typecasting of a parent object to a child object. Downcasting cannot be implicit."
},
{
"code": null,
"e": 1722,
"s": 1647,
"text": "The following image illustrates the concept of upcasting and downcasting: "
},
{
"code": null,
"e": 2447,
"s": 1722,
"text": "Example: Let there be a parent class. There can be many children of a parent. Let’s take one of the children into consideration. The child inherits the properties of the parent. Therefore, there is an “is-a” relationship between the child and parent. Therefore, the child can be implicitly upcasted to the parent. However, a parent may or may not inherits the child’s properties. However, we can forcefully cast a parent to a child which is known as downcasting. After we define this type of casting explicitly, the compiler checks in the background if this type of casting is possible or not. If it’s not possible, the compiler throws a ClassCastException. Let’s understand the following code to understand the difference: "
},
{
"code": null,
"e": 2452,
"s": 2447,
"text": "Java"
},
{
"code": "// Java program to demonstrate// Upcasting Vs Downcasting // Parent classclass Parent { String name; // A method which prints the // signature of the parent class void method() { System.out.println(\"Method from Parent\"); }} // Child classclass Child extends Parent { int id; // Overriding the parent method // to print the signature of the // child class @Override void method() { System.out.println(\"Method from Child\"); }} // Demo class to see the difference// between upcasting and downcastingpublic class GFG { // Driver code public static void main(String[] args) { // Upcasting Parent p = new Child(); p.name = \"GeeksforGeeks\"; //Printing the parentclass name System.out.println(p.name); //parent class method is overriden method hence this will be executed p.method(); // Trying to Downcasting Implicitly // Child c = new Parent(); - > compile time error // Downcasting Explicitly Child c = (Child)p; c.id = 1; System.out.println(c.name); System.out.println(c.id); c.method(); }}",
"e": 3616,
"s": 2452,
"text": null
},
{
"code": null,
"e": 3682,
"s": 3616,
"text": "GeeksforGeeks\nMethod from Child\nGeeksforGeeks\n1\nMethod from Child"
},
{
"code": null,
"e": 3728,
"s": 3682,
"text": "An illustrative figure of the above program: "
},
{
"code": null,
"e": 3790,
"s": 3728,
"text": "From the above example we can observe the following points: "
},
{
"code": null,
"e": 3813,
"s": 3790,
"text": "Syntax of Upcasting: "
},
{
"code": null,
"e": 3836,
"s": 3813,
"text": "Syntax of Upcasting: "
},
{
"code": null,
"e": 3860,
"s": 3836,
"text": "Parent p = new Child();"
},
{
"code": null,
"e": 4057,
"s": 3860,
"text": "Upcasting will be done internally and due to upcasting the object is allowed to access only parent class members and child class specified members (overridden methods, etc.) but not all members. "
},
{
"code": null,
"e": 4254,
"s": 4057,
"text": "Upcasting will be done internally and due to upcasting the object is allowed to access only parent class members and child class specified members (overridden methods, etc.) but not all members. "
},
{
"code": null,
"e": 4304,
"s": 4254,
"text": "// This variable is not \n// accessible\np.id = 1; "
},
{
"code": null,
"e": 4329,
"s": 4304,
"text": "Syntax of Downcasting: "
},
{
"code": null,
"e": 4354,
"s": 4329,
"text": "Syntax of Downcasting: "
},
{
"code": null,
"e": 4374,
"s": 4354,
"text": "Child c = (Child)p;"
},
{
"code": null,
"e": 4501,
"s": 4374,
"text": "Downcasting has to be done externally and due to downcasting a child object can acquire the properties of the parent object. "
},
{
"code": null,
"e": 4628,
"s": 4501,
"text": "Downcasting has to be done externally and due to downcasting a child object can acquire the properties of the parent object. "
},
{
"code": null,
"e": 4676,
"s": 4628,
"text": "c.name = p.name;\ni.e., c.name = \"GeeksforGeeks\""
},
{
"code": null,
"e": 4687,
"s": 4678,
"text": "satvik99"
},
{
"code": null,
"e": 4699,
"s": 4687,
"text": "zack_aayush"
},
{
"code": null,
"e": 4711,
"s": 4699,
"text": "rkumarpatra"
},
{
"code": null,
"e": 4716,
"s": 4711,
"text": "Java"
},
{
"code": null,
"e": 4732,
"s": 4716,
"text": "Write From Home"
},
{
"code": null,
"e": 4737,
"s": 4732,
"text": "Java"
},
{
"code": null,
"e": 4835,
"s": 4737,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4866,
"s": 4835,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 4885,
"s": 4866,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 4915,
"s": 4885,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 4930,
"s": 4915,
"text": "Stream In Java"
},
{
"code": null,
"e": 4948,
"s": 4930,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 4984,
"s": 4948,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 5020,
"s": 4984,
"text": "Convert string to integer in Python"
},
{
"code": null,
"e": 5081,
"s": 5020,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 5097,
"s": 5081,
"text": "Python infinity"
}
] |
Find coordinates of the triangle given midpoint of each side | 24 Nov, 2021
Given three coordinates (x, y), which are the midpoint of the sides of the triangle. The task is to find the coordinates of the triangle.
Examples:
Input : midx1 = 5, midy1 = 3
midx2 = 4, midy2 = 4
midx3 = 5, midy3 = 5
Output : x1 = 4 y1 = 2
x2 = 4 y2 = 6
x3 = 6 y3 = 4
Solution can be verified by the figure.
Let’s separately solve for X-coordinates and Y-coordinates. For X coordinate of vertices, let them be x1, x2, x3. Then, X-coordinate of middle points will be (x1 + x2)/2, (x2 + x3)/2, (x3 + x1)/2. Observe, sum of these 3 expressions is equal to sum of X-coordinates. Now, we have sum of 3 variables and 3 expressions for sum of every pair of them, find out the values of coordinates by solving equations. Similarly, we solve for Y-coordinates.
Below is the implementation of this approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find coordinate of the// triangle given midpoint of each side#include<bits/stdc++.h>#define N 3using namespace std; // Return after solving the equations and// finding the vertices coordinate.vector<int> solve(int v[]){ vector<int> res; // Finding sum of all three coordinate. int all3 = v[0] + v[1] + v[2]; // Solving the equation. res.push_back(all3 - v[1]*2); res.push_back(all3 - v[2]*2); res.push_back(all3 - v[0]*2); return res;} // Finds vertices of a triangles from given// middle vertices.void findVertex(int xmid[], int ymid[]){ // Find X coordinates of vertices. vector<int> V1 = solve(xmid); // Find Y coordinates of vertices. vector<int> V2 = solve(ymid); // Output the solution. for (int i = 0; i < 3; i++) cout << V1[i] << " " << V2[i] <<endl;} // Driver codeint main(){ int xmid[N] = { 5, 4, 5 }; int ymid[N] = { 3, 4, 5 }; findVertex(xmid, ymid); return 0;}
import java.util.Vector; // Java program to find coordinate of the // triangle given midpoint of each side class GFG { //static final int N = 3; // Return after solving the equations and // finding the vertices coordinate. static Vector<Integer> solve(int v[]) { Vector<Integer> res = new Vector<Integer>(); // Finding sum of all three coordinate. int all3 = v[0] + v[1] + v[2]; // Solving the equation. res.add(all3 - v[1] * 2); res.add(all3 - v[2] * 2); res.add(all3 - v[0] * 2); return res; } // Finds vertices of a triangles from given // middle vertices. static void findVertex(int xmid[], int ymid[]) { // Find X coordinates of vertices. Vector<Integer> V1 = solve(xmid); // Find Y coordinates of vertices. Vector<Integer> V2 = solve(ymid); // Output the solution. for (int i = 0; i < 3; i++) { System.out.println(V1.get(i) + " " + V2.get(i)); } } // Driver code public static void main(String[] args) { int xmid[] = {5, 4, 5}; int ymid[] = {3, 4, 5}; findVertex(xmid, ymid); }}// This code is contributed by// PrinciRaj1992
# Python3 program to find coordinate of the# triangle given midpoint of each side N = 3 # Return after solving the equations and# finding the vertices coordinate.def solve(v): res = [] # Finding sum of all three coordinate. all3 = v[0] + v[1] + v[2] # Solving the equation. res.append(all3 - v[1] * 2) res.append(all3 - v[2] * 2) res.append(all3 - v[0] * 2) return res # Finds vertices of a triangles from given# middle vertices.def findVertex(xmid, ymid): # Find X coordinates of vertices. V1 = solve(xmid) # Find Y coordinates of vertices. V2 = solve(ymid) # Output the solution. for i in range(0, 3): print(V1[i], end=" ") print(V2[i]) # Driver codeif __name__=='__main__': xmid = [5, 4, 5] ymid = [3, 4, 5] findVertex(xmid, ymid) # This code is contributed by# Sanjit_Prasad
// C# program to find coordinate of the // triangle given midpoint of each side using System;using System.Collections; class GFG { //static final int N = 3; // Return after solving the equations and // finding the vertices coordinate. static ArrayList solve(int []v) { ArrayList res = new ArrayList(); // Finding sum of all three coordinate. int all3 = v[0] + v[1] + v[2]; // Solving the equation. res.Add(all3 - v[1] * 2); res.Add(all3 - v[2] * 2); res.Add(all3 - v[0] * 2); return res; } // Finds vertices of a triangles from given // middle vertices. static void findVertex(int []xmid, int []ymid) { // Find X coordinates of vertices. ArrayList V1 = solve(xmid); // Find Y coordinates of vertices. ArrayList V2 = solve(ymid); // Output the solution. for (int i = 0; i < 3; i++) { Console.WriteLine(V1[i] + " " + V2[i]); } } // Driver code public static void Main() { int []xmid = {5, 4, 5}; int []ymid = {3, 4, 5}; findVertex(xmid, ymid); } } // This code is contributed by mits
<?php// PHP program to find coordinate of the // triangle given midpoint of each side $N = 3; // Return after solving the equations and // finding the vertices coordinate. function solve($v) { $res = array(); // Finding sum of all three coordinate. $all3 = $v[0] + $v[1] + $v[2]; // Solving the equation. array_push($res, $all3 - $v[1] * 2); array_push($res, $all3 - $v[2] * 2); array_push($res, $all3 - $v[0] * 2); return $res; } // Finds vertices of a triangles from // given middle vertices. function findVertex($xmid, $ymid) { // Find X coordinates of vertices. $V1 = solve($xmid); // Find Y coordinates of vertices. $V2 = solve($ymid); // Output the solution. for ($i = 0; $i < 3; $i++) print($V1[$i] . " " . $V2[$i] . "\n");} // Driver code $xmid = array(5, 4, 5); $ymid = array(3, 4, 5); findVertex($xmid, $ymid) // This code is contributed by mits?>
<script> // JavaScript program to find coordinate of the // triangle given midpoint of each side // Return after solving the equations and // finding the vertices coordinate. function solve(v) { var res = []; // Finding sum of all three coordinate. var all3 = v[0] + v[1] + v[2]; // Solving the equation. res.push(all3 - v[1] * 2); res.push(all3 - v[2] * 2); res.push(all3 - v[0] * 2); return res; } // Finds vertices of a triangles from given // middle vertices. function findVertex(xmid, ymid) { // Find X coordinates of vertices. var V1 = solve(xmid); // Find Y coordinates of vertices. var V2 = solve(ymid); // Output the solution. for (var i = 0; i < 3; i++) { document.write(V1[i] + " " + V2[i] + "<br>"); } } // Driver code var xmid = [5, 4, 5]; var ymid = [3, 4, 5]; findVertex(xmid, ymid); </script>
Output:
6 4
4 2
4 6
Time Complexity: O(1)
This 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.
Sanjit_Prasad
princiraj1992
Mithun Kumar
VishalBachchas
rdtank
saurabh1990aror
rajeev0719singh
kalrap615
triangle
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Algorithm to solve Rubik's Cube
Merge two sorted arrays with O(1) extra space
Program to print prime numbers from 1 to N.
Segment Tree | Set 1 (Sum of given range)
Sum of the series (1*2) + (2*3) + (3*4) + ...... upto n terms
Check if a number is Palindrome
Count ways to reach the n'th stair
Fizz Buzz Implementation
Median of two sorted arrays of same size
Product of Array except itself | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n24 Nov, 2021"
},
{
"code": null,
"e": 167,
"s": 28,
"text": "Given three coordinates (x, y), which are the midpoint of the sides of the triangle. The task is to find the coordinates of the triangle. "
},
{
"code": null,
"e": 179,
"s": 167,
"text": "Examples: "
},
{
"code": null,
"e": 336,
"s": 179,
"text": "Input : midx1 = 5, midy1 = 3\n midx2 = 4, midy2 = 4\n midx3 = 5, midy3 = 5\n\nOutput : x1 = 4 y1 = 2\n x2 = 4 y2 = 6\n x3 = 6 y3 = 4"
},
{
"code": null,
"e": 376,
"s": 336,
"text": "Solution can be verified by the figure."
},
{
"code": null,
"e": 820,
"s": 376,
"text": "Let’s separately solve for X-coordinates and Y-coordinates. For X coordinate of vertices, let them be x1, x2, x3. Then, X-coordinate of middle points will be (x1 + x2)/2, (x2 + x3)/2, (x3 + x1)/2. Observe, sum of these 3 expressions is equal to sum of X-coordinates. Now, we have sum of 3 variables and 3 expressions for sum of every pair of them, find out the values of coordinates by solving equations. Similarly, we solve for Y-coordinates."
},
{
"code": null,
"e": 868,
"s": 820,
"text": "Below is the implementation of this approach: "
},
{
"code": null,
"e": 872,
"s": 868,
"text": "C++"
},
{
"code": null,
"e": 877,
"s": 872,
"text": "Java"
},
{
"code": null,
"e": 885,
"s": 877,
"text": "Python3"
},
{
"code": null,
"e": 888,
"s": 885,
"text": "C#"
},
{
"code": null,
"e": 892,
"s": 888,
"text": "PHP"
},
{
"code": null,
"e": 903,
"s": 892,
"text": "Javascript"
},
{
"code": "// C++ program to find coordinate of the// triangle given midpoint of each side#include<bits/stdc++.h>#define N 3using namespace std; // Return after solving the equations and// finding the vertices coordinate.vector<int> solve(int v[]){ vector<int> res; // Finding sum of all three coordinate. int all3 = v[0] + v[1] + v[2]; // Solving the equation. res.push_back(all3 - v[1]*2); res.push_back(all3 - v[2]*2); res.push_back(all3 - v[0]*2); return res;} // Finds vertices of a triangles from given// middle vertices.void findVertex(int xmid[], int ymid[]){ // Find X coordinates of vertices. vector<int> V1 = solve(xmid); // Find Y coordinates of vertices. vector<int> V2 = solve(ymid); // Output the solution. for (int i = 0; i < 3; i++) cout << V1[i] << \" \" << V2[i] <<endl;} // Driver codeint main(){ int xmid[N] = { 5, 4, 5 }; int ymid[N] = { 3, 4, 5 }; findVertex(xmid, ymid); return 0;}",
"e": 1882,
"s": 903,
"text": null
},
{
"code": "import java.util.Vector; // Java program to find coordinate of the // triangle given midpoint of each side class GFG { //static final int N = 3; // Return after solving the equations and // finding the vertices coordinate. static Vector<Integer> solve(int v[]) { Vector<Integer> res = new Vector<Integer>(); // Finding sum of all three coordinate. int all3 = v[0] + v[1] + v[2]; // Solving the equation. res.add(all3 - v[1] * 2); res.add(all3 - v[2] * 2); res.add(all3 - v[0] * 2); return res; } // Finds vertices of a triangles from given // middle vertices. static void findVertex(int xmid[], int ymid[]) { // Find X coordinates of vertices. Vector<Integer> V1 = solve(xmid); // Find Y coordinates of vertices. Vector<Integer> V2 = solve(ymid); // Output the solution. for (int i = 0; i < 3; i++) { System.out.println(V1.get(i) + \" \" + V2.get(i)); } } // Driver code public static void main(String[] args) { int xmid[] = {5, 4, 5}; int ymid[] = {3, 4, 5}; findVertex(xmid, ymid); }}// This code is contributed by// PrinciRaj1992",
"e": 3092,
"s": 1882,
"text": null
},
{
"code": "# Python3 program to find coordinate of the# triangle given midpoint of each side N = 3 # Return after solving the equations and# finding the vertices coordinate.def solve(v): res = [] # Finding sum of all three coordinate. all3 = v[0] + v[1] + v[2] # Solving the equation. res.append(all3 - v[1] * 2) res.append(all3 - v[2] * 2) res.append(all3 - v[0] * 2) return res # Finds vertices of a triangles from given# middle vertices.def findVertex(xmid, ymid): # Find X coordinates of vertices. V1 = solve(xmid) # Find Y coordinates of vertices. V2 = solve(ymid) # Output the solution. for i in range(0, 3): print(V1[i], end=\" \") print(V2[i]) # Driver codeif __name__=='__main__': xmid = [5, 4, 5] ymid = [3, 4, 5] findVertex(xmid, ymid) # This code is contributed by# Sanjit_Prasad",
"e": 3953,
"s": 3092,
"text": null
},
{
"code": "// C# program to find coordinate of the // triangle given midpoint of each side using System;using System.Collections; class GFG { //static final int N = 3; // Return after solving the equations and // finding the vertices coordinate. static ArrayList solve(int []v) { ArrayList res = new ArrayList(); // Finding sum of all three coordinate. int all3 = v[0] + v[1] + v[2]; // Solving the equation. res.Add(all3 - v[1] * 2); res.Add(all3 - v[2] * 2); res.Add(all3 - v[0] * 2); return res; } // Finds vertices of a triangles from given // middle vertices. static void findVertex(int []xmid, int []ymid) { // Find X coordinates of vertices. ArrayList V1 = solve(xmid); // Find Y coordinates of vertices. ArrayList V2 = solve(ymid); // Output the solution. for (int i = 0; i < 3; i++) { Console.WriteLine(V1[i] + \" \" + V2[i]); } } // Driver code public static void Main() { int []xmid = {5, 4, 5}; int []ymid = {3, 4, 5}; findVertex(xmid, ymid); } } // This code is contributed by mits",
"e": 5177,
"s": 3953,
"text": null
},
{
"code": "<?php// PHP program to find coordinate of the // triangle given midpoint of each side $N = 3; // Return after solving the equations and // finding the vertices coordinate. function solve($v) { $res = array(); // Finding sum of all three coordinate. $all3 = $v[0] + $v[1] + $v[2]; // Solving the equation. array_push($res, $all3 - $v[1] * 2); array_push($res, $all3 - $v[2] * 2); array_push($res, $all3 - $v[0] * 2); return $res; } // Finds vertices of a triangles from // given middle vertices. function findVertex($xmid, $ymid) { // Find X coordinates of vertices. $V1 = solve($xmid); // Find Y coordinates of vertices. $V2 = solve($ymid); // Output the solution. for ($i = 0; $i < 3; $i++) print($V1[$i] . \" \" . $V2[$i] . \"\\n\");} // Driver code $xmid = array(5, 4, 5); $ymid = array(3, 4, 5); findVertex($xmid, $ymid) // This code is contributed by mits?>",
"e": 6128,
"s": 5177,
"text": null
},
{
"code": "<script> // JavaScript program to find coordinate of the // triangle given midpoint of each side // Return after solving the equations and // finding the vertices coordinate. function solve(v) { var res = []; // Finding sum of all three coordinate. var all3 = v[0] + v[1] + v[2]; // Solving the equation. res.push(all3 - v[1] * 2); res.push(all3 - v[2] * 2); res.push(all3 - v[0] * 2); return res; } // Finds vertices of a triangles from given // middle vertices. function findVertex(xmid, ymid) { // Find X coordinates of vertices. var V1 = solve(xmid); // Find Y coordinates of vertices. var V2 = solve(ymid); // Output the solution. for (var i = 0; i < 3; i++) { document.write(V1[i] + \" \" + V2[i] + \"<br>\"); } } // Driver code var xmid = [5, 4, 5]; var ymid = [3, 4, 5]; findVertex(xmid, ymid); </script>",
"e": 7138,
"s": 6128,
"text": null
},
{
"code": null,
"e": 7147,
"s": 7138,
"text": "Output: "
},
{
"code": null,
"e": 7159,
"s": 7147,
"text": "6 4\n4 2\n4 6"
},
{
"code": null,
"e": 7181,
"s": 7159,
"text": "Time Complexity: O(1)"
},
{
"code": null,
"e": 7602,
"s": 7181,
"text": "This 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": 7616,
"s": 7602,
"text": "Sanjit_Prasad"
},
{
"code": null,
"e": 7630,
"s": 7616,
"text": "princiraj1992"
},
{
"code": null,
"e": 7643,
"s": 7630,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 7658,
"s": 7643,
"text": "VishalBachchas"
},
{
"code": null,
"e": 7665,
"s": 7658,
"text": "rdtank"
},
{
"code": null,
"e": 7681,
"s": 7665,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 7697,
"s": 7681,
"text": "rajeev0719singh"
},
{
"code": null,
"e": 7707,
"s": 7697,
"text": "kalrap615"
},
{
"code": null,
"e": 7716,
"s": 7707,
"text": "triangle"
},
{
"code": null,
"e": 7729,
"s": 7716,
"text": "Mathematical"
},
{
"code": null,
"e": 7742,
"s": 7729,
"text": "Mathematical"
},
{
"code": null,
"e": 7840,
"s": 7742,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7872,
"s": 7840,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 7918,
"s": 7872,
"text": "Merge two sorted arrays with O(1) extra space"
},
{
"code": null,
"e": 7962,
"s": 7918,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 8004,
"s": 7962,
"text": "Segment Tree | Set 1 (Sum of given range)"
},
{
"code": null,
"e": 8066,
"s": 8004,
"text": "Sum of the series (1*2) + (2*3) + (3*4) + ...... upto n terms"
},
{
"code": null,
"e": 8098,
"s": 8066,
"text": "Check if a number is Palindrome"
},
{
"code": null,
"e": 8133,
"s": 8098,
"text": "Count ways to reach the n'th stair"
},
{
"code": null,
"e": 8158,
"s": 8133,
"text": "Fizz Buzz Implementation"
},
{
"code": null,
"e": 8199,
"s": 8158,
"text": "Median of two sorted arrays of same size"
}
] |
Sum of all numbers that can be formed with permutations of n digits | 05 Jul, 2022
Given n distinct digits (from 0 to 9), find sum of all n digit numbers that can be formed using these digits. It is assumed that numbers formed with leading 0 are allowed.
Example:
Input: 1 2 3
Output: 1332
Explanation
Numbers Formed: 123 , 132 , 312 , 213, 231 , 321
123 + 132 + 312 + 213 + 231 + 321 = 1332
Total numbers that can be formed using n digits is total number of permutations of n digits, i.e factorial(n). Now, since the number formed is a n-digit number, each digit will appear factorial(n)/n times at each position from least significant digit to most significant digit. Therefore, sum of digits at a position = (sum of all the digits) * (factorial(n)/n).
Considering the example digits as 1 2 3
factorial(3)/3 = 2
Sum of digits at least significant digit = (1 + 2 + 3) * 2 = 12
Similarly sum of digits at tens, hundreds place is 12.
(This sum will contribute as 12 * 100)
Similarly sum of digits at tens, thousands place is 12.
(This sum will contribute as 12 * 1000)
Required sum of all numbers = 12 + (10 * 12) + (100 * 12) = 1332
Implementation:
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find sun of numbers formed// by all permutations of given set of digits#include<stdio.h> // function to calculate factorial of a numberint factorial(int n){ int f = 1; if (n==0||n==1) return 1; for (int i=2; i<=n; i++) f = f*i; return f;} // Function to calculate sum of all numbersint getSum(int arr[],int n){ // calculate factorial int fact = factorial(n); // sum of all the given digits at different // positions is same and is going to be stored // in digitsum. int digitsum = 0; for (int i=0; i<n; i++) digitsum += arr[i]; digitsum *= (fact/n); // Compute result (sum of all the numbers) int res = 0; for (int i=1, k=1; i<=n; i++) { res += (k*digitsum); k = k*10; } return res;} // Driver program to test above functionint main(){ // n distinct digits int arr[] = {1, 2, 3}; int n = sizeof(arr)/sizeof(arr[0]); // Print sum of all the numbers formed printf("%d", getSum(arr, n)); return 0;}
// Java program to find sum// of numbers formed by all// permutations of given set// of digitsimport java.io.*; class GFG{ // function to calculate// factorial of a numberstatic int factorial(int n){ int f = 1; if (n == 0|| n == 1) return 1; for (int i = 2; i <= n; i++) f = f * i; return f;} // Function to calculate// sum of all numbersstatic int getSum(int arr[], int n){ // calculate factorial int fact = factorial(n); // sum of all the given // digits at different // positions is same and // is going to be stored // in digitsum. int digitsum = 0; for (int i = 0; i < n; i++) digitsum += arr[i]; digitsum *= (fact / n); // Compute result (sum // of all the numbers) int res = 0; for (int i = 1, k = 1; i <= n; i++) { res += (k * digitsum); k = k * 10; } return res;} // Driver Codepublic static void main (String[] args){ // n distinct digits int arr[] = {1, 2, 3}; int n = arr.length; // Print sum of all // the numbers formed System.out.println(getSum(arr, n));}} // This code is contributed// by ajit
# Python3 program to find sun of# numbers formed by all permutations# of given set of digits # function to calculate factorial# of a numberdef factorial(n): f = 1 if (n == 0 or n == 1): return 1 for i in range(2, n + 1): f = f * i return f # Function to calculate sum# of all numbersdef getSum(arr, n): # calculate factorial fact = factorial(n) # sum of all the given digits at # different positions is same and # is going to be stored in digitsum. digitsum = 0 for i in range(n): digitsum += arr[i] digitsum *= (fact // n) # Compute result (sum of # all the numbers) res = 0 i = 1 k = 1 while i <= n : res += (k * digitsum) k = k * 10 i += 1 return res # Driver Codeif __name__ == "__main__": # n distinct digits arr = [1, 2, 3] n = len(arr) # Print sum of all the numbers formed print(getSum(arr, n)) # This code is contributed by ita_c
// C# program to find sum// of numbers formed by all// permutations of given set// of digitsusing System; class GFG{ // function to calculate// factorial of a numberstatic int factorial(int n){ int f = 1; if (n == 0|| n == 1) return 1; for (int i = 2; i <= n; i++) f = f * i; return f;} // Function to calculate// sum of all numbersstatic int getSum(int []arr, int n){ // calculate factorial int fact = factorial(n); // sum of all the given // digits at different // positions is same and // is going to be stored // in digitsum. int digitsum = 0; for (int i = 0; i < n; i++) digitsum += arr[i]; digitsum *= (fact / n); // Compute result (sum // of all the numbers) int res = 0; for (int i = 1, k = 1; i <= n; i++) { res += (k * digitsum); k = k * 10; } return res;} // Driver Codestatic public void Main (){ // n distinct digits int []arr = {1, 2, 3}; int n = arr.Length; // Print sum of all // the numbers formed Console.WriteLine(getSum(arr, n));}} // This code is contributed// by akt_mit
<?php// PHP program to find sum// of numbers formed by all// permutations of given set// of digits function to// calculate factorial of a numberfunction factorial($n){ $f = 1; if ($n == 0||$n == 1) return 1; for ($i = 2; $i <= $n; $i++) $f = $f * $i; return $f;} // Function to calculate// sum of all numbersfunction getSum($arr,$n){ // calculate factorial $fact = factorial($n); // sum of all the given // digits at different // positions is same and // is going to be stored // in digitsum. $digitsum = 0; for ($i = 0; $i < $n; $i++) $digitsum += $arr[$i]; $digitsum *= ($fact / $n); // Compute result (sum // of all the numbers) $res = 0; for ($i = 1, $k = 1; $i <= $n; $i++) { $res += ($k * $digitsum); $k = $k * 10; } return $res;} // Driver Code // n distinct digits$arr = array(1, 2, 3);$n = sizeof($arr); // Print sum of all// the numbers formedecho getSum($arr, $n); // This code is contributed by ajit?>
<script> // Javascript program to find sum of// numbers formed by all permutations// of given set of digits // Function to calculate// factorial of a numberfunction factorial(n){ let f = 1; if (n == 0 || n == 1) return 1; for (let i = 2; i <= n; i++) f = f * i; return f;} // Function to calculate// sum of all numbersfunction getSum(arr, n){ // Calculate factorial let fact = factorial(n); // Sum of all the given // digits at different // positions is same and // is going to be stored // in digitsum. let digitsum = 0; for (let i = 0; i < n; i++) digitsum += arr[i]; digitsum *= (fact / n); // Compute result (sum // of all the numbers) let res = 0; for(let i = 1, k = 1; i <= n; i++) { res += (k * digitsum); k = k * 10; } return res;} // Driver code // n distinct digitslet arr = [1, 2, 3];let n = arr.length; // Print sum of all// the numbers formeddocument.write(getSum(arr, n)); // This code is contributed by susmitakundugoaldanga </script>
1332
Time Complexity: O(n)Auxiliary Space: O(1)
This article is contributed by Harsh Agarwal. 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.
jit_t
ukasp
subham348
susmitakundugoaldanga
hardikkoriintern
Modular Arithmetic
number-digits
permutation
Arrays
Combinatorial
Arrays
permutation
Combinatorial
Modular Arithmetic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Stack Data Structure (Introduction and Program)
Linear Search
Write a program to print all permutations of a given string
Permutation and Combination in Python
Factorial of a large number
Count of subsets with sum equal to X
itertools.combinations() module in Python to print all possible combinations | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n05 Jul, 2022"
},
{
"code": null,
"e": 226,
"s": 54,
"text": "Given n distinct digits (from 0 to 9), find sum of all n digit numbers that can be formed using these digits. It is assumed that numbers formed with leading 0 are allowed."
},
{
"code": null,
"e": 236,
"s": 226,
"text": "Example: "
},
{
"code": null,
"e": 364,
"s": 236,
"text": "Input: 1 2 3\nOutput: 1332\nExplanation\nNumbers Formed: 123 , 132 , 312 , 213, 231 , 321\n123 + 132 + 312 + 213 + 231 + 321 = 1332"
},
{
"code": null,
"e": 728,
"s": 364,
"text": "Total numbers that can be formed using n digits is total number of permutations of n digits, i.e factorial(n). Now, since the number formed is a n-digit number, each digit will appear factorial(n)/n times at each position from least significant digit to most significant digit. Therefore, sum of digits at a position = (sum of all the digits) * (factorial(n)/n). "
},
{
"code": null,
"e": 1113,
"s": 728,
"text": "Considering the example digits as 1 2 3\n\nfactorial(3)/3 = 2\n\nSum of digits at least significant digit = (1 + 2 + 3) * 2 = 12\n\nSimilarly sum of digits at tens, hundreds place is 12. \n(This sum will contribute as 12 * 100)\n\nSimilarly sum of digits at tens, thousands place is 12. \n(This sum will contribute as 12 * 1000)\n\nRequired sum of all numbers = 12 + (10 * 12) + (100 * 12) = 1332"
},
{
"code": null,
"e": 1129,
"s": 1113,
"text": "Implementation:"
},
{
"code": null,
"e": 1133,
"s": 1129,
"text": "C++"
},
{
"code": null,
"e": 1138,
"s": 1133,
"text": "Java"
},
{
"code": null,
"e": 1146,
"s": 1138,
"text": "Python3"
},
{
"code": null,
"e": 1149,
"s": 1146,
"text": "C#"
},
{
"code": null,
"e": 1153,
"s": 1149,
"text": "PHP"
},
{
"code": null,
"e": 1164,
"s": 1153,
"text": "Javascript"
},
{
"code": "// C++ program to find sun of numbers formed// by all permutations of given set of digits#include<stdio.h> // function to calculate factorial of a numberint factorial(int n){ int f = 1; if (n==0||n==1) return 1; for (int i=2; i<=n; i++) f = f*i; return f;} // Function to calculate sum of all numbersint getSum(int arr[],int n){ // calculate factorial int fact = factorial(n); // sum of all the given digits at different // positions is same and is going to be stored // in digitsum. int digitsum = 0; for (int i=0; i<n; i++) digitsum += arr[i]; digitsum *= (fact/n); // Compute result (sum of all the numbers) int res = 0; for (int i=1, k=1; i<=n; i++) { res += (k*digitsum); k = k*10; } return res;} // Driver program to test above functionint main(){ // n distinct digits int arr[] = {1, 2, 3}; int n = sizeof(arr)/sizeof(arr[0]); // Print sum of all the numbers formed printf(\"%d\", getSum(arr, n)); return 0;}",
"e": 2191,
"s": 1164,
"text": null
},
{
"code": "// Java program to find sum// of numbers formed by all// permutations of given set// of digitsimport java.io.*; class GFG{ // function to calculate// factorial of a numberstatic int factorial(int n){ int f = 1; if (n == 0|| n == 1) return 1; for (int i = 2; i <= n; i++) f = f * i; return f;} // Function to calculate// sum of all numbersstatic int getSum(int arr[], int n){ // calculate factorial int fact = factorial(n); // sum of all the given // digits at different // positions is same and // is going to be stored // in digitsum. int digitsum = 0; for (int i = 0; i < n; i++) digitsum += arr[i]; digitsum *= (fact / n); // Compute result (sum // of all the numbers) int res = 0; for (int i = 1, k = 1; i <= n; i++) { res += (k * digitsum); k = k * 10; } return res;} // Driver Codepublic static void main (String[] args){ // n distinct digits int arr[] = {1, 2, 3}; int n = arr.length; // Print sum of all // the numbers formed System.out.println(getSum(arr, n));}} // This code is contributed// by ajit",
"e": 3342,
"s": 2191,
"text": null
},
{
"code": "# Python3 program to find sun of# numbers formed by all permutations# of given set of digits # function to calculate factorial# of a numberdef factorial(n): f = 1 if (n == 0 or n == 1): return 1 for i in range(2, n + 1): f = f * i return f # Function to calculate sum# of all numbersdef getSum(arr, n): # calculate factorial fact = factorial(n) # sum of all the given digits at # different positions is same and # is going to be stored in digitsum. digitsum = 0 for i in range(n): digitsum += arr[i] digitsum *= (fact // n) # Compute result (sum of # all the numbers) res = 0 i = 1 k = 1 while i <= n : res += (k * digitsum) k = k * 10 i += 1 return res # Driver Codeif __name__ == \"__main__\": # n distinct digits arr = [1, 2, 3] n = len(arr) # Print sum of all the numbers formed print(getSum(arr, n)) # This code is contributed by ita_c",
"e": 4306,
"s": 3342,
"text": null
},
{
"code": "// C# program to find sum// of numbers formed by all// permutations of given set// of digitsusing System; class GFG{ // function to calculate// factorial of a numberstatic int factorial(int n){ int f = 1; if (n == 0|| n == 1) return 1; for (int i = 2; i <= n; i++) f = f * i; return f;} // Function to calculate// sum of all numbersstatic int getSum(int []arr, int n){ // calculate factorial int fact = factorial(n); // sum of all the given // digits at different // positions is same and // is going to be stored // in digitsum. int digitsum = 0; for (int i = 0; i < n; i++) digitsum += arr[i]; digitsum *= (fact / n); // Compute result (sum // of all the numbers) int res = 0; for (int i = 1, k = 1; i <= n; i++) { res += (k * digitsum); k = k * 10; } return res;} // Driver Codestatic public void Main (){ // n distinct digits int []arr = {1, 2, 3}; int n = arr.Length; // Print sum of all // the numbers formed Console.WriteLine(getSum(arr, n));}} // This code is contributed// by akt_mit",
"e": 5456,
"s": 4306,
"text": null
},
{
"code": "<?php// PHP program to find sum// of numbers formed by all// permutations of given set// of digits function to// calculate factorial of a numberfunction factorial($n){ $f = 1; if ($n == 0||$n == 1) return 1; for ($i = 2; $i <= $n; $i++) $f = $f * $i; return $f;} // Function to calculate// sum of all numbersfunction getSum($arr,$n){ // calculate factorial $fact = factorial($n); // sum of all the given // digits at different // positions is same and // is going to be stored // in digitsum. $digitsum = 0; for ($i = 0; $i < $n; $i++) $digitsum += $arr[$i]; $digitsum *= ($fact / $n); // Compute result (sum // of all the numbers) $res = 0; for ($i = 1, $k = 1; $i <= $n; $i++) { $res += ($k * $digitsum); $k = $k * 10; } return $res;} // Driver Code // n distinct digits$arr = array(1, 2, 3);$n = sizeof($arr); // Print sum of all// the numbers formedecho getSum($arr, $n); // This code is contributed by ajit?>",
"e": 6471,
"s": 5456,
"text": null
},
{
"code": "<script> // Javascript program to find sum of// numbers formed by all permutations// of given set of digits // Function to calculate// factorial of a numberfunction factorial(n){ let f = 1; if (n == 0 || n == 1) return 1; for (let i = 2; i <= n; i++) f = f * i; return f;} // Function to calculate// sum of all numbersfunction getSum(arr, n){ // Calculate factorial let fact = factorial(n); // Sum of all the given // digits at different // positions is same and // is going to be stored // in digitsum. let digitsum = 0; for (let i = 0; i < n; i++) digitsum += arr[i]; digitsum *= (fact / n); // Compute result (sum // of all the numbers) let res = 0; for(let i = 1, k = 1; i <= n; i++) { res += (k * digitsum); k = k * 10; } return res;} // Driver code // n distinct digitslet arr = [1, 2, 3];let n = arr.length; // Print sum of all// the numbers formeddocument.write(getSum(arr, n)); // This code is contributed by susmitakundugoaldanga </script>",
"e": 7577,
"s": 6471,
"text": null
},
{
"code": null,
"e": 7582,
"s": 7577,
"text": "1332"
},
{
"code": null,
"e": 7625,
"s": 7582,
"text": "Time Complexity: O(n)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 7923,
"s": 7625,
"text": "This article is contributed by Harsh Agarwal. 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": 7929,
"s": 7923,
"text": "jit_t"
},
{
"code": null,
"e": 7935,
"s": 7929,
"text": "ukasp"
},
{
"code": null,
"e": 7945,
"s": 7935,
"text": "subham348"
},
{
"code": null,
"e": 7967,
"s": 7945,
"text": "susmitakundugoaldanga"
},
{
"code": null,
"e": 7984,
"s": 7967,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 8003,
"s": 7984,
"text": "Modular Arithmetic"
},
{
"code": null,
"e": 8017,
"s": 8003,
"text": "number-digits"
},
{
"code": null,
"e": 8029,
"s": 8017,
"text": "permutation"
},
{
"code": null,
"e": 8036,
"s": 8029,
"text": "Arrays"
},
{
"code": null,
"e": 8050,
"s": 8036,
"text": "Combinatorial"
},
{
"code": null,
"e": 8057,
"s": 8050,
"text": "Arrays"
},
{
"code": null,
"e": 8069,
"s": 8057,
"text": "permutation"
},
{
"code": null,
"e": 8083,
"s": 8069,
"text": "Combinatorial"
},
{
"code": null,
"e": 8102,
"s": 8083,
"text": "Modular Arithmetic"
},
{
"code": null,
"e": 8200,
"s": 8102,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8268,
"s": 8200,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 8312,
"s": 8268,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 8344,
"s": 8312,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 8392,
"s": 8344,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 8406,
"s": 8392,
"text": "Linear Search"
},
{
"code": null,
"e": 8466,
"s": 8406,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 8504,
"s": 8466,
"text": "Permutation and Combination in Python"
},
{
"code": null,
"e": 8532,
"s": 8504,
"text": "Factorial of a large number"
},
{
"code": null,
"e": 8569,
"s": 8532,
"text": "Count of subsets with sum equal to X"
}
] |
How to populate virtuals to a mongoose model using Node.js ? | 01 Jun, 2021
In Mongoose, the virtual is the property that is not stored in the database, they only exist logically, and you cannot query directly on the basis of this property. To know more about virtual refers to this article Mongoose Virtuals.
Populating Virtuals:
In MongoDB, Population is the process of replacing the specified path in the document of one collection with the actual document from the other collection.
Mongoose also supports a population of virtual properties during their creation. Whenever we want our virtual property to refer to a model of any other collection we have to populate it so that it can contain the document(s) of the other collection.
Install Mongoose:
Step 1: You can visit the link Install mongoose to install the mongoose module. You can install this package by using this command.
npm install mongoose
Step 2: Now you can import the mongoose module in your file using:
const mongoose = require('mongoose');
Database: We have two collections users and posts in our database GFG.
users: The users collection has two users User1 and User2.
posts: The posts collection is empty.
Initially users and posts collection in database
Implementation:
Create a folder and add the file main.js.For populating virtual, we have to specify three necessary options:ref: It contains the name of the model from which we want to populate the document.localField: It is any field of the current collection.foreignField: It is any field of the collection from which we want to populate the document.
Create a folder and add the file main.js.
For populating virtual, we have to specify three necessary options:ref: It contains the name of the model from which we want to populate the document.localField: It is any field of the current collection.foreignField: It is any field of the collection from which we want to populate the document.
ref: It contains the name of the model from which we want to populate the document.
localField: It is any field of the current collection.
foreignField: It is any field of the collection from which we want to populate the document.
Mongoose will populate those documents from the model given in ref, whose foreignField value will match with the localField value of the current collection.
Example: Now we will see how to populate virtuals to a mongoose model using Node.js.
main.js
// Requiring moduleconst mongoose = require('mongoose'); // Connecting to databasemongoose.connect('mongodb://localhost:27017/GFG', { useNewUrlParser: true, useUnifiedTopology: true, useFindAndModify: false }); // User Schemaconst userSchema = new mongoose.Schema({ username: String, email: String}) // Post Schemaconst postSchema = new mongoose.Schema({ title: String, postedBy: mongoose.Schema.Types.ObjectId}) // Creating and populating virtual property 'user' in postSchema// will populate the documents from user collection if // their '_id' matches with the 'postedBy' of the postpostSchema.virtual('user', { ref: 'User', localField: 'postedBy', // Of post collection foreignField: '_id', // Of user collection justOne: true}) // Creating user and post models const User = mongoose.model('User', userSchema);const Post = mongoose.model('Post', postSchema); // Function to create a post by the userconst createPost = async (next) => { const user = await User.findOne({ _id: '60acfa48e82a52560c32ec0a' }); const newPost = new Post({ title: 'Post 1', postedBy: user._id }) const postSaved = await newPost.save(); console.log("post created"); // The findPost will be called after the post is created next();} // Function to find the post and show the virtual propertyconst findPost = async () => { const post = await Post.findOne().populate('user'); console.log(post.user);} // Creating the post then showing the virtual property on consolecreatePost(findPost);
Run main.js using the command:
node main.js
Output:
Output after executing main.js
Explanation: Here we are finding User 1 by _id field and then creating a post whose postedBy field value will be the User 1 _id field value (hence the post is created by User 1). Whenever a post will be created, a virtual property ‘user’ will be created for the post which would be populated with the document of the User model whose _id field value matches with the postedBy value of the post.
Database: After creating a post with a populated virtual property user, we can see Post 1 in posts collection of our database. But here we cannot see the property user in the database because it’s a virtual property, and it doesn’t get stored in the database.
Posts collection after creating the post with populated virtual
Mongoose
NodeJS-Questions
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 Jun, 2021"
},
{
"code": null,
"e": 262,
"s": 28,
"text": "In Mongoose, the virtual is the property that is not stored in the database, they only exist logically, and you cannot query directly on the basis of this property. To know more about virtual refers to this article Mongoose Virtuals."
},
{
"code": null,
"e": 284,
"s": 262,
"text": "Populating Virtuals: "
},
{
"code": null,
"e": 440,
"s": 284,
"text": "In MongoDB, Population is the process of replacing the specified path in the document of one collection with the actual document from the other collection."
},
{
"code": null,
"e": 690,
"s": 440,
"text": "Mongoose also supports a population of virtual properties during their creation. Whenever we want our virtual property to refer to a model of any other collection we have to populate it so that it can contain the document(s) of the other collection."
},
{
"code": null,
"e": 708,
"s": 690,
"text": "Install Mongoose:"
},
{
"code": null,
"e": 840,
"s": 708,
"text": "Step 1: You can visit the link Install mongoose to install the mongoose module. You can install this package by using this command."
},
{
"code": null,
"e": 861,
"s": 840,
"text": "npm install mongoose"
},
{
"code": null,
"e": 928,
"s": 861,
"text": "Step 2: Now you can import the mongoose module in your file using:"
},
{
"code": null,
"e": 966,
"s": 928,
"text": "const mongoose = require('mongoose');"
},
{
"code": null,
"e": 1038,
"s": 966,
"text": "Database: We have two collections users and posts in our database GFG. "
},
{
"code": null,
"e": 1097,
"s": 1038,
"text": "users: The users collection has two users User1 and User2."
},
{
"code": null,
"e": 1135,
"s": 1097,
"text": "posts: The posts collection is empty."
},
{
"code": null,
"e": 1184,
"s": 1135,
"text": "Initially users and posts collection in database"
},
{
"code": null,
"e": 1200,
"s": 1184,
"text": "Implementation:"
},
{
"code": null,
"e": 1538,
"s": 1200,
"text": "Create a folder and add the file main.js.For populating virtual, we have to specify three necessary options:ref: It contains the name of the model from which we want to populate the document.localField: It is any field of the current collection.foreignField: It is any field of the collection from which we want to populate the document."
},
{
"code": null,
"e": 1580,
"s": 1538,
"text": "Create a folder and add the file main.js."
},
{
"code": null,
"e": 1877,
"s": 1580,
"text": "For populating virtual, we have to specify three necessary options:ref: It contains the name of the model from which we want to populate the document.localField: It is any field of the current collection.foreignField: It is any field of the collection from which we want to populate the document."
},
{
"code": null,
"e": 1961,
"s": 1877,
"text": "ref: It contains the name of the model from which we want to populate the document."
},
{
"code": null,
"e": 2016,
"s": 1961,
"text": "localField: It is any field of the current collection."
},
{
"code": null,
"e": 2109,
"s": 2016,
"text": "foreignField: It is any field of the collection from which we want to populate the document."
},
{
"code": null,
"e": 2266,
"s": 2109,
"text": "Mongoose will populate those documents from the model given in ref, whose foreignField value will match with the localField value of the current collection."
},
{
"code": null,
"e": 2351,
"s": 2266,
"text": "Example: Now we will see how to populate virtuals to a mongoose model using Node.js."
},
{
"code": null,
"e": 2359,
"s": 2351,
"text": "main.js"
},
{
"code": "// Requiring moduleconst mongoose = require('mongoose'); // Connecting to databasemongoose.connect('mongodb://localhost:27017/GFG', { useNewUrlParser: true, useUnifiedTopology: true, useFindAndModify: false }); // User Schemaconst userSchema = new mongoose.Schema({ username: String, email: String}) // Post Schemaconst postSchema = new mongoose.Schema({ title: String, postedBy: mongoose.Schema.Types.ObjectId}) // Creating and populating virtual property 'user' in postSchema// will populate the documents from user collection if // their '_id' matches with the 'postedBy' of the postpostSchema.virtual('user', { ref: 'User', localField: 'postedBy', // Of post collection foreignField: '_id', // Of user collection justOne: true}) // Creating user and post models const User = mongoose.model('User', userSchema);const Post = mongoose.model('Post', postSchema); // Function to create a post by the userconst createPost = async (next) => { const user = await User.findOne({ _id: '60acfa48e82a52560c32ec0a' }); const newPost = new Post({ title: 'Post 1', postedBy: user._id }) const postSaved = await newPost.save(); console.log(\"post created\"); // The findPost will be called after the post is created next();} // Function to find the post and show the virtual propertyconst findPost = async () => { const post = await Post.findOne().populate('user'); console.log(post.user);} // Creating the post then showing the virtual property on consolecreatePost(findPost);",
"e": 3932,
"s": 2359,
"text": null
},
{
"code": null,
"e": 3963,
"s": 3932,
"text": "Run main.js using the command:"
},
{
"code": null,
"e": 3976,
"s": 3963,
"text": "node main.js"
},
{
"code": null,
"e": 3986,
"s": 3976,
"text": "Output: "
},
{
"code": null,
"e": 4017,
"s": 3986,
"text": "Output after executing main.js"
},
{
"code": null,
"e": 4412,
"s": 4017,
"text": "Explanation: Here we are finding User 1 by _id field and then creating a post whose postedBy field value will be the User 1 _id field value (hence the post is created by User 1). Whenever a post will be created, a virtual property ‘user’ will be created for the post which would be populated with the document of the User model whose _id field value matches with the postedBy value of the post."
},
{
"code": null,
"e": 4672,
"s": 4412,
"text": "Database: After creating a post with a populated virtual property user, we can see Post 1 in posts collection of our database. But here we cannot see the property user in the database because it’s a virtual property, and it doesn’t get stored in the database."
},
{
"code": null,
"e": 4736,
"s": 4672,
"text": "Posts collection after creating the post with populated virtual"
},
{
"code": null,
"e": 4745,
"s": 4736,
"text": "Mongoose"
},
{
"code": null,
"e": 4762,
"s": 4745,
"text": "NodeJS-Questions"
},
{
"code": null,
"e": 4769,
"s": 4762,
"text": "Picked"
},
{
"code": null,
"e": 4777,
"s": 4769,
"text": "Node.js"
},
{
"code": null,
"e": 4794,
"s": 4777,
"text": "Web Technologies"
}
] |
Flutter – Modal Bottom Sheet | 21 Jun, 2022
Modal Bottom Sheet is an alternative to a menu or a dialog and prevents the user from interacting with the rest of the app. It will appear over the UI so that there is no need to navigate to a different page. It can be used to perform a small task that does not require the whole new screen to be built.
Future<T> showModalBottomSheet <T>(
{@required BuildContext context,
@required WidgetBuilder builder,
Color backgroundColor,
double elevation,
ShapeBorder shape,
Clip clipBehavior,
Color barrierColor,
bool isScrollControlled: false,
bool useRootNavigator: false,
bool isDismissible: true,
bool enableDrag: true,
RouteSettings routeSettings}
)
builder: A builder for the contents of the sheet.
backgroundColor: To display background color.
elevation: Elevates the snackbar by increasing shadow.
shape: Shape of the modal bottom sheet.
clipBehavior: The content will be clipped according to this option.
barrierColor: Color to display in the background after the modal bottom sheet is displayed.
isScrollControlled: Enable or disable scrolling.
useRootNavigator: The useRootNavigator parameter ensures that the root navigator is used to display the BottomSheet when set to true.
isDismissible: Specifies whether the user can dismiss modal bottom sheet by tapping on the scrim.
enableDrag: The enableDrag parameter specifies whether the bottom sheet can be dragged up and down and dismissed by swiping downwards.
routeSettings: Sets the RouteSettings of the modal bottom sheet.
Note: The context and builder have @required class applied which means these parameters are mandatory to use.
Implementation:
Dart
import 'package:flutter/material.dart'; void main() => runApp(const MyApp()); // This is the main application widget.class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp( title: 'GeeksforGeeks', home: Scaffold( appBar: AppBar( title: const Text('GeeksforGeeks'), backgroundColor: Colors.green, ), body: const ModalBottomSheetDemo(), ), ); }} class ModalBottomSheetDemo extends StatelessWidget { const ModalBottomSheetDemo({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Center( child: ElevatedButton( child: const Text('showModalBottomSheet'), onPressed: () { // when raised button is pressed // we display showModalBottomSheet showModalBottomSheet<void>( // context and builder are // required properties in this widget context: context, builder: (BuildContext context) { // we set up a container inside which // we create center column and display text // Returning SizedBox instead of a Container return SizedBox( height: 200, child: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: const <Widget>[ Text('GeeksforGeeks'), ], ), ), ); }, ); }, ), // RaisedButton is deprecated and should not be used // Use ElevatedButton instead. // child: RaisedButton( // child: const Text('showModalBottomSheet'), // onPressed: () { // // when raised button is pressed // // we display showModalBottomSheet // showModalBottomSheet<void>( // // context and builder are // // required properties in this widget // context: context, // builder: (BuildContext context) { // // we set up a container inside which // // we create center column and display text // return Container( // height: 200, // child: Center( // child: Column( // mainAxisAlignment: MainAxisAlignment.center, // children: <Widget>[ // const Text('GeeksforGeeks'), // ], // ), // ), // ); // }, // ); // }, // ), ); }}
Output:
Explanation: Here we have created 2 stateless widgets where the first stateless widget is used to build our main screen using the material app. In the first stateless widget, we have defined our appbar inside the scaffold and call to our second stateless widget.
In the second stateless widget we are building content inside our main screen. Here we created a raised button named showmodalbottomsheet button. When we press on it, it displays modal bottom sheet inside which we added builder property which displays text geeksforgeeks inside the column.
Dart
import 'package:flutter/material.dart'; void main() => runApp(const MyApp()); /// This is the main application widget.class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp( title: 'GeeksforGeeks', home: Scaffold( appBar: AppBar( title: const Text('GeeksforGeeks'), backgroundColor: Colors.green, ), body: const ModalBottomSheetDemo(), ), ); }} class ModalBottomSheetDemo extends StatelessWidget { const ModalBottomSheetDemo({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Center( // REPLACED: RaisedButton class with Elevated button class. // Raisedbutton is deprecatred and shouldn't be used. child: ElevatedButton( child: const Text('showModalBottomSheet'), onPressed: () { // adding some properties showModalBottomSheet( context: context, // color is applied to main screen when modal bottom screen is displayed barrierColor: Colors.greenAccent, //background color for modal bottom screen backgroundColor: Colors.yellow, //elevates modal bottom screen elevation: 10, // gives rounded corner to modal bottom screen shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10.0), ), builder: (BuildContext context) { // UDE : SizedBox instead of Container for whitespaces return SizedBox( height: 200, child: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: const <Widget>[ Text('GeeksforGeeks'), ], ), ), ); }, ); }, ), ); }}
Output:
Explanation: In above code we added some properties like barrierColor, backgroundColor, shape, and elevation.
ankit_kumar_
android
Flutter
Picked
Flutter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Flutter - Custom Bottom Navigation Bar
Flutter - Stack Widget
Flutter - Search Bar
Flutter - Dialogs
Flutter - FutureBuilder Widget
Flutter - Flexible Widget
Flutter - File Structure
Flutter - Pop Up Menu
Flutter - AppBar Widget
Flutter - CircleAvatar Widget | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Jun, 2022"
},
{
"code": null,
"e": 332,
"s": 28,
"text": "Modal Bottom Sheet is an alternative to a menu or a dialog and prevents the user from interacting with the rest of the app. It will appear over the UI so that there is no need to navigate to a different page. It can be used to perform a small task that does not require the whole new screen to be built."
},
{
"code": null,
"e": 675,
"s": 332,
"text": "Future<T> showModalBottomSheet <T>(\n{@required BuildContext context,\n@required WidgetBuilder builder,\nColor backgroundColor,\ndouble elevation,\nShapeBorder shape,\nClip clipBehavior,\nColor barrierColor,\nbool isScrollControlled: false,\nbool useRootNavigator: false,\nbool isDismissible: true,\nbool enableDrag: true,\nRouteSettings routeSettings}\n)"
},
{
"code": null,
"e": 725,
"s": 675,
"text": "builder: A builder for the contents of the sheet."
},
{
"code": null,
"e": 771,
"s": 725,
"text": "backgroundColor: To display background color."
},
{
"code": null,
"e": 826,
"s": 771,
"text": "elevation: Elevates the snackbar by increasing shadow."
},
{
"code": null,
"e": 866,
"s": 826,
"text": "shape: Shape of the modal bottom sheet."
},
{
"code": null,
"e": 934,
"s": 866,
"text": "clipBehavior: The content will be clipped according to this option."
},
{
"code": null,
"e": 1027,
"s": 934,
"text": " barrierColor: Color to display in the background after the modal bottom sheet is displayed."
},
{
"code": null,
"e": 1076,
"s": 1027,
"text": "isScrollControlled: Enable or disable scrolling."
},
{
"code": null,
"e": 1211,
"s": 1076,
"text": " useRootNavigator: The useRootNavigator parameter ensures that the root navigator is used to display the BottomSheet when set to true."
},
{
"code": null,
"e": 1310,
"s": 1211,
"text": " isDismissible: Specifies whether the user can dismiss modal bottom sheet by tapping on the scrim."
},
{
"code": null,
"e": 1446,
"s": 1310,
"text": " enableDrag: The enableDrag parameter specifies whether the bottom sheet can be dragged up and down and dismissed by swiping downwards."
},
{
"code": null,
"e": 1512,
"s": 1446,
"text": " routeSettings: Sets the RouteSettings of the modal bottom sheet."
},
{
"code": null,
"e": 1623,
"s": 1512,
"text": "Note: The context and builder have @required class applied which means these parameters are mandatory to use. "
},
{
"code": null,
"e": 1639,
"s": 1623,
"text": "Implementation:"
},
{
"code": null,
"e": 1644,
"s": 1639,
"text": "Dart"
},
{
"code": "import 'package:flutter/material.dart'; void main() => runApp(const MyApp()); // This is the main application widget.class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp( title: 'GeeksforGeeks', home: Scaffold( appBar: AppBar( title: const Text('GeeksforGeeks'), backgroundColor: Colors.green, ), body: const ModalBottomSheetDemo(), ), ); }} class ModalBottomSheetDemo extends StatelessWidget { const ModalBottomSheetDemo({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Center( child: ElevatedButton( child: const Text('showModalBottomSheet'), onPressed: () { // when raised button is pressed // we display showModalBottomSheet showModalBottomSheet<void>( // context and builder are // required properties in this widget context: context, builder: (BuildContext context) { // we set up a container inside which // we create center column and display text // Returning SizedBox instead of a Container return SizedBox( height: 200, child: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: const <Widget>[ Text('GeeksforGeeks'), ], ), ), ); }, ); }, ), // RaisedButton is deprecated and should not be used // Use ElevatedButton instead. // child: RaisedButton( // child: const Text('showModalBottomSheet'), // onPressed: () { // // when raised button is pressed // // we display showModalBottomSheet // showModalBottomSheet<void>( // // context and builder are // // required properties in this widget // context: context, // builder: (BuildContext context) { // // we set up a container inside which // // we create center column and display text // return Container( // height: 200, // child: Center( // child: Column( // mainAxisAlignment: MainAxisAlignment.center, // children: <Widget>[ // const Text('GeeksforGeeks'), // ], // ), // ), // ); // }, // ); // }, // ), ); }}",
"e": 4373,
"s": 1644,
"text": null
},
{
"code": null,
"e": 4381,
"s": 4373,
"text": "Output:"
},
{
"code": null,
"e": 4645,
"s": 4381,
"text": "Explanation: Here we have created 2 stateless widgets where the first stateless widget is used to build our main screen using the material app. In the first stateless widget, we have defined our appbar inside the scaffold and call to our second stateless widget. "
},
{
"code": null,
"e": 4935,
"s": 4645,
"text": "In the second stateless widget we are building content inside our main screen. Here we created a raised button named showmodalbottomsheet button. When we press on it, it displays modal bottom sheet inside which we added builder property which displays text geeksforgeeks inside the column."
},
{
"code": null,
"e": 4940,
"s": 4935,
"text": "Dart"
},
{
"code": "import 'package:flutter/material.dart'; void main() => runApp(const MyApp()); /// This is the main application widget.class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp( title: 'GeeksforGeeks', home: Scaffold( appBar: AppBar( title: const Text('GeeksforGeeks'), backgroundColor: Colors.green, ), body: const ModalBottomSheetDemo(), ), ); }} class ModalBottomSheetDemo extends StatelessWidget { const ModalBottomSheetDemo({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Center( // REPLACED: RaisedButton class with Elevated button class. // Raisedbutton is deprecatred and shouldn't be used. child: ElevatedButton( child: const Text('showModalBottomSheet'), onPressed: () { // adding some properties showModalBottomSheet( context: context, // color is applied to main screen when modal bottom screen is displayed barrierColor: Colors.greenAccent, //background color for modal bottom screen backgroundColor: Colors.yellow, //elevates modal bottom screen elevation: 10, // gives rounded corner to modal bottom screen shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10.0), ), builder: (BuildContext context) { // UDE : SizedBox instead of Container for whitespaces return SizedBox( height: 200, child: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: const <Widget>[ Text('GeeksforGeeks'), ], ), ), ); }, ); }, ), ); }}",
"e": 6929,
"s": 4940,
"text": null
},
{
"code": null,
"e": 6937,
"s": 6929,
"text": "Output:"
},
{
"code": null,
"e": 7047,
"s": 6937,
"text": "Explanation: In above code we added some properties like barrierColor, backgroundColor, shape, and elevation."
},
{
"code": null,
"e": 7060,
"s": 7047,
"text": "ankit_kumar_"
},
{
"code": null,
"e": 7068,
"s": 7060,
"text": "android"
},
{
"code": null,
"e": 7076,
"s": 7068,
"text": "Flutter"
},
{
"code": null,
"e": 7083,
"s": 7076,
"text": "Picked"
},
{
"code": null,
"e": 7091,
"s": 7083,
"text": "Flutter"
},
{
"code": null,
"e": 7189,
"s": 7091,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7228,
"s": 7189,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 7251,
"s": 7228,
"text": "Flutter - Stack Widget"
},
{
"code": null,
"e": 7272,
"s": 7251,
"text": "Flutter - Search Bar"
},
{
"code": null,
"e": 7290,
"s": 7272,
"text": "Flutter - Dialogs"
},
{
"code": null,
"e": 7321,
"s": 7290,
"text": "Flutter - FutureBuilder Widget"
},
{
"code": null,
"e": 7347,
"s": 7321,
"text": "Flutter - Flexible Widget"
},
{
"code": null,
"e": 7372,
"s": 7347,
"text": "Flutter - File Structure"
},
{
"code": null,
"e": 7394,
"s": 7372,
"text": "Flutter - Pop Up Menu"
},
{
"code": null,
"e": 7418,
"s": 7394,
"text": "Flutter - AppBar Widget"
}
] |
JavaScript for Capturing mouse positions after every given interval | 19 Feb, 2019
The JavaScript language was initially created for web browsers. Since then, it evolved and became a language with many uses and platforms. It lets us interact with browser using events. Events are signals that something has happened. When JavaScript is used in HTML pages, JavaScript can react on these events. To react on events we can assign a handler – a function that runs in case of an event. Handlers are a way to run JavaScript code in case of user actions.
In this article, we will be focusing on how to capture mouse positions on an empty HTML page in a time period of 10 seconds within a given interval of time. The page will be initially empty. On the first click, a timer will of 10 seconds will start and on ending the start time and the X and Y-coordinates of mouse positions will be displayed in form of JavaScript object.
The event handlers we will be using for this task will be:
1. movemouse: When the cursor of the mouse is moved.2. DOMContentLoaded: When the HTML is loaded and processed. DOM is fully built.
Here is the JavaScript program for the same:
<html> <head> <title>Timer Demo</title></head> <body> <div id="timer-section" style="text-align: center"> Timer will appear here!</div> <div id="output-section"></div> <script type="text/javascript"> // timervar limit = 10000; // time interval of 500 millisecond setvar throttle = 500; //timer is off initiallyvar timerON = false; var start ;var last ;var mousePositions = []; // records the time when the timer startsfunction makeTime(s) { return s.getHours() +" : " + s.getMinutes() + " : " + s.getSeconds();} // when the first click to start the timer,// this function will get envokedfunction clickEnvoke() { start = (new Date).getTime(); mousePositions.push({ time : { start : makeTime(new Date()) } }); console.log(mousePositions); last = (new Date).getTime(); var time = 10; // timer has started timerON = true; document.removeEventListener('click', clickEnvoke); document.addEventListener('mousemove', mouseUpdate); var timer = setInterval(function () { if (time >= 0) document.getElementById('timer-section').innerHTML = time; else{ // mouse positions will be stop recording as timer is 0 timerON = false; clearInterval(timer); document.removeEventListener('mousemove', mouseUpdate); // JSON data need to converted into string to print as object document.getElementById('timer-section').innerHTML = ""; document.getElementById('timer-section').innerHTML += JSON.stringify(mousePositions); } time--; }, 1000);} // capturing mouse positions envokedfunction mouseUpdate (event) { var now = (new Date).getTime(); if (timerON){ if (now - start > limit ) { return document.removeEventListener('mousemove', mouseUpdate); } if (now - last < throttle) { return; } last = now; mousePositions.push({ info : { x : event.pageX, y : event.pageY } }); } else console.log(mousePositions); // do whatever you want to do within your // time limit here} // initial HTML page is empty and DOM is loaded// upon first click our functions will workdocument.addEventListener('DOMContentLoaded', function () { var loadTime = (new Date).getTime(); document.addEventListener('click', clickEnvoke);});</script></body></html>
NOTE: We have to keep on moving the mouse cursor as soon as the timer starts else we may not get number of coordinates as desired.We will learn about more event handlers and related problems in the coming articles on “Using JavaScript to interact with the browser”.
JavaScript-Misc
javascrpt-input
JavaScript
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Feb, 2019"
},
{
"code": null,
"e": 493,
"s": 28,
"text": "The JavaScript language was initially created for web browsers. Since then, it evolved and became a language with many uses and platforms. It lets us interact with browser using events. Events are signals that something has happened. When JavaScript is used in HTML pages, JavaScript can react on these events. To react on events we can assign a handler – a function that runs in case of an event. Handlers are a way to run JavaScript code in case of user actions."
},
{
"code": null,
"e": 866,
"s": 493,
"text": "In this article, we will be focusing on how to capture mouse positions on an empty HTML page in a time period of 10 seconds within a given interval of time. The page will be initially empty. On the first click, a timer will of 10 seconds will start and on ending the start time and the X and Y-coordinates of mouse positions will be displayed in form of JavaScript object."
},
{
"code": null,
"e": 925,
"s": 866,
"text": "The event handlers we will be using for this task will be:"
},
{
"code": null,
"e": 1057,
"s": 925,
"text": "1. movemouse: When the cursor of the mouse is moved.2. DOMContentLoaded: When the HTML is loaded and processed. DOM is fully built."
},
{
"code": null,
"e": 1102,
"s": 1057,
"text": "Here is the JavaScript program for the same:"
},
{
"code": "<html> <head> <title>Timer Demo</title></head> <body> <div id=\"timer-section\" style=\"text-align: center\"> Timer will appear here!</div> <div id=\"output-section\"></div> <script type=\"text/javascript\"> // timervar limit = 10000; // time interval of 500 millisecond setvar throttle = 500; //timer is off initiallyvar timerON = false; var start ;var last ;var mousePositions = []; // records the time when the timer startsfunction makeTime(s) { return s.getHours() +\" : \" + s.getMinutes() + \" : \" + s.getSeconds();} // when the first click to start the timer,// this function will get envokedfunction clickEnvoke() { start = (new Date).getTime(); mousePositions.push({ time : { start : makeTime(new Date()) } }); console.log(mousePositions); last = (new Date).getTime(); var time = 10; // timer has started timerON = true; document.removeEventListener('click', clickEnvoke); document.addEventListener('mousemove', mouseUpdate); var timer = setInterval(function () { if (time >= 0) document.getElementById('timer-section').innerHTML = time; else{ // mouse positions will be stop recording as timer is 0 timerON = false; clearInterval(timer); document.removeEventListener('mousemove', mouseUpdate); // JSON data need to converted into string to print as object document.getElementById('timer-section').innerHTML = \"\"; document.getElementById('timer-section').innerHTML += JSON.stringify(mousePositions); } time--; }, 1000);} // capturing mouse positions envokedfunction mouseUpdate (event) { var now = (new Date).getTime(); if (timerON){ if (now - start > limit ) { return document.removeEventListener('mousemove', mouseUpdate); } if (now - last < throttle) { return; } last = now; mousePositions.push({ info : { x : event.pageX, y : event.pageY } }); } else console.log(mousePositions); // do whatever you want to do within your // time limit here} // initial HTML page is empty and DOM is loaded// upon first click our functions will workdocument.addEventListener('DOMContentLoaded', function () { var loadTime = (new Date).getTime(); document.addEventListener('click', clickEnvoke);});</script></body></html> ",
"e": 3634,
"s": 1102,
"text": null
},
{
"code": null,
"e": 3900,
"s": 3634,
"text": "NOTE: We have to keep on moving the mouse cursor as soon as the timer starts else we may not get number of coordinates as desired.We will learn about more event handlers and related problems in the coming articles on “Using JavaScript to interact with the browser”."
},
{
"code": null,
"e": 3916,
"s": 3900,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 3932,
"s": 3916,
"text": "javascrpt-input"
},
{
"code": null,
"e": 3943,
"s": 3932,
"text": "JavaScript"
}
] |
Valid Sudoku in C++ | Let’s suppose we’ve given a 9×9 matrix called a Sudoku. The task is to check whether the given Sudoku Pattern is valid or not.
In general, a Sudoku board look like this,
Rules of Sudoku −
Every row contains a number in the range 1-9
Every row contains a number in the range 1-9
Every column contains numbers in the range 1-9.
Every column contains numbers in the range 1-9.
Each block of 3×3 contains unique numbers in it.
Each block of 3×3 contains unique numbers in it.
A particular row cannot have the same number.
A particular row cannot have the same number.
A particular column cannot have the same number.
A particular column cannot have the same number.
For Example
Input-1 −
sudoku[]=
[["3","5",".",".","2",".",".",".","."]
,["7",".",".","1","6","5",".",".","."]
,[".","9","8",".",".",".",".","6","."]
,["8",".",".",".","6",".",".",".","3"]
,["4",".",".","5",".","4",".",".","1"]
,["7",".",".",".","2",".",".",".","6"]
,[".","6",".",".",".",".","2","8","."]
,[".",".",".","4","1","9",".",".","5"]
,[".",".",".",".","8",".",".","7","9"]]
Output − True.
Explanation − Since all the numbers inside the Sudoku matrix follow the pattern of a valid Sudoku, the output is True.
Initially we will check if the given Sudoku board has the column with unique numbers or not. Then we will check for the row. Each 3*3 block contains all the numbers unique in it. We will check each of the block row and block column if it contains any number duplicate we will return false otherwise return true.
Take input of a 2-D array for the Sudoku board.
Take input of a 2-D array for the Sudoku board.
A Boolean function to check the row whether the elements present in it are unique is not.
A Boolean function to check the row whether the elements present in it are unique is not.
A Boolean function to check the column whether the elements present in it are unique is not.
A Boolean function to check the column whether the elements present in it are unique is not.
A Boolean function to check the block whether the elements present in it are unique is not.
A Boolean function to check the block whether the elements present in it are unique is not.
Live Demo
#include<bits/stdc++.h>
using namespace std;
bool validSudoku(vector<vector<char>>& sudoku) {
int row = 0, col = 0, i = 0, block = 0;
int count[9];
for (row = 0; row < 9; ++row){
memset(count, 0, 9 * sizeof(int));
for (col = 0; col < 9; ++col){
if (sudoku[row][col] != '.')
++count[sudoku[row][col]-'1'];
}
for (i = 0; i < 9; ++i)
if (count[i] > 1)
return false;
}
for (col = 0; col < 9; ++col){
memset(count, 0, 9 * sizeof(int));
for (row = 0; row < 9; ++row){
if (sudoku[row][col] != '.')
++count[sudoku[row][col]-'1'];
}
for (i = 0; i < 9; ++i)
if (count[i] > 1)
return false;
}
int block_row = 0, block_col = 0;
for (block = 0; block < 9; ++block){
block_row = (block / 3) * 3, block_col = (block % 3) * 3;
memset(count, 0, 9 * sizeof(int));
for (row = block_row; row < (block_row + 3); ++row)
for (col = block_col; col < (block_col + 3); ++col)
if (sudoku[row][col] != '.')
++count[sudoku[row][col] - '1'];
for (i = 0; i < 9; ++i)
if (count[i] > 1)
return false;
}
return true;
}
int main(){
vector<vector<char> > sudoku= {
{'5','3','.','.','7','.','.','.','.'},
{'6','.','.','1','9','5','.','.','.'},
{'.','9','8','.','.','.','.','6','.'},
{'8','.','.','.','6','.','.','.','3'},
{'4','.','.','8','.','3','.','.','1'},
{'7','.','.','.','2','.','.','.','6'},
{'.','6','.','.','.','.','2','8','.'},
{'.','.','.','4','1','9','.','.','5'},
{'.','.','.','.','8','.','.','7','9'}
};
bool ans= validSudoku(sudoku);
if(ans){
cout<<"True"<<endl;
} else {
cout<<"false"<<endl;
}
return 0;
}
True | [
{
"code": null,
"e": 1314,
"s": 1187,
"text": "Let’s suppose we’ve given a 9×9 matrix called a Sudoku. The task is to check whether the given Sudoku Pattern is valid or not."
},
{
"code": null,
"e": 1357,
"s": 1314,
"text": "In general, a Sudoku board look like this,"
},
{
"code": null,
"e": 1375,
"s": 1357,
"text": "Rules of Sudoku −"
},
{
"code": null,
"e": 1420,
"s": 1375,
"text": "Every row contains a number in the range 1-9"
},
{
"code": null,
"e": 1465,
"s": 1420,
"text": "Every row contains a number in the range 1-9"
},
{
"code": null,
"e": 1513,
"s": 1465,
"text": "Every column contains numbers in the range 1-9."
},
{
"code": null,
"e": 1561,
"s": 1513,
"text": "Every column contains numbers in the range 1-9."
},
{
"code": null,
"e": 1610,
"s": 1561,
"text": "Each block of 3×3 contains unique numbers in it."
},
{
"code": null,
"e": 1659,
"s": 1610,
"text": "Each block of 3×3 contains unique numbers in it."
},
{
"code": null,
"e": 1705,
"s": 1659,
"text": "A particular row cannot have the same number."
},
{
"code": null,
"e": 1751,
"s": 1705,
"text": "A particular row cannot have the same number."
},
{
"code": null,
"e": 1800,
"s": 1751,
"text": "A particular column cannot have the same number."
},
{
"code": null,
"e": 1849,
"s": 1800,
"text": "A particular column cannot have the same number."
},
{
"code": null,
"e": 1861,
"s": 1849,
"text": "For Example"
},
{
"code": null,
"e": 1871,
"s": 1861,
"text": "Input-1 −"
},
{
"code": null,
"e": 2260,
"s": 1871,
"text": "sudoku[]=\n [[\"3\",\"5\",\".\",\".\",\"2\",\".\",\".\",\".\",\".\"]\n ,[\"7\",\".\",\".\",\"1\",\"6\",\"5\",\".\",\".\",\".\"]\n ,[\".\",\"9\",\"8\",\".\",\".\",\".\",\".\",\"6\",\".\"]\n ,[\"8\",\".\",\".\",\".\",\"6\",\".\",\".\",\".\",\"3\"]\n ,[\"4\",\".\",\".\",\"5\",\".\",\"4\",\".\",\".\",\"1\"]\n ,[\"7\",\".\",\".\",\".\",\"2\",\".\",\".\",\".\",\"6\"]\n ,[\".\",\"6\",\".\",\".\",\".\",\".\",\"2\",\"8\",\".\"]\n ,[\".\",\".\",\".\",\"4\",\"1\",\"9\",\".\",\".\",\"5\"]\n ,[\".\",\".\",\".\",\".\",\"8\",\".\",\".\",\"7\",\"9\"]]"
},
{
"code": null,
"e": 2275,
"s": 2260,
"text": "Output − True."
},
{
"code": null,
"e": 2394,
"s": 2275,
"text": "Explanation − Since all the numbers inside the Sudoku matrix follow the pattern of a valid Sudoku, the output is True."
},
{
"code": null,
"e": 2706,
"s": 2394,
"text": "Initially we will check if the given Sudoku board has the column with unique numbers or not. Then we will check for the row. Each 3*3 block contains all the numbers unique in it. We will check each of the block row and block column if it contains any number duplicate we will return false otherwise return true."
},
{
"code": null,
"e": 2754,
"s": 2706,
"text": "Take input of a 2-D array for the Sudoku board."
},
{
"code": null,
"e": 2802,
"s": 2754,
"text": "Take input of a 2-D array for the Sudoku board."
},
{
"code": null,
"e": 2892,
"s": 2802,
"text": "A Boolean function to check the row whether the elements present in it are unique is not."
},
{
"code": null,
"e": 2982,
"s": 2892,
"text": "A Boolean function to check the row whether the elements present in it are unique is not."
},
{
"code": null,
"e": 3075,
"s": 2982,
"text": "A Boolean function to check the column whether the elements present in it are unique is not."
},
{
"code": null,
"e": 3168,
"s": 3075,
"text": "A Boolean function to check the column whether the elements present in it are unique is not."
},
{
"code": null,
"e": 3260,
"s": 3168,
"text": "A Boolean function to check the block whether the elements present in it are unique is not."
},
{
"code": null,
"e": 3352,
"s": 3260,
"text": "A Boolean function to check the block whether the elements present in it are unique is not."
},
{
"code": null,
"e": 3363,
"s": 3352,
"text": " Live Demo"
},
{
"code": null,
"e": 5170,
"s": 3363,
"text": "#include<bits/stdc++.h>\nusing namespace std;\nbool validSudoku(vector<vector<char>>& sudoku) {\n int row = 0, col = 0, i = 0, block = 0;\n int count[9];\n for (row = 0; row < 9; ++row){\n memset(count, 0, 9 * sizeof(int));\n for (col = 0; col < 9; ++col){\n if (sudoku[row][col] != '.')\n ++count[sudoku[row][col]-'1'];\n }\n for (i = 0; i < 9; ++i)\n if (count[i] > 1)\n return false;\n }\n for (col = 0; col < 9; ++col){\n memset(count, 0, 9 * sizeof(int));\n for (row = 0; row < 9; ++row){\n if (sudoku[row][col] != '.')\n ++count[sudoku[row][col]-'1'];\n }\n for (i = 0; i < 9; ++i)\n if (count[i] > 1)\n return false;\n }\n int block_row = 0, block_col = 0;\n for (block = 0; block < 9; ++block){\n block_row = (block / 3) * 3, block_col = (block % 3) * 3;\n memset(count, 0, 9 * sizeof(int));\n for (row = block_row; row < (block_row + 3); ++row)\n for (col = block_col; col < (block_col + 3); ++col)\n if (sudoku[row][col] != '.')\n ++count[sudoku[row][col] - '1'];\n for (i = 0; i < 9; ++i)\n if (count[i] > 1)\n return false;\n }\n return true;\n}\nint main(){\n vector<vector<char> > sudoku= {\n {'5','3','.','.','7','.','.','.','.'},\n {'6','.','.','1','9','5','.','.','.'},\n {'.','9','8','.','.','.','.','6','.'},\n {'8','.','.','.','6','.','.','.','3'},\n {'4','.','.','8','.','3','.','.','1'},\n {'7','.','.','.','2','.','.','.','6'},\n {'.','6','.','.','.','.','2','8','.'},\n {'.','.','.','4','1','9','.','.','5'},\n {'.','.','.','.','8','.','.','7','9'}\n };\n bool ans= validSudoku(sudoku);\n if(ans){\n cout<<\"True\"<<endl;\n } else {\n cout<<\"false\"<<endl;\n }\n return 0;\n}"
},
{
"code": null,
"e": 5175,
"s": 5170,
"text": "True"
}
] |
Real, Effective and Saved UserID in Linux | 18 Mar, 2021
Every user in Unix like operating system is identified by a different integer number, this unique number is called as UserID.
There are three types of UID defined for a process, which can be dynamically changed as per the privilege of task.
The three different types of UIDs defined are : 1. Real UserID 2. Effective UserID 3. Saved UserID
1. Real UserID : For a process, Real UserId is simply the UserID of the user that has started it. It defines which files that this process has access to.
2. Effective UserID : It is normally the same as Real UserID, but sometimes it is changed to enable a non-privileged user to access files that can only be accessed by a privileged user like root.
If you see the permission of /usr/bin/passwd file:
-rwsr-xr-x 1 root root 59640 Mar 23 2019 /usr/bin/passwd
So if a non-root user runs this file, the EUID of the process will be “0” i.e. root and UID remains the same as of original user.
3. Saved UserID : It is used when a process is running with elevated privileges (generally root) needs to do some under-privileged work, this can be achieved by temporarily switching to a non-privileged account.
While performing under-privileged work, the effective UID is changed to some lower privilege value, and the euid is saved to saved userID(suid), so that it can be used for switching back to a privileged account when the task is completed.
You can print UID by simply typing id on terminal :
# id
Output:
uid=1000(mandeep) gid=1000(mandeep)
groups=1000(mandeep), 4(adm), 24(cdrom),
27(sudo), 30(dip), 46(plugdev), 113(lpadmin),
128(sambashare)
id command can be used to print real and effective user and group IDs
Different options of id:
-g, --group : print only effective group id
-G, --groups : print all group IDs
-r, --real : print only real user id
-u, --user : print only effective user id
For example :
id -g
Output :
1000
Note: While you use id command with -r option, you will get error like
id: cannot print only names or real IDs in default format
To deal with this, use -r option in conjunction with other option, for example, id -rg Now, for setting up real user ID, the effective user ID, and the saved set-user-ID of the calling process, we use setresuid() and setresgid() Syntax :
int setresuid(uid_t ruid, uid_t euid, uid_t suid); # for specific user
int setresgid(gid_t rgid, gid_t egid, gid_t sgid); # for specific group
Return Value : On success, 0 is returned. On error, -1 is returned.
For more details : Use Linux manual page (man user id).
mohit singh 1
linux-command
Linux-Unix
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
scp command in Linux with Examples
Docker - COPY Instruction
chown command in Linux with Examples
SED command in Linux | Set 2
nohup Command in Linux with Examples
chmod command in Linux with examples
Array Basics in Shell Scripting | Set 1
mv command in Linux with examples
Introduction to Linux Operating System
Basic Operators in Shell Scripting | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n18 Mar, 2021"
},
{
"code": null,
"e": 181,
"s": 54,
"text": "Every user in Unix like operating system is identified by a different integer number, this unique number is called as UserID. "
},
{
"code": null,
"e": 297,
"s": 181,
"text": "There are three types of UID defined for a process, which can be dynamically changed as per the privilege of task. "
},
{
"code": null,
"e": 397,
"s": 297,
"text": "The three different types of UIDs defined are : 1. Real UserID 2. Effective UserID 3. Saved UserID "
},
{
"code": null,
"e": 552,
"s": 397,
"text": "1. Real UserID : For a process, Real UserId is simply the UserID of the user that has started it. It defines which files that this process has access to. "
},
{
"code": null,
"e": 748,
"s": 552,
"text": "2. Effective UserID : It is normally the same as Real UserID, but sometimes it is changed to enable a non-privileged user to access files that can only be accessed by a privileged user like root."
},
{
"code": null,
"e": 799,
"s": 748,
"text": "If you see the permission of /usr/bin/passwd file:"
},
{
"code": null,
"e": 858,
"s": 799,
"text": "-rwsr-xr-x 1 root root 59640 Mar 23 2019 /usr/bin/passwd "
},
{
"code": null,
"e": 988,
"s": 858,
"text": "So if a non-root user runs this file, the EUID of the process will be “0” i.e. root and UID remains the same as of original user."
},
{
"code": null,
"e": 1201,
"s": 988,
"text": "3. Saved UserID : It is used when a process is running with elevated privileges (generally root) needs to do some under-privileged work, this can be achieved by temporarily switching to a non-privileged account. "
},
{
"code": null,
"e": 1441,
"s": 1201,
"text": "While performing under-privileged work, the effective UID is changed to some lower privilege value, and the euid is saved to saved userID(suid), so that it can be used for switching back to a privileged account when the task is completed. "
},
{
"code": null,
"e": 1494,
"s": 1441,
"text": "You can print UID by simply typing id on terminal : "
},
{
"code": null,
"e": 1499,
"s": 1494,
"text": "# id"
},
{
"code": null,
"e": 1507,
"s": 1499,
"text": "Output:"
},
{
"code": null,
"e": 1649,
"s": 1507,
"text": "uid=1000(mandeep) gid=1000(mandeep) \ngroups=1000(mandeep), 4(adm), 24(cdrom), \n27(sudo), 30(dip), 46(plugdev), 113(lpadmin), \n128(sambashare)"
},
{
"code": null,
"e": 1720,
"s": 1649,
"text": "id command can be used to print real and effective user and group IDs "
},
{
"code": null,
"e": 1745,
"s": 1720,
"text": "Different options of id:"
},
{
"code": null,
"e": 1903,
"s": 1745,
"text": "-g, --group : print only effective group id\n-G, --groups : print all group IDs\n-r, --real : print only real user id\n-u, --user : print only effective user id"
},
{
"code": null,
"e": 1919,
"s": 1903,
"text": "For example : "
},
{
"code": null,
"e": 1925,
"s": 1919,
"text": "id -g"
},
{
"code": null,
"e": 1936,
"s": 1925,
"text": "Output : "
},
{
"code": null,
"e": 1941,
"s": 1936,
"text": "1000"
},
{
"code": null,
"e": 2013,
"s": 1941,
"text": "Note: While you use id command with -r option, you will get error like "
},
{
"code": null,
"e": 2071,
"s": 2013,
"text": "id: cannot print only names or real IDs in default format"
},
{
"code": null,
"e": 2311,
"s": 2071,
"text": "To deal with this, use -r option in conjunction with other option, for example, id -rg Now, for setting up real user ID, the effective user ID, and the saved set-user-ID of the calling process, we use setresuid() and setresgid() Syntax : "
},
{
"code": null,
"e": 2454,
"s": 2311,
"text": "int setresuid(uid_t ruid, uid_t euid, uid_t suid); # for specific user\nint setresgid(gid_t rgid, gid_t egid, gid_t sgid); # for specific group"
},
{
"code": null,
"e": 2523,
"s": 2454,
"text": "Return Value : On success, 0 is returned. On error, -1 is returned. "
},
{
"code": null,
"e": 2579,
"s": 2523,
"text": "For more details : Use Linux manual page (man user id)."
},
{
"code": null,
"e": 2593,
"s": 2579,
"text": "mohit singh 1"
},
{
"code": null,
"e": 2607,
"s": 2593,
"text": "linux-command"
},
{
"code": null,
"e": 2618,
"s": 2607,
"text": "Linux-Unix"
},
{
"code": null,
"e": 2637,
"s": 2618,
"text": "Technical Scripter"
},
{
"code": null,
"e": 2735,
"s": 2637,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2770,
"s": 2735,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 2796,
"s": 2770,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 2833,
"s": 2796,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 2862,
"s": 2833,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 2899,
"s": 2862,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 2936,
"s": 2899,
"text": "chmod command in Linux with examples"
},
{
"code": null,
"e": 2976,
"s": 2936,
"text": "Array Basics in Shell Scripting | Set 1"
},
{
"code": null,
"e": 3010,
"s": 2976,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 3049,
"s": 3010,
"text": "Introduction to Linux Operating System"
}
] |
Types of Recursions | 04 Jun, 2022
What is Recursion? The process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. Using recursive algorithm, certain problems can be solved quite easily. Examples of such problems are Towers of Hanoi (TOH), Inorder/Preorder/Postorder Tree Traversals, DFS of Graph, etc.
Types of Recursions: Recursion are mainly of two types depending on whether a function calls itself from within itself or more than one function call one another mutually. The first one is called direct recursion and another one is called indirect recursion. Thus, the two types of recursion are:
1. Direct Recursion: These can be further categorized into four types:
Tail Recursion: If a recursive function calling itself and that recursive call is the last statement in the function then it’s known as Tail Recursion. After that call the recursive function performs nothing. The function has to process or perform any operation at the time of calling and it does nothing at returning time.Example:
C++
C
Java
Python3
C#
Javascript
// Code Showing Tail Recursion#include <iostream>using namespace std; // Recursion functionvoid fun(int n){ if (n > 0) { cout << n << " "; // Last statement in the function fun(n - 1); }} // Driver Codeint main(){ int x = 3; fun(x); return 0;} // This code is contributed by shubhamsingh10
// Code Showing Tail Recursion #include <stdio.h> // Recursion functionvoid fun(int n){ if (n > 0) { printf("%d ", n); // Last statement in the function fun(n - 1); }} // Driver Codeint main(){ int x = 3; fun(x); return 0;}
// Java code Showing Tail Recursionclass GFG { // Recursion function static void fun(int n) { if (n > 0) { System.out.print(n + " "); // Last statement in the function fun(n - 1); } } // Driver Code public static void main(String[] args) { int x = 3; fun(x); }} // This code is contributed by pratham76.
# Code Showing Tail Recursion # Recursion functiondef fun(n): if (n > 0): print(n, end=" ") # Last statement in the function fun(n - 1) # Driver Codex = 3fun(x) # This code is contributed by Shubhamsingh10
// C# code Showing Tail Recursionusing System; class GFG{ // Recursion function static void fun(int n) { if (n > 0) { Console.Write(n + " "); // Last statement in the function fun(n - 1); } } // Driver Code public static void Main(string[] args) { int x = 3; fun(x); }} // This code is contributed by rutvik_56
<script>// Javascript code Showing Tail Recursion // Recursion function function fun(n) { if (n > 0) { document.write(n + " "); // Last statement in the function fun(n - 1); } } // Driver Code var x = 3; fun(x); // This code is contributed by shivanisinghss2110</script>
3 2 1
Let’s understand the example by tracing tree of recursive function. That is how the calls are made and how the outputs are produced.
Time Complexity For Tail Recursion : O(n) Space Complexity For Tail Recursion : O(n)Note: Time & Space Complexity is given for this specific example. It may vary for another example.
Lets’s now converting Tail Recursion into Loop and compare each other in terms of Time & Space Complexity and decide which is more efficient.
C++
C
Java
Python3
C#
Javascript
// Converting Tail Recursion into Loop#include <iostream>using namespace std; void fun(int y){ while (y > 0) { cout << y << " "; y--; }} // Driver codeint main(){ int x = 3; fun(x); return 0;} //This Code is contributed by Shubhamsingh10
// Converting Tail Recursion into Loop #include <stdio.h> void fun(int y){ while (y > 0) { printf("%d ", y); y--; }} // Driver codeint main(){ int x = 3; fun(x); return 0;}
// Converting Tail Recursion into Loopimport java.io.*;class GFG{static void fun(int y){ while (y > 0) { System.out.print(" "+ y); y--; }} // Driver codepublic static void main(String[] args){ int x = 3; fun(x); }} // This code is contributed by shivanisinghss2110
# Converting Tail Recursion into Loopdef fun(y): while (y > 0): print(y , end = " ") y -= 1 # Driver codex = 3fun(x) # This Code is contributed by shivanisinghss2110
// Converting Tail Recursion into Loopusing System;class GFG{static void fun(int y){ while (y > 0) { Console.Write(" "+ y); y--; }} // Driver codepublic static void Main(String[] args){ int x = 3; fun(x); }}// This code is contributed by shivanisinghss2110
<script>function fun(y){ while (y > 0) { document.write(" "+ y); y--; }} // Driver code var x = 3; fun(x); // This code is contributed by shivanisinghss2110</script>
3 2 1
Time Complexity: O(n) Space Complexity: O(1)
Note: Time & Space Complexity is given for this specific example. It may vary for another example.So it was seen that in case of loop the Space Complexity is O(1) so it was better to write code in loop instead of tail recursion in terms of Space Complexity which is more efficient than tail recursion.
Why space complexity is less in case of loop ?Before explaining this I am assuming that you are familiar with the knowledge that’s how the data stored in main memory during execution of a program. In brief,when the program executes,the main memory divided into three parts. One part for code section, the second one is heap memory and another one is stack memory. Remember that the program can directly access only the stack memory, it can’t directly access the heap memory so we need the help of pointer to access the heap memory.
Let’s now understand why space complexity is less in case of loop ?In case of loop when function “(void fun(int y))” executes there only one activation record created in stack memory(activation record created for only ‘y’ variable) so it takes only ‘one’ unit of memory inside stack so it’s space complexity is O(1) but in case of recursive function every time it calls itself for each call a separate activation record created in stack.So if there’s ‘n’ no of call then it takes ‘n’ unit of memory inside stack so it’s space complexity is O(n).
Head Recursion: If a recursive function calling itself and that recursive call is the first statement in the function then it’s known as Head Recursion. There’s no statement, no operation before the call. The function doesn’t have to process or perform any operation at the time of calling and all operations are done at returning time.Example:
C++
C
Java
Python3
C#
Javascript
// C++ program showing Head Recursion #include <bits/stdc++.h>using namespace std; // Recursive functionvoid fun(int n){ if (n > 0) { // First statement in the function fun(n - 1); cout << " "<< n; }} // Driver codeint main(){ int x = 3; fun(x); return 0;} // this code is contributed by shivanisinghss2110
// C program showing Head Recursion #include <stdio.h> // Recursive functionvoid fun(int n){ if (n > 0) { // First statement in the function fun(n - 1); printf("%d ", n); }} // Driver codeint main(){ int x = 3; fun(x); return 0;}
// Java program showing Head Recursionimport java.io.*; class GFG{ // Recursive functionstatic void fun(int n){ if (n > 0) { // First statement in the function fun(n - 1); System.out.print(" "+ n); }} // Driver codepublic static void main(String[] args){ int x = 3; fun(x); }} // This code is contributed by shivanisinghss2110
# Python program showing Head Recursion# Recursive functiondef fun(n): if (n > 0): # First statement in the function fun(n - 1) print(n,end=" ") # Driver codex = 3fun(x) # this code is contributed by shivanisinghss2110
// Java program showing Head Recursionusing System; class GFG{ // Recursive functionstatic void fun(int n){ if (n > 0) { // First statement in the function fun(n - 1); Console.Write(" "+ n); }} // Driver codepublic static void Main(String[] args){ int x = 3; fun(x); }} // This code is contributed by shivanisinghss2110
<script> // JavaScript program showing Head Recursion// Recursive functionfunction fun(n){ if (n > 0) { // First statement in the function fun(n - 1); document.write(" "+ n); }} // Driver code var x = 3; fun(x); // This code is contributed by shivanisinghss2110 </script>
1 2 3
Let’s understand the example by tracing tree of recursive function. That is how the calls are made and how the outputs are produced.
Time Complexity For Head Recursion: O(n) Space Complexity For Head Recursion: O(n)
Note: Time & Space Complexity is given for this specific example. It may vary for another example.Note: Head recursion can’t easily convert into loop as Tail Recursion but it can. Let’s convert the above code into the loop.
C++
C
Java
Python3
C#
Javascript
// Converting Head Recursion into Loop#include <iostream>using namespace std; // Recursive functionvoid fun(int n){ int i = 1; while (i <= n) { cout <<" "<< i; i++; }} // Driver codeint main(){ int x = 3; fun(x); return 0;}// this code is contributed by shivanisinghss2110
// Converting Head Recursion into Loop #include <stdio.h> // Recursive functionvoid fun(int n){ int i = 1; while (i <= n) { printf("%d ", i); i++; }} // Driver codeint main(){ int x = 3; fun(x); return 0;}
// Converting Head Recursion into Loopimport java.util.*;class GFG{// Recursive functionstatic void fun(int n){ int i = 1; while (i <= n) { System.out.print(" "+ i); i++; }} // Driver codepublic static void main(String[] args){ int x = 3; fun(x);}} // this code is contributed by shivanisinghss2110
# Converting Head Recursion into Loop# Recursive functiondef fun(n): i = 1 while (i <= n): print(i,end=" ") i+=1 # Driver codex = 3fun(x) # This code is contributed by shivanisinghss2110
// Converting Head Recursion into Loopusing System;class GFG{// Recursive functionstatic void fun(int n){ int i = 1; while (i <= n) { Console.Write(" "+ i); i++; }} // Driver codepublic static void Main(String[] args){ int x = 3; fun(x);}} // this code is contributed by shivanisinghss2110
<script> // Converting Head Recursion into Loop// Recursive functionfunction fun(n){ var i = 1; while (i <= n) { document.write(" "+ i); i++; }} // Driver codevar x = 3;fun(x); // this code is contributed by shivanisinghss2110 </script>
1 2 3
Tree Recursion: To understand Tree Recursion let’s first understand Linear Recursion. If a recursive function calling itself for one time then it’s known as Linear Recursion. Otherwise if a recursive function calling itself for more than one time then it’s known as Tree Recursion.Example:Pseudo Code for linear recursion
fun(n)
{
// some code
if(n>0)
{
fun(n-1); // Calling itself only once
}
// some code
}
Program for tree recursion
C++
C
Java
Python3
C#
Javascript
// C++ program to show Tree Recursion#include <iostream>using namespace std; // Recursive functionvoid fun(int n){ if (n > 0) { cout << " " << n; // Calling once fun(n - 1); // Calling twice fun(n - 1); }} // Driver codeint main(){ fun(3); return 0;} // This code is contributed by shivanisinghss2110
// C program to show Tree Recursion #include <stdio.h> // Recursive functionvoid fun(int n){ if (n > 0) { printf("%d ", n); // Calling once fun(n - 1); // Calling twice fun(n - 1); }} // Driver codeint main(){ fun(3); return 0;}
// Java program to show Tree Recursionclass GFG{ // Recursive functionstatic void fun(int n){ if (n > 0) { System.out.print(" "+ n); // Calling once fun(n - 1); // Calling twice fun(n - 1); }} // Driver codepublic static void main(String[] args) { fun(3); }} // This code is contributed by shivanisinghss2110
# C++ program to show Tree Recursion# Recursive functiondef fun(n): if (n > 0): print(n, end=" ") # Calling once fun(n - 1) # Calling twice fun(n - 1) # Driver codefun(3) # This code is contributed by shivanisinghss2110
// C# program to show Tree Recursionusing System;class GFG{ // Recursive functionstatic void fun(int n){ if (n > 0) { Console.Write(" "+ n); // Calling once fun(n - 1); // Calling twice fun(n - 1); }} // Driver codepublic static void Main(String[] args) { fun(3); }} // This code is contributed by shivanisinghss2110
<script> // JavaScript program to show Tree Recursion // Recursive functionfunction fun(n){ if (n > 0) { document.write(" "+ n); // Calling once fun(n - 1); // Calling twice fun(n - 1); }} // Driver code fun(3); // This code is contributed by shivanisinghss2110 </script>
3 2 1 1 2 1 1
Let’s understand the example by tracing tree of recursive function. That is how the calls are made and how the outputs are produced.
Time Complexity For Tree Recursion: O(2^n) Space Complexity For Tree Recursion: O(n)Note: Time & Space Complexity is given for this specific example. It may vary for another example.
Nested Recursion: In this recursion, a recursive function will pass the parameter as a recursive call. That means “recursion inside recursion”. Let see the example to understand this recursion.Example:
C++
C
Java
Python3
C#
Javascript
// C++ program to show Nested Recursion#include <iostream>using namespace std; int fun(int n){ if (n > 100) return n - 10; // A recursive function passing parameter // as a recursive call or recursion inside // the recursion return fun(fun(n + 11));} // Driver codeint main(){ int r; r = fun(95); cout << " " << r; return 0;} // This code is contributed by shivanisinghss2110
// C program to show Nested Recursion #include <stdio.h>int fun(int n){ if (n > 100) return n - 10; // A recursive function passing parameter // as a recursive call or recursion // inside the recursion return fun(fun(n + 11));} // Driver codeint main(){ int r; r = fun(95); printf("%d\n", r); return 0;}
// Java program to show Nested Recursionimport java.util.*; class GFG {static int fun(int n){ if (n > 100) return n - 10; // A recursive function passing parameter // as a recursive call or recursion // inside the recursion return fun(fun(n + 11));} // Driver codepublic static void main(String args[]){ int r; r = fun(95); System.out.print(" "+ r); }}// This code is contributed by shivanisinghss2110
# Python program to show Nested Recursiondef fun(n): if (n > 100): return n - 10 # A recursive function passing parameter # as a recursive call or recursion inside # the recursion return fun(fun(n + 11)) # Driver coder = fun(95)print("", r) # This code is contributed by shivanisinghss2110
// C# program to show Nested Recursionusing System; class GFG {static int fun(int n){ if (n > 100) return n - 10; // A recursive function passing parameter // as a recursive call or recursion // inside the recursion return fun(fun(n + 11));} // Driver codepublic static void Main(String []args){ int r; r = fun(95); Console.Write(" "+ r); }}// This code is contributed by shivanisinghss2110
<script> // JavaScript program to show Nested Recursionfunction fun( n){ if (n > 100) return n - 10; // A recursive function passing parameter // as a recursive call or recursion // inside the recursion return fun(fun(n + 11));} // Driver code var r; r = fun(95); document.write(" "+ r); // This code is contributed by shivanisinghss2110</script>
91
Let’s understand the example by tracing tree of recursive function. That is how the calls are made and how the outputs are produced.
2. Indirect Recursion: In this recursion, there may be more than one functions and they are calling one another in a circular manner.
From the above diagram fun(A) is calling for fun(B), fun(B) is calling for fun(C) and fun(C) is calling for fun(A) and thus it makes a cycle.
Example:
C++
C
Java
C#
Python3
Javascript
// C++ program to show Indirect Recursion#include <iostream>using namespace std; void funB(int n); void funA(int n){ if (n > 0) { cout <<" "<< n; // fun(A) is calling fun(B) funB(n - 1); }} void funB(int n){ if (n > 1) { cout <<" "<< n; // fun(B) is calling fun(A) funA(n / 2); }} // Driver codeint main(){ funA(20); return 0;} // this code is contributed by shivanisinghss2110
// C program to show Indirect Recursion #include <stdio.h> void funB(int n); void funA(int n){ if (n > 0) { printf("%d ", n); // Fun(A) is calling fun(B) funB(n - 1); }} void funB(int n){ if (n > 1) { printf("%d ", n); // Fun(B) is calling fun(A) funA(n / 2); }} // Driver codeint main(){ funA(20); return 0;}
// Java program to show Indirect Recursionimport java.io.*; class GFG{ static void funA(int n){ if (n > 0) { System.out.print(" " +n); // Fun(A) is calling fun(B) funB(n - 1); }} static void funB(int n){ if (n > 1) { System.out.print(" " +n); // Fun(B) is calling fun(A) funA(n / 2); }} // Driver codepublic static void main (String[] args){ funA(20);}} // This code is contributed by shivanisinghss2110
// C# program to show Indirect Recursionusing System; class GFG{ static void funA(int n){ if (n > 0) { Console.Write(" " +n); // Fun(A) is calling fun(B) funB(n - 1); }} static void funB(int n){ if (n > 1) { Console.Write(" " +n); // Fun(B) is calling fun(A) funA(n / 2); }} // Driver codepublic static void Main (String[] args){ funA(20);}} // This code is contributed by shivanisinghss2110
# Python program to show Indirect Recursiondef funA(n): if (n > 0): print("", n, end='') # Fun(A) is calling fun(B) funB(n - 1) def funB( n): if (n > 1): print("", n, end='') # Fun(B) is calling fun(A) funA(n // 2) # Driver codefunA(20) # This code is contributed by shivanisinghss2110
<script> // JavaScript program to show Indirect Recursionfunction funA(n){ if (n > 0) { document.write(n.toFixed(0) + "</br>"); // Fun(A) is calling fun(B) funB(n - 1); }} function funB(n){ if (n > 1) { document.write(n.toFixed(0) + "</br>"); // Fun(B) is calling fun(A) funA(n / 2); }} // Driver codefunA(20); // this code is contributed by shivanisinghss2110</script>
20 19 9 8 4 3 1
Let’s understand the example by tracing tree of recursive function. That is how the calls are made and how the outputs are produced.
This article is contributed by AmiyaRanjanRout. 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] your article appearing on the GeeksforGeeks main page and help other Geeks.
AmiyaRanjanRout
pratham76
rutvik_56
darshkaushik
shivanisinghss2110
SHUBHAMSINGH10
abhishekaslk
Recursion
Recursion
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sum of the series (1*2) + (2*3) + (3*4) + ...... upto n terms
Generate all the binary strings of N bits
Traverse a given Matrix using Recursion
Generating subarrays using recursion
Practice Questions for Recursion | Set 1
Recursively Reversing a linked list (A simple implementation)
Generating all possible Subsequences using Recursion including the empty one.
Tutorial on Binary Tree
Memoization (1D, 2D and 3D)
Count number of nodes in a complete Binary Tree | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n04 Jun, 2022"
},
{
"code": null,
"e": 412,
"s": 54,
"text": "What is Recursion? The process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. Using recursive algorithm, certain problems can be solved quite easily. Examples of such problems are Towers of Hanoi (TOH), Inorder/Preorder/Postorder Tree Traversals, DFS of Graph, etc."
},
{
"code": null,
"e": 709,
"s": 412,
"text": "Types of Recursions: Recursion are mainly of two types depending on whether a function calls itself from within itself or more than one function call one another mutually. The first one is called direct recursion and another one is called indirect recursion. Thus, the two types of recursion are:"
},
{
"code": null,
"e": 780,
"s": 709,
"text": "1. Direct Recursion: These can be further categorized into four types:"
},
{
"code": null,
"e": 1112,
"s": 780,
"text": "Tail Recursion: If a recursive function calling itself and that recursive call is the last statement in the function then it’s known as Tail Recursion. After that call the recursive function performs nothing. The function has to process or perform any operation at the time of calling and it does nothing at returning time.Example:"
},
{
"code": null,
"e": 1116,
"s": 1112,
"text": "C++"
},
{
"code": null,
"e": 1118,
"s": 1116,
"text": "C"
},
{
"code": null,
"e": 1123,
"s": 1118,
"text": "Java"
},
{
"code": null,
"e": 1131,
"s": 1123,
"text": "Python3"
},
{
"code": null,
"e": 1134,
"s": 1131,
"text": "C#"
},
{
"code": null,
"e": 1145,
"s": 1134,
"text": "Javascript"
},
{
"code": "// Code Showing Tail Recursion#include <iostream>using namespace std; // Recursion functionvoid fun(int n){ if (n > 0) { cout << n << \" \"; // Last statement in the function fun(n - 1); }} // Driver Codeint main(){ int x = 3; fun(x); return 0;} // This code is contributed by shubhamsingh10",
"e": 1472,
"s": 1145,
"text": null
},
{
"code": "// Code Showing Tail Recursion #include <stdio.h> // Recursion functionvoid fun(int n){ if (n > 0) { printf(\"%d \", n); // Last statement in the function fun(n - 1); }} // Driver Codeint main(){ int x = 3; fun(x); return 0;}",
"e": 1733,
"s": 1472,
"text": null
},
{
"code": "// Java code Showing Tail Recursionclass GFG { // Recursion function static void fun(int n) { if (n > 0) { System.out.print(n + \" \"); // Last statement in the function fun(n - 1); } } // Driver Code public static void main(String[] args) { int x = 3; fun(x); }} // This code is contributed by pratham76.",
"e": 2078,
"s": 1733,
"text": null
},
{
"code": "# Code Showing Tail Recursion # Recursion functiondef fun(n): if (n > 0): print(n, end=\" \") # Last statement in the function fun(n - 1) # Driver Codex = 3fun(x) # This code is contributed by Shubhamsingh10",
"e": 2308,
"s": 2078,
"text": null
},
{
"code": "// C# code Showing Tail Recursionusing System; class GFG{ // Recursion function static void fun(int n) { if (n > 0) { Console.Write(n + \" \"); // Last statement in the function fun(n - 1); } } // Driver Code public static void Main(string[] args) { int x = 3; fun(x); }} // This code is contributed by rutvik_56",
"e": 2660,
"s": 2308,
"text": null
},
{
"code": "<script>// Javascript code Showing Tail Recursion // Recursion function function fun(n) { if (n > 0) { document.write(n + \" \"); // Last statement in the function fun(n - 1); } } // Driver Code var x = 3; fun(x); // This code is contributed by shivanisinghss2110</script>",
"e": 2974,
"s": 2660,
"text": null
},
{
"code": null,
"e": 2981,
"s": 2974,
"text": "3 2 1 "
},
{
"code": null,
"e": 3114,
"s": 2981,
"text": "Let’s understand the example by tracing tree of recursive function. That is how the calls are made and how the outputs are produced."
},
{
"code": null,
"e": 3297,
"s": 3114,
"text": "Time Complexity For Tail Recursion : O(n) Space Complexity For Tail Recursion : O(n)Note: Time & Space Complexity is given for this specific example. It may vary for another example."
},
{
"code": null,
"e": 3439,
"s": 3297,
"text": "Lets’s now converting Tail Recursion into Loop and compare each other in terms of Time & Space Complexity and decide which is more efficient."
},
{
"code": null,
"e": 3443,
"s": 3439,
"text": "C++"
},
{
"code": null,
"e": 3445,
"s": 3443,
"text": "C"
},
{
"code": null,
"e": 3450,
"s": 3445,
"text": "Java"
},
{
"code": null,
"e": 3458,
"s": 3450,
"text": "Python3"
},
{
"code": null,
"e": 3461,
"s": 3458,
"text": "C#"
},
{
"code": null,
"e": 3472,
"s": 3461,
"text": "Javascript"
},
{
"code": "// Converting Tail Recursion into Loop#include <iostream>using namespace std; void fun(int y){ while (y > 0) { cout << y << \" \"; y--; }} // Driver codeint main(){ int x = 3; fun(x); return 0;} //This Code is contributed by Shubhamsingh10",
"e": 3739,
"s": 3472,
"text": null
},
{
"code": "// Converting Tail Recursion into Loop #include <stdio.h> void fun(int y){ while (y > 0) { printf(\"%d \", y); y--; }} // Driver codeint main(){ int x = 3; fun(x); return 0;}",
"e": 3941,
"s": 3739,
"text": null
},
{
"code": "// Converting Tail Recursion into Loopimport java.io.*;class GFG{static void fun(int y){ while (y > 0) { System.out.print(\" \"+ y); y--; }} // Driver codepublic static void main(String[] args){ int x = 3; fun(x); }} // This code is contributed by shivanisinghss2110",
"e": 4236,
"s": 3941,
"text": null
},
{
"code": "# Converting Tail Recursion into Loopdef fun(y): while (y > 0): print(y , end = \" \") y -= 1 # Driver codex = 3fun(x) # This Code is contributed by shivanisinghss2110",
"e": 4424,
"s": 4236,
"text": null
},
{
"code": "// Converting Tail Recursion into Loopusing System;class GFG{static void fun(int y){ while (y > 0) { Console.Write(\" \"+ y); y--; }} // Driver codepublic static void Main(String[] args){ int x = 3; fun(x); }}// This code is contributed by shivanisinghss2110",
"e": 4711,
"s": 4424,
"text": null
},
{
"code": "<script>function fun(y){ while (y > 0) { document.write(\" \"+ y); y--; }} // Driver code var x = 3; fun(x); // This code is contributed by shivanisinghss2110</script>",
"e": 4901,
"s": 4711,
"text": null
},
{
"code": null,
"e": 4908,
"s": 4901,
"text": "3 2 1 "
},
{
"code": null,
"e": 4953,
"s": 4908,
"text": "Time Complexity: O(n) Space Complexity: O(1)"
},
{
"code": null,
"e": 5255,
"s": 4953,
"text": "Note: Time & Space Complexity is given for this specific example. It may vary for another example.So it was seen that in case of loop the Space Complexity is O(1) so it was better to write code in loop instead of tail recursion in terms of Space Complexity which is more efficient than tail recursion."
},
{
"code": null,
"e": 5787,
"s": 5255,
"text": "Why space complexity is less in case of loop ?Before explaining this I am assuming that you are familiar with the knowledge that’s how the data stored in main memory during execution of a program. In brief,when the program executes,the main memory divided into three parts. One part for code section, the second one is heap memory and another one is stack memory. Remember that the program can directly access only the stack memory, it can’t directly access the heap memory so we need the help of pointer to access the heap memory."
},
{
"code": null,
"e": 6334,
"s": 5787,
"text": "Let’s now understand why space complexity is less in case of loop ?In case of loop when function “(void fun(int y))” executes there only one activation record created in stack memory(activation record created for only ‘y’ variable) so it takes only ‘one’ unit of memory inside stack so it’s space complexity is O(1) but in case of recursive function every time it calls itself for each call a separate activation record created in stack.So if there’s ‘n’ no of call then it takes ‘n’ unit of memory inside stack so it’s space complexity is O(n). "
},
{
"code": null,
"e": 6679,
"s": 6334,
"text": "Head Recursion: If a recursive function calling itself and that recursive call is the first statement in the function then it’s known as Head Recursion. There’s no statement, no operation before the call. The function doesn’t have to process or perform any operation at the time of calling and all operations are done at returning time.Example:"
},
{
"code": null,
"e": 6683,
"s": 6679,
"text": "C++"
},
{
"code": null,
"e": 6685,
"s": 6683,
"text": "C"
},
{
"code": null,
"e": 6690,
"s": 6685,
"text": "Java"
},
{
"code": null,
"e": 6698,
"s": 6690,
"text": "Python3"
},
{
"code": null,
"e": 6701,
"s": 6698,
"text": "C#"
},
{
"code": null,
"e": 6712,
"s": 6701,
"text": "Javascript"
},
{
"code": "// C++ program showing Head Recursion #include <bits/stdc++.h>using namespace std; // Recursive functionvoid fun(int n){ if (n > 0) { // First statement in the function fun(n - 1); cout << \" \"<< n; }} // Driver codeint main(){ int x = 3; fun(x); return 0;} // this code is contributed by shivanisinghss2110",
"e": 7057,
"s": 6712,
"text": null
},
{
"code": "// C program showing Head Recursion #include <stdio.h> // Recursive functionvoid fun(int n){ if (n > 0) { // First statement in the function fun(n - 1); printf(\"%d \", n); }} // Driver codeint main(){ int x = 3; fun(x); return 0;}",
"e": 7325,
"s": 7057,
"text": null
},
{
"code": "// Java program showing Head Recursionimport java.io.*; class GFG{ // Recursive functionstatic void fun(int n){ if (n > 0) { // First statement in the function fun(n - 1); System.out.print(\" \"+ n); }} // Driver codepublic static void main(String[] args){ int x = 3; fun(x); }} // This code is contributed by shivanisinghss2110",
"e": 7696,
"s": 7325,
"text": null
},
{
"code": "# Python program showing Head Recursion# Recursive functiondef fun(n): if (n > 0): # First statement in the function fun(n - 1) print(n,end=\" \") # Driver codex = 3fun(x) # this code is contributed by shivanisinghss2110",
"e": 7949,
"s": 7696,
"text": null
},
{
"code": "// Java program showing Head Recursionusing System; class GFG{ // Recursive functionstatic void fun(int n){ if (n > 0) { // First statement in the function fun(n - 1); Console.Write(\" \"+ n); }} // Driver codepublic static void Main(String[] args){ int x = 3; fun(x); }} // This code is contributed by shivanisinghss2110",
"e": 8313,
"s": 7949,
"text": null
},
{
"code": "<script> // JavaScript program showing Head Recursion// Recursive functionfunction fun(n){ if (n > 0) { // First statement in the function fun(n - 1); document.write(\" \"+ n); }} // Driver code var x = 3; fun(x); // This code is contributed by shivanisinghss2110 </script>",
"e": 8620,
"s": 8313,
"text": null
},
{
"code": null,
"e": 8627,
"s": 8620,
"text": " 1 2 3"
},
{
"code": null,
"e": 8760,
"s": 8627,
"text": "Let’s understand the example by tracing tree of recursive function. That is how the calls are made and how the outputs are produced."
},
{
"code": null,
"e": 8843,
"s": 8760,
"text": "Time Complexity For Head Recursion: O(n) Space Complexity For Head Recursion: O(n)"
},
{
"code": null,
"e": 9067,
"s": 8843,
"text": "Note: Time & Space Complexity is given for this specific example. It may vary for another example.Note: Head recursion can’t easily convert into loop as Tail Recursion but it can. Let’s convert the above code into the loop."
},
{
"code": null,
"e": 9071,
"s": 9067,
"text": "C++"
},
{
"code": null,
"e": 9073,
"s": 9071,
"text": "C"
},
{
"code": null,
"e": 9078,
"s": 9073,
"text": "Java"
},
{
"code": null,
"e": 9086,
"s": 9078,
"text": "Python3"
},
{
"code": null,
"e": 9089,
"s": 9086,
"text": "C#"
},
{
"code": null,
"e": 9100,
"s": 9089,
"text": "Javascript"
},
{
"code": "// Converting Head Recursion into Loop#include <iostream>using namespace std; // Recursive functionvoid fun(int n){ int i = 1; while (i <= n) { cout <<\" \"<< i; i++; }} // Driver codeint main(){ int x = 3; fun(x); return 0;}// this code is contributed by shivanisinghss2110",
"e": 9405,
"s": 9100,
"text": null
},
{
"code": "// Converting Head Recursion into Loop #include <stdio.h> // Recursive functionvoid fun(int n){ int i = 1; while (i <= n) { printf(\"%d \", i); i++; }} // Driver codeint main(){ int x = 3; fun(x); return 0;}",
"e": 9643,
"s": 9405,
"text": null
},
{
"code": "// Converting Head Recursion into Loopimport java.util.*;class GFG{// Recursive functionstatic void fun(int n){ int i = 1; while (i <= n) { System.out.print(\" \"+ i); i++; }} // Driver codepublic static void main(String[] args){ int x = 3; fun(x);}} // this code is contributed by shivanisinghss2110",
"e": 9971,
"s": 9643,
"text": null
},
{
"code": "# Converting Head Recursion into Loop# Recursive functiondef fun(n): i = 1 while (i <= n): print(i,end=\" \") i+=1 # Driver codex = 3fun(x) # This code is contributed by shivanisinghss2110",
"e": 10183,
"s": 9971,
"text": null
},
{
"code": "// Converting Head Recursion into Loopusing System;class GFG{// Recursive functionstatic void fun(int n){ int i = 1; while (i <= n) { Console.Write(\" \"+ i); i++; }} // Driver codepublic static void Main(String[] args){ int x = 3; fun(x);}} // this code is contributed by shivanisinghss2110",
"e": 10502,
"s": 10183,
"text": null
},
{
"code": "<script> // Converting Head Recursion into Loop// Recursive functionfunction fun(n){ var i = 1; while (i <= n) { document.write(\" \"+ i); i++; }} // Driver codevar x = 3;fun(x); // this code is contributed by shivanisinghss2110 </script>",
"e": 10762,
"s": 10502,
"text": null
},
{
"code": null,
"e": 10769,
"s": 10762,
"text": " 1 2 3"
},
{
"code": null,
"e": 11091,
"s": 10769,
"text": "Tree Recursion: To understand Tree Recursion let’s first understand Linear Recursion. If a recursive function calling itself for one time then it’s known as Linear Recursion. Otherwise if a recursive function calling itself for more than one time then it’s known as Tree Recursion.Example:Pseudo Code for linear recursion"
},
{
"code": null,
"e": 11206,
"s": 11091,
"text": "fun(n)\n{\n // some code\n if(n>0)\n {\n fun(n-1); // Calling itself only once\n }\n // some code\n}"
},
{
"code": null,
"e": 11233,
"s": 11206,
"text": "Program for tree recursion"
},
{
"code": null,
"e": 11237,
"s": 11233,
"text": "C++"
},
{
"code": null,
"e": 11239,
"s": 11237,
"text": "C"
},
{
"code": null,
"e": 11244,
"s": 11239,
"text": "Java"
},
{
"code": null,
"e": 11252,
"s": 11244,
"text": "Python3"
},
{
"code": null,
"e": 11255,
"s": 11252,
"text": "C#"
},
{
"code": null,
"e": 11266,
"s": 11255,
"text": "Javascript"
},
{
"code": "// C++ program to show Tree Recursion#include <iostream>using namespace std; // Recursive functionvoid fun(int n){ if (n > 0) { cout << \" \" << n; // Calling once fun(n - 1); // Calling twice fun(n - 1); }} // Driver codeint main(){ fun(3); return 0;} // This code is contributed by shivanisinghss2110",
"e": 11635,
"s": 11266,
"text": null
},
{
"code": "// C program to show Tree Recursion #include <stdio.h> // Recursive functionvoid fun(int n){ if (n > 0) { printf(\"%d \", n); // Calling once fun(n - 1); // Calling twice fun(n - 1); }} // Driver codeint main(){ fun(3); return 0;}",
"e": 11913,
"s": 11635,
"text": null
},
{
"code": "// Java program to show Tree Recursionclass GFG{ // Recursive functionstatic void fun(int n){ if (n > 0) { System.out.print(\" \"+ n); // Calling once fun(n - 1); // Calling twice fun(n - 1); }} // Driver codepublic static void main(String[] args) { fun(3); }} // This code is contributed by shivanisinghss2110",
"e": 12281,
"s": 11913,
"text": null
},
{
"code": "# C++ program to show Tree Recursion# Recursive functiondef fun(n): if (n > 0): print(n, end=\" \") # Calling once fun(n - 1) # Calling twice fun(n - 1) # Driver codefun(3) # This code is contributed by shivanisinghss2110",
"e": 12569,
"s": 12281,
"text": null
},
{
"code": "// C# program to show Tree Recursionusing System;class GFG{ // Recursive functionstatic void fun(int n){ if (n > 0) { Console.Write(\" \"+ n); // Calling once fun(n - 1); // Calling twice fun(n - 1); }} // Driver codepublic static void Main(String[] args) { fun(3); }} // This code is contributed by shivanisinghss2110",
"e": 12945,
"s": 12569,
"text": null
},
{
"code": "<script> // JavaScript program to show Tree Recursion // Recursive functionfunction fun(n){ if (n > 0) { document.write(\" \"+ n); // Calling once fun(n - 1); // Calling twice fun(n - 1); }} // Driver code fun(3); // This code is contributed by shivanisinghss2110 </script>",
"e": 13263,
"s": 12945,
"text": null
},
{
"code": null,
"e": 13278,
"s": 13263,
"text": " 3 2 1 1 2 1 1"
},
{
"code": null,
"e": 13411,
"s": 13278,
"text": "Let’s understand the example by tracing tree of recursive function. That is how the calls are made and how the outputs are produced."
},
{
"code": null,
"e": 13594,
"s": 13411,
"text": "Time Complexity For Tree Recursion: O(2^n) Space Complexity For Tree Recursion: O(n)Note: Time & Space Complexity is given for this specific example. It may vary for another example."
},
{
"code": null,
"e": 13796,
"s": 13594,
"text": "Nested Recursion: In this recursion, a recursive function will pass the parameter as a recursive call. That means “recursion inside recursion”. Let see the example to understand this recursion.Example:"
},
{
"code": null,
"e": 13800,
"s": 13796,
"text": "C++"
},
{
"code": null,
"e": 13802,
"s": 13800,
"text": "C"
},
{
"code": null,
"e": 13807,
"s": 13802,
"text": "Java"
},
{
"code": null,
"e": 13815,
"s": 13807,
"text": "Python3"
},
{
"code": null,
"e": 13818,
"s": 13815,
"text": "C#"
},
{
"code": null,
"e": 13829,
"s": 13818,
"text": "Javascript"
},
{
"code": "// C++ program to show Nested Recursion#include <iostream>using namespace std; int fun(int n){ if (n > 100) return n - 10; // A recursive function passing parameter // as a recursive call or recursion inside // the recursion return fun(fun(n + 11));} // Driver codeint main(){ int r; r = fun(95); cout << \" \" << r; return 0;} // This code is contributed by shivanisinghss2110",
"e": 14246,
"s": 13829,
"text": null
},
{
"code": "// C program to show Nested Recursion #include <stdio.h>int fun(int n){ if (n > 100) return n - 10; // A recursive function passing parameter // as a recursive call or recursion // inside the recursion return fun(fun(n + 11));} // Driver codeint main(){ int r; r = fun(95); printf(\"%d\\n\", r); return 0;}",
"e": 14585,
"s": 14246,
"text": null
},
{
"code": "// Java program to show Nested Recursionimport java.util.*; class GFG {static int fun(int n){ if (n > 100) return n - 10; // A recursive function passing parameter // as a recursive call or recursion // inside the recursion return fun(fun(n + 11));} // Driver codepublic static void main(String args[]){ int r; r = fun(95); System.out.print(\" \"+ r); }}// This code is contributed by shivanisinghss2110",
"e": 15024,
"s": 14585,
"text": null
},
{
"code": "# Python program to show Nested Recursiondef fun(n): if (n > 100): return n - 10 # A recursive function passing parameter # as a recursive call or recursion inside # the recursion return fun(fun(n + 11)) # Driver coder = fun(95)print(\"\", r) # This code is contributed by shivanisinghss2110",
"e": 15338,
"s": 15024,
"text": null
},
{
"code": "// C# program to show Nested Recursionusing System; class GFG {static int fun(int n){ if (n > 100) return n - 10; // A recursive function passing parameter // as a recursive call or recursion // inside the recursion return fun(fun(n + 11));} // Driver codepublic static void Main(String []args){ int r; r = fun(95); Console.Write(\" \"+ r); }}// This code is contributed by shivanisinghss2110",
"e": 15766,
"s": 15338,
"text": null
},
{
"code": "<script> // JavaScript program to show Nested Recursionfunction fun( n){ if (n > 100) return n - 10; // A recursive function passing parameter // as a recursive call or recursion // inside the recursion return fun(fun(n + 11));} // Driver code var r; r = fun(95); document.write(\" \"+ r); // This code is contributed by shivanisinghss2110</script>",
"e": 16150,
"s": 15766,
"text": null
},
{
"code": null,
"e": 16154,
"s": 16150,
"text": " 91"
},
{
"code": null,
"e": 16287,
"s": 16154,
"text": "Let’s understand the example by tracing tree of recursive function. That is how the calls are made and how the outputs are produced."
},
{
"code": null,
"e": 16421,
"s": 16287,
"text": "2. Indirect Recursion: In this recursion, there may be more than one functions and they are calling one another in a circular manner."
},
{
"code": null,
"e": 16563,
"s": 16421,
"text": "From the above diagram fun(A) is calling for fun(B), fun(B) is calling for fun(C) and fun(C) is calling for fun(A) and thus it makes a cycle."
},
{
"code": null,
"e": 16572,
"s": 16563,
"text": "Example:"
},
{
"code": null,
"e": 16576,
"s": 16572,
"text": "C++"
},
{
"code": null,
"e": 16578,
"s": 16576,
"text": "C"
},
{
"code": null,
"e": 16583,
"s": 16578,
"text": "Java"
},
{
"code": null,
"e": 16586,
"s": 16583,
"text": "C#"
},
{
"code": null,
"e": 16594,
"s": 16586,
"text": "Python3"
},
{
"code": null,
"e": 16605,
"s": 16594,
"text": "Javascript"
},
{
"code": "// C++ program to show Indirect Recursion#include <iostream>using namespace std; void funB(int n); void funA(int n){ if (n > 0) { cout <<\" \"<< n; // fun(A) is calling fun(B) funB(n - 1); }} void funB(int n){ if (n > 1) { cout <<\" \"<< n; // fun(B) is calling fun(A) funA(n / 2); }} // Driver codeint main(){ funA(20); return 0;} // this code is contributed by shivanisinghss2110",
"e": 17045,
"s": 16605,
"text": null
},
{
"code": "// C program to show Indirect Recursion #include <stdio.h> void funB(int n); void funA(int n){ if (n > 0) { printf(\"%d \", n); // Fun(A) is calling fun(B) funB(n - 1); }} void funB(int n){ if (n > 1) { printf(\"%d \", n); // Fun(B) is calling fun(A) funA(n / 2); }} // Driver codeint main(){ funA(20); return 0;}",
"e": 17417,
"s": 17045,
"text": null
},
{
"code": "// Java program to show Indirect Recursionimport java.io.*; class GFG{ static void funA(int n){ if (n > 0) { System.out.print(\" \" +n); // Fun(A) is calling fun(B) funB(n - 1); }} static void funB(int n){ if (n > 1) { System.out.print(\" \" +n); // Fun(B) is calling fun(A) funA(n / 2); }} // Driver codepublic static void main (String[] args){ funA(20);}} // This code is contributed by shivanisinghss2110",
"e": 17881,
"s": 17417,
"text": null
},
{
"code": "// C# program to show Indirect Recursionusing System; class GFG{ static void funA(int n){ if (n > 0) { Console.Write(\" \" +n); // Fun(A) is calling fun(B) funB(n - 1); }} static void funB(int n){ if (n > 1) { Console.Write(\" \" +n); // Fun(B) is calling fun(A) funA(n / 2); }} // Driver codepublic static void Main (String[] args){ funA(20);}} // This code is contributed by shivanisinghss2110",
"e": 18333,
"s": 17881,
"text": null
},
{
"code": "# Python program to show Indirect Recursiondef funA(n): if (n > 0): print(\"\", n, end='') # Fun(A) is calling fun(B) funB(n - 1) def funB( n): if (n > 1): print(\"\", n, end='') # Fun(B) is calling fun(A) funA(n // 2) # Driver codefunA(20) # This code is contributed by shivanisinghss2110",
"e": 18698,
"s": 18333,
"text": null
},
{
"code": "<script> // JavaScript program to show Indirect Recursionfunction funA(n){ if (n > 0) { document.write(n.toFixed(0) + \"</br>\"); // Fun(A) is calling fun(B) funB(n - 1); }} function funB(n){ if (n > 1) { document.write(n.toFixed(0) + \"</br>\"); // Fun(B) is calling fun(A) funA(n / 2); }} // Driver codefunA(20); // this code is contributed by shivanisinghss2110</script>",
"e": 19124,
"s": 18698,
"text": null
},
{
"code": null,
"e": 19141,
"s": 19124,
"text": " 20 19 9 8 4 3 1"
},
{
"code": null,
"e": 19274,
"s": 19141,
"text": "Let’s understand the example by tracing tree of recursive function. That is how the calls are made and how the outputs are produced."
},
{
"code": null,
"e": 19573,
"s": 19274,
"text": "This article is contributed by AmiyaRanjanRout. 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] your article appearing on the GeeksforGeeks main page and help other Geeks. "
},
{
"code": null,
"e": 19589,
"s": 19573,
"text": "AmiyaRanjanRout"
},
{
"code": null,
"e": 19599,
"s": 19589,
"text": "pratham76"
},
{
"code": null,
"e": 19609,
"s": 19599,
"text": "rutvik_56"
},
{
"code": null,
"e": 19622,
"s": 19609,
"text": "darshkaushik"
},
{
"code": null,
"e": 19641,
"s": 19622,
"text": "shivanisinghss2110"
},
{
"code": null,
"e": 19656,
"s": 19641,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 19669,
"s": 19656,
"text": "abhishekaslk"
},
{
"code": null,
"e": 19679,
"s": 19669,
"text": "Recursion"
},
{
"code": null,
"e": 19689,
"s": 19679,
"text": "Recursion"
},
{
"code": null,
"e": 19787,
"s": 19689,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 19849,
"s": 19787,
"text": "Sum of the series (1*2) + (2*3) + (3*4) + ...... upto n terms"
},
{
"code": null,
"e": 19891,
"s": 19849,
"text": "Generate all the binary strings of N bits"
},
{
"code": null,
"e": 19931,
"s": 19891,
"text": "Traverse a given Matrix using Recursion"
},
{
"code": null,
"e": 19968,
"s": 19931,
"text": "Generating subarrays using recursion"
},
{
"code": null,
"e": 20009,
"s": 19968,
"text": "Practice Questions for Recursion | Set 1"
},
{
"code": null,
"e": 20071,
"s": 20009,
"text": "Recursively Reversing a linked list (A simple implementation)"
},
{
"code": null,
"e": 20149,
"s": 20071,
"text": "Generating all possible Subsequences using Recursion including the empty one."
},
{
"code": null,
"e": 20173,
"s": 20149,
"text": "Tutorial on Binary Tree"
},
{
"code": null,
"e": 20201,
"s": 20173,
"text": "Memoization (1D, 2D and 3D)"
}
] |
Deploying PySpark ML Model on Google Compute Engine as a REST API | by Ricky Kim | Towards Data Science | This post is loosely connected to my previous post.
Step-by-Step Tutorial: PySpark Sentiment Analysis on Google Dataproc
In my previous post, I trained a PySpark sentiment analysis model on Google Dataproc, and saved the model to Google Cloud Storage. In this post, I will show you how you can deploy a PySpark model on Google Compute Engine as a REST API. I will use the model I trained in my previous post, but I’m sure you can make some minor changes to the codes I will share and use with your own PySpark ML model.
I have the whole pipeline saved as a pipelineModel, and now I want to use the model for a REST API so that it can serve real-time predictions through simple REST API calls.
I first looked at Google Cloud ML Engine to see if this is a valid option for this specific use case. By reading through the introduction, you can not only train a machine learning model but also serve your model for predictions. But sadly it seems like Cloud ML Engine does not support Spark ML model. The next Google service I found was Google App Engine. This service made it really easy for anyone to deploy a web app. But after a couple of attempts, I realised it is not easy to set up Java Development Kit (which is needed to run PySpark) on the VM instances created through Google App Engine. It might be possible, but at least it was not straightforward enough for me to choose that route.
After some consideration and trials, below is the way that I found working. I will first go through the process step-by-step, then I will also tell you about the downside using Spark ML model for online real-time predictions.
In this tutorial, I will not go through the basic set up process again such as setting up a free account, enabling APIs for the services you want to use, installing Google Cloud SDK, but if this is your first time to try Google Cloud Platform I recommend you to check my previous post, and go through the set up steps (Creating a Free Trial Account on GCP, Enabling APIs, Installing Google Cloud SDK). Before you can proceed with the below steps, you will have to be ready by enabling Google Compute Engine API.
Now clone the git repository for this project by running below command in terminal.
git clone https://github.com/tthustla/flask_sparkml
Once you clone the repository, it will create a folder named flask_sparkml. Go into the folder and check what files are there.
cd flask_sparkml/ls
You will see three files and one subfolder.
install.sh (startup script when creating Compute Engine instance)
main.py (Flask web app to serve predictions as REST API)
model (the folder where trained PySpark pipeline model is stored)
response_time.py (simple Python script to measure API response time)
You can either create an instance through the web console or from your terminal using Google Cloud SDK. Before we create an instance, let’s take a quick look at the startup script install.sh to see what it does.
The above code will be a startup script for the VM.
Go to your console by visiting https://console.cloud.google.com/. Once you are in the console, click “Compute Engine” and “VM instances” from the left side menu. Click “Create”.
Type in the name for your VM instance, and choose the region and zone where you want your VM to be created. For this tutorial, we won’t use any other GCP services, so you can choose any region/zone you like, but it’s better to consider where the majority of the traffic will be coming from once the API is online.
Scroll down and choose “Allow full access to all Cloud APIs” in Identity and API access section, and tick “Allow HTTP traffic” in Firewall so that it can be reached from outside your VM. Finally, let’s add the startup script so that the VM will install required packages when starting up.
From the above screen just below Firewall section, you will see blue text “Management, security, disks, networking, sole tenancy”. Click on it to expand, and find the text box under “Startup script”. Copy and paste the whole install.sh code.
Click “Create” at the bottom.
In order to be able to interact with GCP from your terminal, you should be logged in to your account, and also it should be set to the project you intend to work on (I’m assuming you already have Google Cloud SDK installed on your terminal, if that’s not the case, please follow instructions on https://cloud.google.com/sdk/)
In order to check whether you’re signed in, copy and paste below command in your terminal, and it will show you which account is active.
gcloud auth list
If you want to check whether Google Cloud SDK is currently set to the project you want to work on, you can use below command from the terminal.
gcloud config list
If everything looks fine, run below command from your terminal in the flask_sparkml folder that you cloned from Git.
gcloud compute instances create flask-sparkml \--zone=europe-west1-b \--scopes=https://www.googleapis.com/auth/cloud-platform \--metadata-from-file startup-script=install.sh --tags http-server
This creates a VM instance with
instance name set to flask-sparkml
zone set to europe-west1-b
allow full access to all Cloud APIs
using local file install.sh as a startup script for the VM
allow HTTP traffic
In order to allow access to the application on port 8080 from outside, we need to create an inbound firewall rule which opens port 8080. Again you can choose to do this on web console or from the terminal.
From the left side menu on your console, find “VPC network” under “NETWORKING” section. Click into “Firewall rules” and click “CREATE FIREWALL RULE” button on the top. This will bring you to a screen looks like below.
First, give it a descriptive name. I named it “default-allow-http-8080”. Scroll down, and you will see the default setting of “Direction of traffic” is already set to “Ingress”, and also “Action on match” is set to “Allow”. For some reasons, if they are not, please make sure they are set properly.
Scroll down more to “Target tags” and give it a tag “http-server”. The tags are how GCP apply network rules to VM instances or instance template. When we created VM in the console, we have checked the tick box for “Allow HTTP traffic”. By doing this we are attaching any firewall rule with the tag “http-server” to the VM instance. Thus by creating a new firewall rule with the same tag will be automatically applied to your VM. Next, type in “0.0.0.0/0” for “Source IP ranges”. This will allow access to our API from any IP address. If you want to specify some limited ranges of IP, then you can do so here. Finally, under “Protocols and ports”, type in “8080” next to “tcp” and click “Create” button at the bottom.
If you want to create the firewall rule from your local terminal, you can run below command from your terminal.
gcloud compute firewall-rules create default-allow-http-8080 \ --allow tcp:8080 \ --source-ranges 0.0.0.0/0 \ --target-tags http-server
You can also check whether this firewall rule created properly.
gcloud compute firewall-rules list
Now a Compute Engine VM is created either through web console or from the terminal. To check whether the startup script is properly triggered, let’s connect to the VM. Again you can do this either through web console or from the terminal.
Go to “Compute Engine” and “VM instances” from the left side menu. You will see an instance running from the list. Click “SSH” under “Connect”.
If your default zone is set to the zone where your VM is created, and the project is set to the current project you are working on (properties you can see by running “gcloud config list” from the terminal), then you can simply type below command to SSH into your VM.
gcloud compute ssh [your_Google_user_name]@flask-sparkml
Now since we are on our VM, let’s inspect a few things. The startup script we provided earlier to VM includes Java JDK8 install and a few Python packages including PySpark. We can check whether they’re installed properly. (Please note that you need to give it a minute or two so that the VM will have enough time to finish the installations in the background.)
java -version
Java seems to be installed. What about the Python packages?
pip list
We can see four Python packages we specified in the startup script are installed on VM. Don’t close the VM terminal yet, since we will need to come back to this later.
The next step is to upload the main.py and model from our local machine to VM. Go to your local terminal and CD into flaks_sparkml (the folder cloned from Git) folder. Run below command to securely copy the files to VM.
gcloud compute scp --recurse . [your_Google_user_name]@flask-sparkml:~/flask_sparkml
Go back to VM terminal and check if the files are uploaded.
cd /home/[your_Google_user_name]/flask_sparkmlls -l
Finally, we are ready to run the actual Flask app.
Before we run the actual code, let’s take a quick look at the code to see what it does. The original code for this is from a Medium post Deploying a Machine Learning Model as a REST API by Nguyen Ngo, and I made some small changes to fit my specific use case. Thank you for the great tutorial Nguyen Ngo! I have already added comments inside the code, so I will not go through it line by line.
It’s time to run the application and make REST API call to the app to get a sentiment prediction from your own text! On your VM terminal (that you left open from the above “Connecting to Created VM Instance” step), run below command (using “nohup” command to prevent VM to go down after exiting VM terminal) from /home/[your_Google_user_name]/flask_sparkml directory.
nohup python main.py
You won’t be able to see the log output of the file main.py, since it writes logs to a file ‘nohup.out’. Let’s close the VM terminal to double check if ‘nohup’ is properly working, and get real-time sentiment prediction through an API call. In order to do that, we first need to know the external IP address that our app is deployed at. You can either check on your web console’s “Compute Engine” -> “VM Instances”
or check from your local terminal by running below command.
gcloud compute instances list
Either start Python from your local terminal or open a Jupyter Notebook and copy and paste below code block and run to see the result.
I expect to see the model to predict the above text as negative.
Hooray! The prediction from our model says it’s negative with quite high confidence.
You might have noticed that there is one more file in the folder that I haven’t mentioned yet. While going through this project, there has been one big question mark in my head. I know Spark can handle big data, and this might be beneficial in the model training stage. But how is the performance of Spark ML, when it is deployed to perform real-time prediction on single entries? When I made the API call in the above, it sure didn’t feel very fast. So I added a final experiment to the finished API. It is a simple Python program, designed to make 100 queries to the API and record API response times. At the end, it shows mean, median, min, max of this recorded response times.
Go to your local terminal, in the flask_sparkml folder, run the program and check the output.
python response_time.py http://[external_IP_address_of_your_app]:8080
Is this fast or slow? We have no way of knowing without a benchmark. So I have googled hard to find some other’s machine learning API response time. And I finally found this Medium post Falcon vs. Flask-Which one to pick to create a scalable deep learning REST API by Dat Tran. Thank you for the informative post, Dat Tran!
From Dat Tran’s post, the average response time for Keras CNN model on MNIST dataset is 60ms. We can see that the average response time of Spark ML is 0.99 seconds, which is 990ms. That doesn’t sound good at all.
While I was looking for an answer for this, I came across a presentation slide Productionizing Spark ML Pipelines with the Portable Format for Analytics by Nick Pentreath. Thank you for the great slide, Nick Pentreath! PFA (Portable Format for Analytics) is a JSON representation of Spark ML model that can be transferred across different languages, platforms. The reason why I’m mentioning this even when I didn’t export my model as PFA, is that he goes through some limitations of Spark ML model in production.
According to the slide (page 9: Challenges specific to Spark), scoring models in Spark is slow due to the overheads of Spark Dataframes and task scheduling, and not the best framework to be used for real-time scoring due to its latency.
Even though we have a working REST API deployed, this seems to be not the ideal solution to serve machine learning prediction real-time. I can explore further into exporting the model as PFA and compare the performance. Or I can also try to build a new model from scratch using Keras or Tensorflow, and deploy it to compare the performance with Spark ML. At the moment, I’m more tempted to try the latter, since it will give me chances to explore other GCP services such as Google Cloud ML Engine. Anyway, I will try to share the next part of my journey here.
To avoid incurring unwanted charges on your GCP account it’s important to clean up. You can simply delete the VM instance you created, but in case you want to know how to kill the nohup process we started with the file main.py, I will go through simple steps to kill processes running in the background. Go to your VM terminal either from web console or from your local terminal using “glcoud compute ssh” command. Once you are in the VM terminal, run below command to check the process ID of main.py running in the background.
ps aux | grep python | grep main.py
Once you have IDs of the currently running processes kill them using below command replacing [] parts with the process IDs of yours.
sudo kill [PID1] [PID2]
The actual deleting instance part can be done either on web console or from the terminal.
gcloud compute instances delete flask-sparkml
Thank you for reading. You can find the Git Repository of the scripts from the below link. | [
{
"code": null,
"e": 224,
"s": 172,
"text": "This post is loosely connected to my previous post."
},
{
"code": null,
"e": 293,
"s": 224,
"text": "Step-by-Step Tutorial: PySpark Sentiment Analysis on Google Dataproc"
},
{
"code": null,
"e": 692,
"s": 293,
"text": "In my previous post, I trained a PySpark sentiment analysis model on Google Dataproc, and saved the model to Google Cloud Storage. In this post, I will show you how you can deploy a PySpark model on Google Compute Engine as a REST API. I will use the model I trained in my previous post, but I’m sure you can make some minor changes to the codes I will share and use with your own PySpark ML model."
},
{
"code": null,
"e": 865,
"s": 692,
"text": "I have the whole pipeline saved as a pipelineModel, and now I want to use the model for a REST API so that it can serve real-time predictions through simple REST API calls."
},
{
"code": null,
"e": 1563,
"s": 865,
"text": "I first looked at Google Cloud ML Engine to see if this is a valid option for this specific use case. By reading through the introduction, you can not only train a machine learning model but also serve your model for predictions. But sadly it seems like Cloud ML Engine does not support Spark ML model. The next Google service I found was Google App Engine. This service made it really easy for anyone to deploy a web app. But after a couple of attempts, I realised it is not easy to set up Java Development Kit (which is needed to run PySpark) on the VM instances created through Google App Engine. It might be possible, but at least it was not straightforward enough for me to choose that route."
},
{
"code": null,
"e": 1789,
"s": 1563,
"text": "After some consideration and trials, below is the way that I found working. I will first go through the process step-by-step, then I will also tell you about the downside using Spark ML model for online real-time predictions."
},
{
"code": null,
"e": 2301,
"s": 1789,
"text": "In this tutorial, I will not go through the basic set up process again such as setting up a free account, enabling APIs for the services you want to use, installing Google Cloud SDK, but if this is your first time to try Google Cloud Platform I recommend you to check my previous post, and go through the set up steps (Creating a Free Trial Account on GCP, Enabling APIs, Installing Google Cloud SDK). Before you can proceed with the below steps, you will have to be ready by enabling Google Compute Engine API."
},
{
"code": null,
"e": 2385,
"s": 2301,
"text": "Now clone the git repository for this project by running below command in terminal."
},
{
"code": null,
"e": 2437,
"s": 2385,
"text": "git clone https://github.com/tthustla/flask_sparkml"
},
{
"code": null,
"e": 2564,
"s": 2437,
"text": "Once you clone the repository, it will create a folder named flask_sparkml. Go into the folder and check what files are there."
},
{
"code": null,
"e": 2584,
"s": 2564,
"text": "cd flask_sparkml/ls"
},
{
"code": null,
"e": 2628,
"s": 2584,
"text": "You will see three files and one subfolder."
},
{
"code": null,
"e": 2694,
"s": 2628,
"text": "install.sh (startup script when creating Compute Engine instance)"
},
{
"code": null,
"e": 2751,
"s": 2694,
"text": "main.py (Flask web app to serve predictions as REST API)"
},
{
"code": null,
"e": 2817,
"s": 2751,
"text": "model (the folder where trained PySpark pipeline model is stored)"
},
{
"code": null,
"e": 2886,
"s": 2817,
"text": "response_time.py (simple Python script to measure API response time)"
},
{
"code": null,
"e": 3098,
"s": 2886,
"text": "You can either create an instance through the web console or from your terminal using Google Cloud SDK. Before we create an instance, let’s take a quick look at the startup script install.sh to see what it does."
},
{
"code": null,
"e": 3150,
"s": 3098,
"text": "The above code will be a startup script for the VM."
},
{
"code": null,
"e": 3328,
"s": 3150,
"text": "Go to your console by visiting https://console.cloud.google.com/. Once you are in the console, click “Compute Engine” and “VM instances” from the left side menu. Click “Create”."
},
{
"code": null,
"e": 3642,
"s": 3328,
"text": "Type in the name for your VM instance, and choose the region and zone where you want your VM to be created. For this tutorial, we won’t use any other GCP services, so you can choose any region/zone you like, but it’s better to consider where the majority of the traffic will be coming from once the API is online."
},
{
"code": null,
"e": 3931,
"s": 3642,
"text": "Scroll down and choose “Allow full access to all Cloud APIs” in Identity and API access section, and tick “Allow HTTP traffic” in Firewall so that it can be reached from outside your VM. Finally, let’s add the startup script so that the VM will install required packages when starting up."
},
{
"code": null,
"e": 4173,
"s": 3931,
"text": "From the above screen just below Firewall section, you will see blue text “Management, security, disks, networking, sole tenancy”. Click on it to expand, and find the text box under “Startup script”. Copy and paste the whole install.sh code."
},
{
"code": null,
"e": 4203,
"s": 4173,
"text": "Click “Create” at the bottom."
},
{
"code": null,
"e": 4529,
"s": 4203,
"text": "In order to be able to interact with GCP from your terminal, you should be logged in to your account, and also it should be set to the project you intend to work on (I’m assuming you already have Google Cloud SDK installed on your terminal, if that’s not the case, please follow instructions on https://cloud.google.com/sdk/)"
},
{
"code": null,
"e": 4666,
"s": 4529,
"text": "In order to check whether you’re signed in, copy and paste below command in your terminal, and it will show you which account is active."
},
{
"code": null,
"e": 4683,
"s": 4666,
"text": "gcloud auth list"
},
{
"code": null,
"e": 4827,
"s": 4683,
"text": "If you want to check whether Google Cloud SDK is currently set to the project you want to work on, you can use below command from the terminal."
},
{
"code": null,
"e": 4846,
"s": 4827,
"text": "gcloud config list"
},
{
"code": null,
"e": 4963,
"s": 4846,
"text": "If everything looks fine, run below command from your terminal in the flask_sparkml folder that you cloned from Git."
},
{
"code": null,
"e": 5156,
"s": 4963,
"text": "gcloud compute instances create flask-sparkml \\--zone=europe-west1-b \\--scopes=https://www.googleapis.com/auth/cloud-platform \\--metadata-from-file startup-script=install.sh --tags http-server"
},
{
"code": null,
"e": 5188,
"s": 5156,
"text": "This creates a VM instance with"
},
{
"code": null,
"e": 5223,
"s": 5188,
"text": "instance name set to flask-sparkml"
},
{
"code": null,
"e": 5250,
"s": 5223,
"text": "zone set to europe-west1-b"
},
{
"code": null,
"e": 5286,
"s": 5250,
"text": "allow full access to all Cloud APIs"
},
{
"code": null,
"e": 5345,
"s": 5286,
"text": "using local file install.sh as a startup script for the VM"
},
{
"code": null,
"e": 5364,
"s": 5345,
"text": "allow HTTP traffic"
},
{
"code": null,
"e": 5570,
"s": 5364,
"text": "In order to allow access to the application on port 8080 from outside, we need to create an inbound firewall rule which opens port 8080. Again you can choose to do this on web console or from the terminal."
},
{
"code": null,
"e": 5788,
"s": 5570,
"text": "From the left side menu on your console, find “VPC network” under “NETWORKING” section. Click into “Firewall rules” and click “CREATE FIREWALL RULE” button on the top. This will bring you to a screen looks like below."
},
{
"code": null,
"e": 6087,
"s": 5788,
"text": "First, give it a descriptive name. I named it “default-allow-http-8080”. Scroll down, and you will see the default setting of “Direction of traffic” is already set to “Ingress”, and also “Action on match” is set to “Allow”. For some reasons, if they are not, please make sure they are set properly."
},
{
"code": null,
"e": 6804,
"s": 6087,
"text": "Scroll down more to “Target tags” and give it a tag “http-server”. The tags are how GCP apply network rules to VM instances or instance template. When we created VM in the console, we have checked the tick box for “Allow HTTP traffic”. By doing this we are attaching any firewall rule with the tag “http-server” to the VM instance. Thus by creating a new firewall rule with the same tag will be automatically applied to your VM. Next, type in “0.0.0.0/0” for “Source IP ranges”. This will allow access to our API from any IP address. If you want to specify some limited ranges of IP, then you can do so here. Finally, under “Protocols and ports”, type in “8080” next to “tcp” and click “Create” button at the bottom."
},
{
"code": null,
"e": 6916,
"s": 6804,
"text": "If you want to create the firewall rule from your local terminal, you can run below command from your terminal."
},
{
"code": null,
"e": 7055,
"s": 6916,
"text": "gcloud compute firewall-rules create default-allow-http-8080 \\ --allow tcp:8080 \\ --source-ranges 0.0.0.0/0 \\ --target-tags http-server"
},
{
"code": null,
"e": 7119,
"s": 7055,
"text": "You can also check whether this firewall rule created properly."
},
{
"code": null,
"e": 7154,
"s": 7119,
"text": "gcloud compute firewall-rules list"
},
{
"code": null,
"e": 7393,
"s": 7154,
"text": "Now a Compute Engine VM is created either through web console or from the terminal. To check whether the startup script is properly triggered, let’s connect to the VM. Again you can do this either through web console or from the terminal."
},
{
"code": null,
"e": 7537,
"s": 7393,
"text": "Go to “Compute Engine” and “VM instances” from the left side menu. You will see an instance running from the list. Click “SSH” under “Connect”."
},
{
"code": null,
"e": 7804,
"s": 7537,
"text": "If your default zone is set to the zone where your VM is created, and the project is set to the current project you are working on (properties you can see by running “gcloud config list” from the terminal), then you can simply type below command to SSH into your VM."
},
{
"code": null,
"e": 7861,
"s": 7804,
"text": "gcloud compute ssh [your_Google_user_name]@flask-sparkml"
},
{
"code": null,
"e": 8222,
"s": 7861,
"text": "Now since we are on our VM, let’s inspect a few things. The startup script we provided earlier to VM includes Java JDK8 install and a few Python packages including PySpark. We can check whether they’re installed properly. (Please note that you need to give it a minute or two so that the VM will have enough time to finish the installations in the background.)"
},
{
"code": null,
"e": 8236,
"s": 8222,
"text": "java -version"
},
{
"code": null,
"e": 8296,
"s": 8236,
"text": "Java seems to be installed. What about the Python packages?"
},
{
"code": null,
"e": 8305,
"s": 8296,
"text": "pip list"
},
{
"code": null,
"e": 8473,
"s": 8305,
"text": "We can see four Python packages we specified in the startup script are installed on VM. Don’t close the VM terminal yet, since we will need to come back to this later."
},
{
"code": null,
"e": 8693,
"s": 8473,
"text": "The next step is to upload the main.py and model from our local machine to VM. Go to your local terminal and CD into flaks_sparkml (the folder cloned from Git) folder. Run below command to securely copy the files to VM."
},
{
"code": null,
"e": 8778,
"s": 8693,
"text": "gcloud compute scp --recurse . [your_Google_user_name]@flask-sparkml:~/flask_sparkml"
},
{
"code": null,
"e": 8838,
"s": 8778,
"text": "Go back to VM terminal and check if the files are uploaded."
},
{
"code": null,
"e": 8890,
"s": 8838,
"text": "cd /home/[your_Google_user_name]/flask_sparkmlls -l"
},
{
"code": null,
"e": 8941,
"s": 8890,
"text": "Finally, we are ready to run the actual Flask app."
},
{
"code": null,
"e": 9335,
"s": 8941,
"text": "Before we run the actual code, let’s take a quick look at the code to see what it does. The original code for this is from a Medium post Deploying a Machine Learning Model as a REST API by Nguyen Ngo, and I made some small changes to fit my specific use case. Thank you for the great tutorial Nguyen Ngo! I have already added comments inside the code, so I will not go through it line by line."
},
{
"code": null,
"e": 9703,
"s": 9335,
"text": "It’s time to run the application and make REST API call to the app to get a sentiment prediction from your own text! On your VM terminal (that you left open from the above “Connecting to Created VM Instance” step), run below command (using “nohup” command to prevent VM to go down after exiting VM terminal) from /home/[your_Google_user_name]/flask_sparkml directory."
},
{
"code": null,
"e": 9724,
"s": 9703,
"text": "nohup python main.py"
},
{
"code": null,
"e": 10139,
"s": 9724,
"text": "You won’t be able to see the log output of the file main.py, since it writes logs to a file ‘nohup.out’. Let’s close the VM terminal to double check if ‘nohup’ is properly working, and get real-time sentiment prediction through an API call. In order to do that, we first need to know the external IP address that our app is deployed at. You can either check on your web console’s “Compute Engine” -> “VM Instances”"
},
{
"code": null,
"e": 10199,
"s": 10139,
"text": "or check from your local terminal by running below command."
},
{
"code": null,
"e": 10229,
"s": 10199,
"text": "gcloud compute instances list"
},
{
"code": null,
"e": 10364,
"s": 10229,
"text": "Either start Python from your local terminal or open a Jupyter Notebook and copy and paste below code block and run to see the result."
},
{
"code": null,
"e": 10429,
"s": 10364,
"text": "I expect to see the model to predict the above text as negative."
},
{
"code": null,
"e": 10514,
"s": 10429,
"text": "Hooray! The prediction from our model says it’s negative with quite high confidence."
},
{
"code": null,
"e": 11195,
"s": 10514,
"text": "You might have noticed that there is one more file in the folder that I haven’t mentioned yet. While going through this project, there has been one big question mark in my head. I know Spark can handle big data, and this might be beneficial in the model training stage. But how is the performance of Spark ML, when it is deployed to perform real-time prediction on single entries? When I made the API call in the above, it sure didn’t feel very fast. So I added a final experiment to the finished API. It is a simple Python program, designed to make 100 queries to the API and record API response times. At the end, it shows mean, median, min, max of this recorded response times."
},
{
"code": null,
"e": 11289,
"s": 11195,
"text": "Go to your local terminal, in the flask_sparkml folder, run the program and check the output."
},
{
"code": null,
"e": 11359,
"s": 11289,
"text": "python response_time.py http://[external_IP_address_of_your_app]:8080"
},
{
"code": null,
"e": 11683,
"s": 11359,
"text": "Is this fast or slow? We have no way of knowing without a benchmark. So I have googled hard to find some other’s machine learning API response time. And I finally found this Medium post Falcon vs. Flask-Which one to pick to create a scalable deep learning REST API by Dat Tran. Thank you for the informative post, Dat Tran!"
},
{
"code": null,
"e": 11896,
"s": 11683,
"text": "From Dat Tran’s post, the average response time for Keras CNN model on MNIST dataset is 60ms. We can see that the average response time of Spark ML is 0.99 seconds, which is 990ms. That doesn’t sound good at all."
},
{
"code": null,
"e": 12409,
"s": 11896,
"text": "While I was looking for an answer for this, I came across a presentation slide Productionizing Spark ML Pipelines with the Portable Format for Analytics by Nick Pentreath. Thank you for the great slide, Nick Pentreath! PFA (Portable Format for Analytics) is a JSON representation of Spark ML model that can be transferred across different languages, platforms. The reason why I’m mentioning this even when I didn’t export my model as PFA, is that he goes through some limitations of Spark ML model in production."
},
{
"code": null,
"e": 12646,
"s": 12409,
"text": "According to the slide (page 9: Challenges specific to Spark), scoring models in Spark is slow due to the overheads of Spark Dataframes and task scheduling, and not the best framework to be used for real-time scoring due to its latency."
},
{
"code": null,
"e": 13206,
"s": 12646,
"text": "Even though we have a working REST API deployed, this seems to be not the ideal solution to serve machine learning prediction real-time. I can explore further into exporting the model as PFA and compare the performance. Or I can also try to build a new model from scratch using Keras or Tensorflow, and deploy it to compare the performance with Spark ML. At the moment, I’m more tempted to try the latter, since it will give me chances to explore other GCP services such as Google Cloud ML Engine. Anyway, I will try to share the next part of my journey here."
},
{
"code": null,
"e": 13734,
"s": 13206,
"text": "To avoid incurring unwanted charges on your GCP account it’s important to clean up. You can simply delete the VM instance you created, but in case you want to know how to kill the nohup process we started with the file main.py, I will go through simple steps to kill processes running in the background. Go to your VM terminal either from web console or from your local terminal using “glcoud compute ssh” command. Once you are in the VM terminal, run below command to check the process ID of main.py running in the background."
},
{
"code": null,
"e": 13770,
"s": 13734,
"text": "ps aux | grep python | grep main.py"
},
{
"code": null,
"e": 13903,
"s": 13770,
"text": "Once you have IDs of the currently running processes kill them using below command replacing [] parts with the process IDs of yours."
},
{
"code": null,
"e": 13927,
"s": 13903,
"text": "sudo kill [PID1] [PID2]"
},
{
"code": null,
"e": 14017,
"s": 13927,
"text": "The actual deleting instance part can be done either on web console or from the terminal."
},
{
"code": null,
"e": 14063,
"s": 14017,
"text": "gcloud compute instances delete flask-sparkml"
}
] |
KBC game using Python - GeeksforGeeks | 27 Jul, 2021
In this article, we will make a KBC game with almost all the features in CLI(Command Line Interface) mode using Python.
Random questions every time
Four lifelinesAudience Poll50:50Double dipFlip the question
Audience Poll
50:50
Double dip
Flip the question
Made with the help of Matplotlib and NumPy libraries of python.
Bar graph for audience poll lifeline
There are four lifelines in this game named Audience Poll,50:50, Double dip, and Flip the question.
2 Stages at ₹10,000 and ₹3,20,000.
Users cannot use another lifeline after taking Double Dip.
Lifelines can be used only once.
Quit option is not available after taking Double Dip.
After taking Audience Poll, the user can also take another lifeline except for Double Dip. The same is for 50:50 and Flip the question.
Users can quit from game anytime.
The total winning price will be displayed after every question.
If the user has selected an incorrect option, the amount will be given according to stage cleared.
Create a new python file.
Make a list of questions.
Also make a list of answers, options, fifty-fifty options, audience poll percentage for options.
Implement a random function so that every time when a user plays a game, he/she can get new random questions from a list of questions.
After the question is answered by a user, assure that that question would not appear again. To do this, delete the answered question from the list and associated options within that question.
If the user needs any help then he/she can use a lifeline from the four lifelines i.e, Audience Poll, Fifty-Fifty, Double dip, and Flip the question.
When the user gives the correct answer to the question, the answered question amount is added to the total amount.
Added some questions in a list with options.
Run while loop and check the condition.If true then proceed further. After that display question to the user with options and ask for input(1, 2, 3, 4, or 9 for lifeline and 0 to exit). Random function is used to shuffle the question every time when a user plays the game.If the user is able to give the correct answer then he can choose an option. If the input given is correct then the winning amount is incremented and the next question will be displayed and the previous question is deleted from the list to avoid repetition of questions.If the user’s input is incorrect then he/she will be given the total winning amount. Remember that there are two stages in the game. If the user has given the wrong answer then the amount will be given according to stage cleared.User can quit the game anytime and the current winning amount will be given.If the user fails to choose the correct answer then he/she can take the lifeline.
If true then proceed further. After that display question to the user with options and ask for input(1, 2, 3, 4, or 9 for lifeline and 0 to exit). Random function is used to shuffle the question every time when a user plays the game.
If the user is able to give the correct answer then he can choose an option. If the input given is correct then the winning amount is incremented and the next question will be displayed and the previous question is deleted from the list to avoid repetition of questions.
If the user’s input is incorrect then he/she will be given the total winning amount. Remember that there are two stages in the game. If the user has given the wrong answer then the amount will be given according to stage cleared.
User can quit the game anytime and the current winning amount will be given.
If the user fails to choose the correct answer then he/she can take the lifeline.
Python3
while(wrong != True): ques_no += 1 ran = random.randint(0, len(questions)-1) print("\n\nQ.", ques_no, ":-", end="") print(questions[ran]) for num, option in enumerate(options): print(str(num+1)+"."+option[ran]) print("Would you like to take lifeline, if yes, press 9\n\ Choose any option: or you can quit by pressing 0 \t\t") give_answer = int(input()) if give_answer == 9: # condition variable is to count lifelines # used if condition <= 4: condition += 1 great = lifeline(ran, opts, op) if great == 0: if total_amt < 10000: total_amt = 0 elif total_amt < 320000: total_amt = 10000 elif total_amt < 70000000: total_amt = 320000 break elif great == -1: ques_no -= 1 pass elif great == None: print("Choose any option or press 0 to quit\t") give_ansr = int(input()) if answer[ran] == give_ansr: print("Correct answer, great") correct += 1 elif great == -2: break else: correct += 1 print("You have won Rs=", end="") total_amt = amount(correct) else: print("You have used your all lifelines\t\n Choose any option: \ or you can quit by pressing 0\t\t") give_ans = int(input()) key = answer[ran] if give_ans == 0: total_amt = amount(correct) break elif key == give_ans: print("Correct, You have won Rs. =", end="") correct += 1 total_amt = amount(correct) else: print("Wrong Answer....") print("Correct Answer is : ", options[answer[ran]-1][ran]) if total_amt < 10000: total_amt = 0 elif total_amt < 320000: total_amt = 10000 elif total_amt < 70000000: total_amt = 32000 wrong = True else: key = answer[ran] if give_answer == 0: if correct != 0: total_amt = amount(correct) break elif key == give_answer: print("Correct answer.., You have won Rs.=", end="") correct += 1 total_amt = amount(correct) else: print("Wrong Answer...Better luck next time...") print("Correct Answer is :", options[answer[ran]-1][ran]) if total_amt < 10000: total_amt = 0 elif total_amt < 320000: total_amt = 10000 elif total_amt < 70000000: total_amt = 320000 wrong = True # total questions are 16 if correct == 16: break # delete previous question and its options from list del questions[ran] del option1[ran] del option2[ran] del option3[ran] del option4[ran] del answer[ran] del opts[0][ran] del opts[1][ran] del opts[2][ran] del opts[3][ran] del op[0][ran] del op[1][ran] del op[2][ran] del op[3][ran] options = [option1, option2, option3, option4] print("Your winning amount is Rs. ", total_amt)
Audience Poll lifeline:The graph will be shown with the correct percentage assigned to all the options. [For ex: A- 32%, B- 56%, C-2%, D-10%].User can either choose the correct answer or can take another lifeline.
The graph will be shown with the correct percentage assigned to all the options. [For ex: A- 32%, B- 56%, C-2%, D-10%].
User can either choose the correct answer or can take another lifeline.
Python3
def audience(ran, opts): # graphical audience poll using pandas print("According to audience\n") s = pd.Series([opt1[ran], opt2[ran], opt3[ran], opt4[ran]], index=['1', '2', '3', '4']) s.plot.bar(figsize=(20, 10)) plt.xlabel('Options') plt.ylabel('%') plt.title("Audience Poll") plt.show() print('1.', opts[0][ran], "%", '\t', '2.', opts[1][ran], "%", '\t', '3.',opts[2][ran], "%", '\t', '4.', opts[3][ran], "%", '\nenter your choice\t') print("Would you like to take lifeline again,if yes then\ press 9 or Press 0 to Quit\t") choice = int(input()) if choice == 9: great = lifeline(ran, opts, op) return great elif choice == answer[ran]: great = 1 print("Correct answer,well done!..") elif choice == 0: great = -2 else: great = 0 print("Incorrect") print("Correct Answer is :", options[answer[ran]-1][ran]) return great
Fifty-Fifty:Two incorrect options will be deleted.User can either choose the correct answer or can take another lifeline.
Two incorrect options will be deleted.
User can either choose the correct answer or can take another lifeline.
Python3
def fifty(ran, op): print("Q."+questions[ran]) for num, option in enumerate(op): print(str(num+1)+"."+option[ran]) choice_fifty = int(input("enter your choice \t")) if choice_fifty == answer[ran]: print("Correct Answer.....") great = 1 else: great = 0 print("wrong answer") print("Correct Answer is :", options[answer[ran]-1][ran]) return great
Double dip:The user will be given two chances to choose the correct option. Remember that after taking double-dip, the user will not able to use any other lifeline. He/she can either choose a correct option or can quit the game.
The user will be given two chances to choose the correct option. Remember that after taking double-dip, the user will not able to use any other lifeline. He/she can either choose a correct option or can quit the game.
Python3
def doubleDip(ran): # double dip gives 2 chances print("Select two options\n") trial1 = int(input()) if answer[ran] == trial1: great = 1 print("Correct Answer,well done....") else: print("Your first trial is wrong, choose another\t") trial2 = int(input()) if answer[ran] == trial2: great = 1 print("Correct Answer\t") else: print("Your second trial is also wrong..Better luck next time..\t") print("Correct Answer is :", options[answer[ran]-1][ran]) great = 0 return great
Flip the question:When flip the question lifelines is taken then the current question is skipped and next question is displayed.
When flip the question lifelines is taken then the current question is skipped and next question is displayed.
Given below is the full implementation.
Program:
Python3
import randomfrom matplotlib import pyplot as pltimport pandas as pd print("WELCOME TO KAUN BANEGA CROREPATI...LET'S PLAY")print("Hello", input("Enter Your Name\t")) # total prize for each questionamount_won = [1000, 2000, 3000, 5000, 10000, 20000, 40000, 80000, 160000, 320000, 640000, 1250000, 2500000, 5000000, 10000000, 70000000]# Options for 50:50 lifelineop1 = [' ', ' ', ' ', 'Srinagar', ' ', 'Cricket', '1920', ' ', ' ', ' ', ' ', 'Cricket', ' ', 'Kolkata', 'Wrestling', ' ', ' ', ' ', 'China', 'Thar', ' ', ' ', 'Israel', ' ', ' ', 'Arjan Singh', 'Parliament of India', ' ', ' ', 'Mohd Hamid Ansari ', ' ', 'Mahatma Gandhi', 'Hanuman'] op2 = ['AB De Villiers', ' ', '9', ' ', ' ', ' ', '1928', ' ', 'Cricket', 'Yuvraj Singh', 'Cricket', 'Football', 'West Indies', 'Mumbai', 'Swimming', ' ', ' ', ' ', ' ', 'Sahara', 'Mahishmati', ' ', 'Jordan', ' ', 'Che Guevera', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '] op3 = ['Shahid Afridi', 'Dishonest', ' ', 'Amritsar', 'Sindhi', ' ', ' ', 'Pakistan', ' ', 'MS Dhoni', ' ', ' ', 'South Africa', ' ', ' ', 'Henry Becquarrel', 'Tephrosia', 'Dermatitis', 'Japan', ' ', ' ', 'Bypass', ' ', 'Mridangam', ' ', ' ', ' ', 'darjeeling', 'Japanese Encephalitis ', 'Mohd Hidayatullah ', 'Saina Nehwal', ' ', 'Shiva'] op4 = [' ', 'Miserly', '8', ' ', 'English', 'Hockey', ' ', 'Australia', 'Football', ' ', 'Polo', ' ', ' ', ' ', ' ', 'None of these', 'Indigofera', 'Cholera', ' ', ' ', 'Badami', 'Debridement', ' ', 'Dafli', 'Vladimir Lenin', 'Aspy Engineer', 'Mangalyaan', 'Kohima', 'Plague', ' ', 'Jwala Gutta', 'Mother Teresa', ' '] op = [op1, op2, op3, op4] # list of lifelineslist_life = [1, 2, 3, 4] def lifeline(ran, opts, op): m = 1 lifelines = ['Audience Poll', 'Fifty Fifty', 'Double dip', 'Flip the question'] print("Lifelines are \t", lifelines[0], '\t', lifelines[1], '\t', lifelines[2], '\t', lifelines[3], '\n\n') if list_life == []: print("You don't have lifelines remaining\t") return None print("Press 1 for audience,2 for 50:50, 3 for double dip\ or 4 for flip the question\t") while(m != 0): get = int(input()) if get == 1: if get in list_life: m = 0 list_life.remove(1) great = audience(ran, opts) else: print("You don't have audience poll\t") elif get == 2: if get in list_life: m = 0 great = fifty(ran, op) list_life.remove(2) else: print("You don't have 50:50 \t") elif get == 3: if get in list_life: m = 0 great = doubleDip(ran) list_life.remove(3) else: print("You don't have double dip\t") elif get == 4: if get in list_life: m = 0 great = flip() list_life.remove(4) else: print("You don't have lifeline to flip the question\t") else: print("Choose correct option") return great def audience(ran, opts): # graphical audience poll using pandas print("According to audience\n") s = pd.Series([opt1[ran], opt2[ran], opt3[ran], opt4[ran]], index=['1', '2', '3', '4']) s.plot.bar(figsize=(20, 10)) plt.xlabel('Options') plt.ylabel('%') plt.title("Audience Poll") plt.show() print('1.', opts[0][ran], "%", '\t', '2.', opts[1][ran], "%", '\t', '3.', opts[2][ran], "%", '\t', '4.', opts[3][ran], "%", '\nenter your choice\t') print("Would you like to take lifeline again,if yes then press\ 9 or Press 0 to Quit\t") choice = int(input()) if choice == 9: great = lifeline(ran, opts, op) return great elif choice == answer[ran]: great = 1 print("Correct answer,well done!..") elif choice == 0: great = -2 else: great = 0 print("Incorrect") print("Correct Answer is :", options[answer[ran]-1][ran]) return great def fifty(ran, op): print("Q."+questions[ran]) for num, option in enumerate(op): print(str(num+1)+"."+option[ran]) choice_fifty = int(input("enter your choice \t")) if choice_fifty == answer[ran]: print("Correct Answer.....") great = 1 else: great = 0 print("wrong answer") print("Correct Answer is :", options[answer[ran]-1][ran]) return great def doubleDip(ran): # double dip gives 2 chances print("Select two options\n") trial1 = int(input()) if answer[ran] == trial1: great = 1 print("Correct Answer,well done....") else: print("Your first trial is wrong, choose another\t") trial2 = int(input()) if answer[ran] == trial2: great = 1 print("Correct Answer\t") else: print("Your second trial is also wrong..Better luck next time..\t") print("Correct Answer is :", options[answer[ran]-1][ran]) great = 0 return great def flip(): return -1 def amount(correct_ans): print(amount_won[correct_ans-1]) if amount_won[correct_ans-1] == 10000: print("Completed 1st stage") elif amount_won[correct_ans-1] == 320000: print("Completed 2st stage") elif amount_won[correct_ans-1] == 70000000: print("You have won Rs 7 CRORE") return amount_won[correct_ans-1] questions = [ 'In ODI Cricket, who created the record of scoring the \ fastest century in just 31 balls ?', ' If you call someone ‘Makkhichoos’ then what are you \ calling him ?', 'How many players of a Kho-Kho team can play on the field\ during the match ?', 'Which of these Indian cities is closest to the Pakistani \ city of Lahore ?', 'The language spoken by the people by Pakistan is ?', 'The term“Googly” is associated with ?', 'India first took part in the olympic games in the year ?', 'Who are Kangaroos ?', 'Oval stadium in England is associated with ?', 'In 2011 India won the World Cup. Who was adjudicated as the\ man of the series in the tournament ? ', 'Eden Gardens in Kolkata is ----- stadium.? ', 'Ronaldo is associated with ? ', 'Icc’s 2007, the World Cup Cricket was held in ? ', 'Wankhede Stadium is at ? ', 'World’s most ancient game is ? ', 'Stethoscope was invented by ?', 'A dye is prepared from ', 'Which disease is caused by the fungi? ', 'Which is the Land of the Rising Sun? ', 'The desert that lies on the boundary between India and Pakistan \ is ', ' In which kingdom is the story of the ‘Bahubali’ series of films\ mainly set?', 'What is the common name for surgery conducted on coronary arteries\ that supply blood to the heart ?', ' In July 2017, Narendra Modi Become the first Indian Prime Minister\ to visit which country ?', 'Which of these musical instrument is held in one hand and played with\ the other ?', ' On the last day of his life Bhagat Singh was reading a book about\ the Ideology of which revolutionary ?', 'Which Air force officer had the unique honour of leading the fly-post\ over the Red fort in Delhi on 15 August 1947 ?', 'Which image appears on the flip side of the new 2000 Rs Note, launched\ in 2016?', 'Which Indian hill station gets its name from the Tibetan words that mean\ ‘land of the thunderbolt’?', 'Which of these diseases is transmitted by mosquitoes?', 'Who among these has served as the Ambassador of India to the United Nations?', ' Who was the first Indian to win the World Junior Badminton Championships?', 'Which of the following is a recipient of the Nobel Peace Prize?', 'The cave temples at the historical site of Elephanta are dedicated to which\ God?'] option1 = ['Corey Anderson', 'Evil', '10', 'Srinagar', 'Hindi', 'Cricket', '1920', 'Bangladesh', 'polo', 'Virat Kohli', 'Tennis', 'Cricket', 'Australia', 'Kolkata', 'Wrestling', 'Bessemer', 'Sida', 'Polio', 'China', 'Thar', 'Magadh', 'Cataract', 'Israel', 'Tabla', 'Antonio Gramsci ', 'Arjan Singh', 'Parliament of India', 'Gangtok', 'Rabies', ' Mohd Hamid Ansari', 'P V Sindhu', 'Mahatma Gandhi', 'Hanuman'] option2 = ['AB De Villiers', 'Humble', '9', 'Jaisalmer', 'Palauan', 'Football', '1928', 'Kenya', 'Cricket', 'Yuvraj Singh', 'Cricket', 'Football', 'West Indies', 'Mumbai', 'Swimming', 'Rane Laennec', 'Tridax', 'Malaria', 'Taiwan', 'Sahara', 'Mahishmati', 'Gastric', 'Jordan', 'Santoor', 'Che Guevera', 'Pratap Chandra Lal', 'Tractor', 'Aizawl', 'Tetanus', ' I K Gujral', 'Aparna Balan', 'Swami Vivekananda ', 'Vishnu'] option3 = ['Shahid Afridi', 'Dishonest', '7', 'Amritsar', 'Sindhi', 'Badminton', '1972', 'Pakistan', 'Hockey', 'MS Dhoni', 'Hockey', 'Hockey', 'South Africa', 'Delhi', 'Boxing', 'Henry Becquarrel', 'Tephrosia', 'Dermatitis', 'Japan', 'Gobi', 'Kalinga', 'Bypass', 'Saudi Arabia', 'Mridangam', ' Leon Trotsky ', 'Subroto Mukarjee', 'Red Fort', 'darjeeling', 'Japanese Encephalitis', 'Mohd Hidayatullah ', 'Saina Nehwal', 'Rabindranath Tagore ', 'Shiva'] option4 = ['Rohit Sharma', 'Miserly', '8', 'Udhampur', 'English', 'Hockey', '1976', 'Australia', 'Football', 'Zaheer Khan', 'Polo', 'Tennis', 'India', 'Jaipur', 'Running', 'None of these', 'Indigofera', 'Cholera', 'Australia', 'None of these', 'Badami', 'Debridement', 'Qatar', 'Dafli', 'Vladimir Lenin', 'Aspy Engineer', 'Mangalyaan', 'Kohima', 'Plague', 'Zakir Hussain', 'Jwala Gutta', 'Mother Teresa', 'Kamadeva'] options = [option1, option2, option3, option4] # answer keyanswer = [2, 4, 2, 3, 3, 1, 1, 4, 2, 2, 2, 2, 2, 2, 1, 3, 4, 3, 3, 1, 2, 3, 1, 4, 4, 1, 4, 3, 3, 1, 3, 4, 3] wrong = False # correct variable for total correct answercorrect = 0total_amt = 0 # option list for audience pollopt1 = [30, 24, 10, 0, 1, 72, 99, 0, 9, 2, 0, 2, 10, 1, 100, 1, 0, 3, 2, 98, 21, 35, 50, 40, 45, 65, 50, 48, 5, 70, 20, 30, 20] opt2 = [60, 32, 80, 0, 2, 5, 1, 1, 91, 94, 95, 87, 90, 96, 0, 0, 2, 12, 13, 1, 60, 20, 30, 2, 0, 20, 0, 1, 10, 12, 20, 20, 10] opt3 = [2, 4, 0, 100, 97, 0, 0, 1, 0, 2, 5, 11, 0, 3, 0, 99, 2, 82, 82, 0, 18, 40, 10, 4, 1, 10, 0, 50, 70, 15, 35, 10, 64] opt4 = [8, 40, 10, 0, 0, 23, 0, 98, 0, 2, 0, 0, 0, 0, 0, 0, 96, 3, 3, 1, 1, 5, 10, 54, 54, 5, 50, 1, 15, 3, 25, 40, 6] opts = [opt1, opt2, opt3, opt4] condition, ques_no = 1, 0 while(wrong != True): ques_no += 1 ran = random.randint(0, len(questions)-1) print("\n\nQ.", ques_no, ":-", end="") print(questions[ran]) for num, option in enumerate(options): print(str(num+1)+"."+option[ran]) print("Would you like to take lifeline, if yes, press\ 9\n Choose any option: or you can quit by pressing 0 \t\t") give_answer = int(input()) if give_answer == 9: # condition variable is to count lifelines used if condition <= 4: condition += 1 great = lifeline(ran, opts, op) if great == 0: if total_amt < 10000: total_amt = 0 elif total_amt < 320000: total_amt = 10000 elif total_amt < 70000000: total_amt = 320000 break elif great == -1: ques_no -= 1 pass elif great == None: print("Choose any option or press 0 to quit\t") give_ansr = int(input()) if answer[ran] == give_ansr: print("Correct answer, great") correct += 1 elif great == -2: break else: correct += 1 print("You have won Rs=", end="") total_amt = amount(correct) else: print( "You have used your all lifelines\t\n Choose any option: \ or you can quit by pressing 0\t\t") give_ans = int(input()) key = answer[ran] if give_ans == 0: total_amt = amount(correct) break elif key == give_ans: print("Correct, You have won Rs. =", end="") correct += 1 total_amt = amount(correct) else: print("Wrong Answer....") print("Correct Answer is : ", options[answer[ran]-1][ran]) if total_amt < 10000: total_amt = 0 elif total_amt < 320000: total_amt = 10000 elif total_amt < 70000000: total_amt = 32000 wrong = True else: key = answer[ran] if give_answer == 0: if correct != 0: total_amt = amount(correct) break elif key == give_answer: print("Correct answer.., You have won Rs.=", end="") correct += 1 total_amt = amount(correct) else: print("Wrong Answer...Better luck next time...") print("Correct Answer is :", options[answer[ran]-1][ran]) if total_amt < 10000: total_amt = 0 elif total_amt < 320000: total_amt = 10000 elif total_amt < 70000000: total_amt = 320000 wrong = True if correct == 16: # total questions are 16 break # delete previous question and its options from list del questions[ran] del option1[ran] del option2[ran] del option3[ran] del option4[ran] del answer[ran] del opts[0][ran] del opts[1][ran] del opts[2][ran] del opts[3][ran] del op[0][ran] del op[1][ran] del op[2][ran] del op[3][ran] options = [option1, option2, option3, option4] print("Your winning amount is Rs. ", total_amt)
Output:
sooda367
Python-projects
school-programming
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python OOPs Concepts
How to Install PIP on Windows ?
Bar Plot in Matplotlib
Defaultdict in Python
Python Classes and Objects
Deque in Python
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python - Ways to remove duplicates from list
Class method vs Static method in Python | [
{
"code": null,
"e": 23927,
"s": 23899,
"text": "\n27 Jul, 2021"
},
{
"code": null,
"e": 24047,
"s": 23927,
"text": "In this article, we will make a KBC game with almost all the features in CLI(Command Line Interface) mode using Python."
},
{
"code": null,
"e": 24075,
"s": 24047,
"text": "Random questions every time"
},
{
"code": null,
"e": 24135,
"s": 24075,
"text": "Four lifelinesAudience Poll50:50Double dipFlip the question"
},
{
"code": null,
"e": 24149,
"s": 24135,
"text": "Audience Poll"
},
{
"code": null,
"e": 24155,
"s": 24149,
"text": "50:50"
},
{
"code": null,
"e": 24166,
"s": 24155,
"text": "Double dip"
},
{
"code": null,
"e": 24184,
"s": 24166,
"text": "Flip the question"
},
{
"code": null,
"e": 24248,
"s": 24184,
"text": "Made with the help of Matplotlib and NumPy libraries of python."
},
{
"code": null,
"e": 24285,
"s": 24248,
"text": "Bar graph for audience poll lifeline"
},
{
"code": null,
"e": 24385,
"s": 24285,
"text": "There are four lifelines in this game named Audience Poll,50:50, Double dip, and Flip the question."
},
{
"code": null,
"e": 24420,
"s": 24385,
"text": "2 Stages at ₹10,000 and ₹3,20,000."
},
{
"code": null,
"e": 24479,
"s": 24420,
"text": "Users cannot use another lifeline after taking Double Dip."
},
{
"code": null,
"e": 24512,
"s": 24479,
"text": "Lifelines can be used only once."
},
{
"code": null,
"e": 24566,
"s": 24512,
"text": "Quit option is not available after taking Double Dip."
},
{
"code": null,
"e": 24702,
"s": 24566,
"text": "After taking Audience Poll, the user can also take another lifeline except for Double Dip. The same is for 50:50 and Flip the question."
},
{
"code": null,
"e": 24736,
"s": 24702,
"text": "Users can quit from game anytime."
},
{
"code": null,
"e": 24800,
"s": 24736,
"text": "The total winning price will be displayed after every question."
},
{
"code": null,
"e": 24899,
"s": 24800,
"text": "If the user has selected an incorrect option, the amount will be given according to stage cleared."
},
{
"code": null,
"e": 24925,
"s": 24899,
"text": "Create a new python file."
},
{
"code": null,
"e": 24951,
"s": 24925,
"text": "Make a list of questions."
},
{
"code": null,
"e": 25048,
"s": 24951,
"text": "Also make a list of answers, options, fifty-fifty options, audience poll percentage for options."
},
{
"code": null,
"e": 25183,
"s": 25048,
"text": "Implement a random function so that every time when a user plays a game, he/she can get new random questions from a list of questions."
},
{
"code": null,
"e": 25375,
"s": 25183,
"text": "After the question is answered by a user, assure that that question would not appear again. To do this, delete the answered question from the list and associated options within that question."
},
{
"code": null,
"e": 25525,
"s": 25375,
"text": "If the user needs any help then he/she can use a lifeline from the four lifelines i.e, Audience Poll, Fifty-Fifty, Double dip, and Flip the question."
},
{
"code": null,
"e": 25640,
"s": 25525,
"text": "When the user gives the correct answer to the question, the answered question amount is added to the total amount."
},
{
"code": null,
"e": 25685,
"s": 25640,
"text": "Added some questions in a list with options."
},
{
"code": null,
"e": 26614,
"s": 25685,
"text": "Run while loop and check the condition.If true then proceed further. After that display question to the user with options and ask for input(1, 2, 3, 4, or 9 for lifeline and 0 to exit). Random function is used to shuffle the question every time when a user plays the game.If the user is able to give the correct answer then he can choose an option. If the input given is correct then the winning amount is incremented and the next question will be displayed and the previous question is deleted from the list to avoid repetition of questions.If the user’s input is incorrect then he/she will be given the total winning amount. Remember that there are two stages in the game. If the user has given the wrong answer then the amount will be given according to stage cleared.User can quit the game anytime and the current winning amount will be given.If the user fails to choose the correct answer then he/she can take the lifeline."
},
{
"code": null,
"e": 26848,
"s": 26614,
"text": "If true then proceed further. After that display question to the user with options and ask for input(1, 2, 3, 4, or 9 for lifeline and 0 to exit). Random function is used to shuffle the question every time when a user plays the game."
},
{
"code": null,
"e": 27119,
"s": 26848,
"text": "If the user is able to give the correct answer then he can choose an option. If the input given is correct then the winning amount is incremented and the next question will be displayed and the previous question is deleted from the list to avoid repetition of questions."
},
{
"code": null,
"e": 27349,
"s": 27119,
"text": "If the user’s input is incorrect then he/she will be given the total winning amount. Remember that there are two stages in the game. If the user has given the wrong answer then the amount will be given according to stage cleared."
},
{
"code": null,
"e": 27426,
"s": 27349,
"text": "User can quit the game anytime and the current winning amount will be given."
},
{
"code": null,
"e": 27508,
"s": 27426,
"text": "If the user fails to choose the correct answer then he/she can take the lifeline."
},
{
"code": null,
"e": 27516,
"s": 27508,
"text": "Python3"
},
{
"code": "while(wrong != True): ques_no += 1 ran = random.randint(0, len(questions)-1) print(\"\\n\\nQ.\", ques_no, \":-\", end=\"\") print(questions[ran]) for num, option in enumerate(options): print(str(num+1)+\".\"+option[ran]) print(\"Would you like to take lifeline, if yes, press 9\\n\\ Choose any option: or you can quit by pressing 0 \\t\\t\") give_answer = int(input()) if give_answer == 9: # condition variable is to count lifelines # used if condition <= 4: condition += 1 great = lifeline(ran, opts, op) if great == 0: if total_amt < 10000: total_amt = 0 elif total_amt < 320000: total_amt = 10000 elif total_amt < 70000000: total_amt = 320000 break elif great == -1: ques_no -= 1 pass elif great == None: print(\"Choose any option or press 0 to quit\\t\") give_ansr = int(input()) if answer[ran] == give_ansr: print(\"Correct answer, great\") correct += 1 elif great == -2: break else: correct += 1 print(\"You have won Rs=\", end=\"\") total_amt = amount(correct) else: print(\"You have used your all lifelines\\t\\n Choose any option: \\ or you can quit by pressing 0\\t\\t\") give_ans = int(input()) key = answer[ran] if give_ans == 0: total_amt = amount(correct) break elif key == give_ans: print(\"Correct, You have won Rs. =\", end=\"\") correct += 1 total_amt = amount(correct) else: print(\"Wrong Answer....\") print(\"Correct Answer is : \", options[answer[ran]-1][ran]) if total_amt < 10000: total_amt = 0 elif total_amt < 320000: total_amt = 10000 elif total_amt < 70000000: total_amt = 32000 wrong = True else: key = answer[ran] if give_answer == 0: if correct != 0: total_amt = amount(correct) break elif key == give_answer: print(\"Correct answer.., You have won Rs.=\", end=\"\") correct += 1 total_amt = amount(correct) else: print(\"Wrong Answer...Better luck next time...\") print(\"Correct Answer is :\", options[answer[ran]-1][ran]) if total_amt < 10000: total_amt = 0 elif total_amt < 320000: total_amt = 10000 elif total_amt < 70000000: total_amt = 320000 wrong = True # total questions are 16 if correct == 16: break # delete previous question and its options from list del questions[ran] del option1[ran] del option2[ran] del option3[ran] del option4[ran] del answer[ran] del opts[0][ran] del opts[1][ran] del opts[2][ran] del opts[3][ran] del op[0][ran] del op[1][ran] del op[2][ran] del op[3][ran] options = [option1, option2, option3, option4] print(\"Your winning amount is Rs. \", total_amt)",
"e": 30934,
"s": 27516,
"text": null
},
{
"code": null,
"e": 31148,
"s": 30934,
"text": "Audience Poll lifeline:The graph will be shown with the correct percentage assigned to all the options. [For ex: A- 32%, B- 56%, C-2%, D-10%].User can either choose the correct answer or can take another lifeline."
},
{
"code": null,
"e": 31268,
"s": 31148,
"text": "The graph will be shown with the correct percentage assigned to all the options. [For ex: A- 32%, B- 56%, C-2%, D-10%]."
},
{
"code": null,
"e": 31340,
"s": 31268,
"text": "User can either choose the correct answer or can take another lifeline."
},
{
"code": null,
"e": 31348,
"s": 31340,
"text": "Python3"
},
{
"code": "def audience(ran, opts): # graphical audience poll using pandas print(\"According to audience\\n\") s = pd.Series([opt1[ran], opt2[ran], opt3[ran], opt4[ran]], index=['1', '2', '3', '4']) s.plot.bar(figsize=(20, 10)) plt.xlabel('Options') plt.ylabel('%') plt.title(\"Audience Poll\") plt.show() print('1.', opts[0][ran], \"%\", '\\t', '2.', opts[1][ran], \"%\", '\\t', '3.',opts[2][ran], \"%\", '\\t', '4.', opts[3][ran], \"%\", '\\nenter your choice\\t') print(\"Would you like to take lifeline again,if yes then\\ press 9 or Press 0 to Quit\\t\") choice = int(input()) if choice == 9: great = lifeline(ran, opts, op) return great elif choice == answer[ran]: great = 1 print(\"Correct answer,well done!..\") elif choice == 0: great = -2 else: great = 0 print(\"Incorrect\") print(\"Correct Answer is :\", options[answer[ran]-1][ran]) return great",
"e": 32318,
"s": 31348,
"text": null
},
{
"code": null,
"e": 32443,
"s": 32321,
"text": "Fifty-Fifty:Two incorrect options will be deleted.User can either choose the correct answer or can take another lifeline."
},
{
"code": null,
"e": 32482,
"s": 32443,
"text": "Two incorrect options will be deleted."
},
{
"code": null,
"e": 32554,
"s": 32482,
"text": "User can either choose the correct answer or can take another lifeline."
},
{
"code": null,
"e": 32564,
"s": 32556,
"text": "Python3"
},
{
"code": "def fifty(ran, op): print(\"Q.\"+questions[ran]) for num, option in enumerate(op): print(str(num+1)+\".\"+option[ran]) choice_fifty = int(input(\"enter your choice \\t\")) if choice_fifty == answer[ran]: print(\"Correct Answer.....\") great = 1 else: great = 0 print(\"wrong answer\") print(\"Correct Answer is :\", options[answer[ran]-1][ran]) return great",
"e": 32973,
"s": 32564,
"text": null
},
{
"code": null,
"e": 33205,
"s": 32976,
"text": "Double dip:The user will be given two chances to choose the correct option. Remember that after taking double-dip, the user will not able to use any other lifeline. He/she can either choose a correct option or can quit the game."
},
{
"code": null,
"e": 33423,
"s": 33205,
"text": "The user will be given two chances to choose the correct option. Remember that after taking double-dip, the user will not able to use any other lifeline. He/she can either choose a correct option or can quit the game."
},
{
"code": null,
"e": 33433,
"s": 33425,
"text": "Python3"
},
{
"code": "def doubleDip(ran): # double dip gives 2 chances print(\"Select two options\\n\") trial1 = int(input()) if answer[ran] == trial1: great = 1 print(\"Correct Answer,well done....\") else: print(\"Your first trial is wrong, choose another\\t\") trial2 = int(input()) if answer[ran] == trial2: great = 1 print(\"Correct Answer\\t\") else: print(\"Your second trial is also wrong..Better luck next time..\\t\") print(\"Correct Answer is :\", options[answer[ran]-1][ran]) great = 0 return great",
"e": 34025,
"s": 33433,
"text": null
},
{
"code": null,
"e": 34157,
"s": 34028,
"text": "Flip the question:When flip the question lifelines is taken then the current question is skipped and next question is displayed."
},
{
"code": null,
"e": 34268,
"s": 34157,
"text": "When flip the question lifelines is taken then the current question is skipped and next question is displayed."
},
{
"code": null,
"e": 34310,
"s": 34270,
"text": "Given below is the full implementation."
},
{
"code": null,
"e": 34321,
"s": 34312,
"text": "Program:"
},
{
"code": null,
"e": 34331,
"s": 34323,
"text": "Python3"
},
{
"code": "import randomfrom matplotlib import pyplot as pltimport pandas as pd print(\"WELCOME TO KAUN BANEGA CROREPATI...LET'S PLAY\")print(\"Hello\", input(\"Enter Your Name\\t\")) # total prize for each questionamount_won = [1000, 2000, 3000, 5000, 10000, 20000, 40000, 80000, 160000, 320000, 640000, 1250000, 2500000, 5000000, 10000000, 70000000]# Options for 50:50 lifelineop1 = [' ', ' ', ' ', 'Srinagar', ' ', 'Cricket', '1920', ' ', ' ', ' ', ' ', 'Cricket', ' ', 'Kolkata', 'Wrestling', ' ', ' ', ' ', 'China', 'Thar', ' ', ' ', 'Israel', ' ', ' ', 'Arjan Singh', 'Parliament of India', ' ', ' ', 'Mohd Hamid Ansari ', ' ', 'Mahatma Gandhi', 'Hanuman'] op2 = ['AB De Villiers', ' ', '9', ' ', ' ', ' ', '1928', ' ', 'Cricket', 'Yuvraj Singh', 'Cricket', 'Football', 'West Indies', 'Mumbai', 'Swimming', ' ', ' ', ' ', ' ', 'Sahara', 'Mahishmati', ' ', 'Jordan', ' ', 'Che Guevera', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '] op3 = ['Shahid Afridi', 'Dishonest', ' ', 'Amritsar', 'Sindhi', ' ', ' ', 'Pakistan', ' ', 'MS Dhoni', ' ', ' ', 'South Africa', ' ', ' ', 'Henry Becquarrel', 'Tephrosia', 'Dermatitis', 'Japan', ' ', ' ', 'Bypass', ' ', 'Mridangam', ' ', ' ', ' ', 'darjeeling', 'Japanese Encephalitis ', 'Mohd Hidayatullah ', 'Saina Nehwal', ' ', 'Shiva'] op4 = [' ', 'Miserly', '8', ' ', 'English', 'Hockey', ' ', 'Australia', 'Football', ' ', 'Polo', ' ', ' ', ' ', ' ', 'None of these', 'Indigofera', 'Cholera', ' ', ' ', 'Badami', 'Debridement', ' ', 'Dafli', 'Vladimir Lenin', 'Aspy Engineer', 'Mangalyaan', 'Kohima', 'Plague', ' ', 'Jwala Gutta', 'Mother Teresa', ' '] op = [op1, op2, op3, op4] # list of lifelineslist_life = [1, 2, 3, 4] def lifeline(ran, opts, op): m = 1 lifelines = ['Audience Poll', 'Fifty Fifty', 'Double dip', 'Flip the question'] print(\"Lifelines are \\t\", lifelines[0], '\\t', lifelines[1], '\\t', lifelines[2], '\\t', lifelines[3], '\\n\\n') if list_life == []: print(\"You don't have lifelines remaining\\t\") return None print(\"Press 1 for audience,2 for 50:50, 3 for double dip\\ or 4 for flip the question\\t\") while(m != 0): get = int(input()) if get == 1: if get in list_life: m = 0 list_life.remove(1) great = audience(ran, opts) else: print(\"You don't have audience poll\\t\") elif get == 2: if get in list_life: m = 0 great = fifty(ran, op) list_life.remove(2) else: print(\"You don't have 50:50 \\t\") elif get == 3: if get in list_life: m = 0 great = doubleDip(ran) list_life.remove(3) else: print(\"You don't have double dip\\t\") elif get == 4: if get in list_life: m = 0 great = flip() list_life.remove(4) else: print(\"You don't have lifeline to flip the question\\t\") else: print(\"Choose correct option\") return great def audience(ran, opts): # graphical audience poll using pandas print(\"According to audience\\n\") s = pd.Series([opt1[ran], opt2[ran], opt3[ran], opt4[ran]], index=['1', '2', '3', '4']) s.plot.bar(figsize=(20, 10)) plt.xlabel('Options') plt.ylabel('%') plt.title(\"Audience Poll\") plt.show() print('1.', opts[0][ran], \"%\", '\\t', '2.', opts[1][ran], \"%\", '\\t', '3.', opts[2][ran], \"%\", '\\t', '4.', opts[3][ran], \"%\", '\\nenter your choice\\t') print(\"Would you like to take lifeline again,if yes then press\\ 9 or Press 0 to Quit\\t\") choice = int(input()) if choice == 9: great = lifeline(ran, opts, op) return great elif choice == answer[ran]: great = 1 print(\"Correct answer,well done!..\") elif choice == 0: great = -2 else: great = 0 print(\"Incorrect\") print(\"Correct Answer is :\", options[answer[ran]-1][ran]) return great def fifty(ran, op): print(\"Q.\"+questions[ran]) for num, option in enumerate(op): print(str(num+1)+\".\"+option[ran]) choice_fifty = int(input(\"enter your choice \\t\")) if choice_fifty == answer[ran]: print(\"Correct Answer.....\") great = 1 else: great = 0 print(\"wrong answer\") print(\"Correct Answer is :\", options[answer[ran]-1][ran]) return great def doubleDip(ran): # double dip gives 2 chances print(\"Select two options\\n\") trial1 = int(input()) if answer[ran] == trial1: great = 1 print(\"Correct Answer,well done....\") else: print(\"Your first trial is wrong, choose another\\t\") trial2 = int(input()) if answer[ran] == trial2: great = 1 print(\"Correct Answer\\t\") else: print(\"Your second trial is also wrong..Better luck next time..\\t\") print(\"Correct Answer is :\", options[answer[ran]-1][ran]) great = 0 return great def flip(): return -1 def amount(correct_ans): print(amount_won[correct_ans-1]) if amount_won[correct_ans-1] == 10000: print(\"Completed 1st stage\") elif amount_won[correct_ans-1] == 320000: print(\"Completed 2st stage\") elif amount_won[correct_ans-1] == 70000000: print(\"You have won Rs 7 CRORE\") return amount_won[correct_ans-1] questions = [ 'In ODI Cricket, who created the record of scoring the \\ fastest century in just 31 balls ?', ' If you call someone ‘Makkhichoos’ then what are you \\ calling him ?', 'How many players of a Kho-Kho team can play on the field\\ during the match ?', 'Which of these Indian cities is closest to the Pakistani \\ city of Lahore ?', 'The language spoken by the people by Pakistan is ?', 'The term“Googly” is associated with ?', 'India first took part in the olympic games in the year ?', 'Who are Kangaroos ?', 'Oval stadium in England is associated with ?', 'In 2011 India won the World Cup. Who was adjudicated as the\\ man of the series in the tournament ? ', 'Eden Gardens in Kolkata is ----- stadium.? ', 'Ronaldo is associated with ? ', 'Icc’s 2007, the World Cup Cricket was held in ? ', 'Wankhede Stadium is at ? ', 'World’s most ancient game is ? ', 'Stethoscope was invented by ?', 'A dye is prepared from ', 'Which disease is caused by the fungi? ', 'Which is the Land of the Rising Sun? ', 'The desert that lies on the boundary between India and Pakistan \\ is ', ' In which kingdom is the story of the ‘Bahubali’ series of films\\ mainly set?', 'What is the common name for surgery conducted on coronary arteries\\ that supply blood to the heart ?', ' In July 2017, Narendra Modi Become the first Indian Prime Minister\\ to visit which country ?', 'Which of these musical instrument is held in one hand and played with\\ the other ?', ' On the last day of his life Bhagat Singh was reading a book about\\ the Ideology of which revolutionary ?', 'Which Air force officer had the unique honour of leading the fly-post\\ over the Red fort in Delhi on 15 August 1947 ?', 'Which image appears on the flip side of the new 2000 Rs Note, launched\\ in 2016?', 'Which Indian hill station gets its name from the Tibetan words that mean\\ ‘land of the thunderbolt’?', 'Which of these diseases is transmitted by mosquitoes?', 'Who among these has served as the Ambassador of India to the United Nations?', ' Who was the first Indian to win the World Junior Badminton Championships?', 'Which of the following is a recipient of the Nobel Peace Prize?', 'The cave temples at the historical site of Elephanta are dedicated to which\\ God?'] option1 = ['Corey Anderson', 'Evil', '10', 'Srinagar', 'Hindi', 'Cricket', '1920', 'Bangladesh', 'polo', 'Virat Kohli', 'Tennis', 'Cricket', 'Australia', 'Kolkata', 'Wrestling', 'Bessemer', 'Sida', 'Polio', 'China', 'Thar', 'Magadh', 'Cataract', 'Israel', 'Tabla', 'Antonio Gramsci ', 'Arjan Singh', 'Parliament of India', 'Gangtok', 'Rabies', ' Mohd Hamid Ansari', 'P V Sindhu', 'Mahatma Gandhi', 'Hanuman'] option2 = ['AB De Villiers', 'Humble', '9', 'Jaisalmer', 'Palauan', 'Football', '1928', 'Kenya', 'Cricket', 'Yuvraj Singh', 'Cricket', 'Football', 'West Indies', 'Mumbai', 'Swimming', 'Rane Laennec', 'Tridax', 'Malaria', 'Taiwan', 'Sahara', 'Mahishmati', 'Gastric', 'Jordan', 'Santoor', 'Che Guevera', 'Pratap Chandra Lal', 'Tractor', 'Aizawl', 'Tetanus', ' I K Gujral', 'Aparna Balan', 'Swami Vivekananda ', 'Vishnu'] option3 = ['Shahid Afridi', 'Dishonest', '7', 'Amritsar', 'Sindhi', 'Badminton', '1972', 'Pakistan', 'Hockey', 'MS Dhoni', 'Hockey', 'Hockey', 'South Africa', 'Delhi', 'Boxing', 'Henry Becquarrel', 'Tephrosia', 'Dermatitis', 'Japan', 'Gobi', 'Kalinga', 'Bypass', 'Saudi Arabia', 'Mridangam', ' Leon Trotsky ', 'Subroto Mukarjee', 'Red Fort', 'darjeeling', 'Japanese Encephalitis', 'Mohd Hidayatullah ', 'Saina Nehwal', 'Rabindranath Tagore ', 'Shiva'] option4 = ['Rohit Sharma', 'Miserly', '8', 'Udhampur', 'English', 'Hockey', '1976', 'Australia', 'Football', 'Zaheer Khan', 'Polo', 'Tennis', 'India', 'Jaipur', 'Running', 'None of these', 'Indigofera', 'Cholera', 'Australia', 'None of these', 'Badami', 'Debridement', 'Qatar', 'Dafli', 'Vladimir Lenin', 'Aspy Engineer', 'Mangalyaan', 'Kohima', 'Plague', 'Zakir Hussain', 'Jwala Gutta', 'Mother Teresa', 'Kamadeva'] options = [option1, option2, option3, option4] # answer keyanswer = [2, 4, 2, 3, 3, 1, 1, 4, 2, 2, 2, 2, 2, 2, 1, 3, 4, 3, 3, 1, 2, 3, 1, 4, 4, 1, 4, 3, 3, 1, 3, 4, 3] wrong = False # correct variable for total correct answercorrect = 0total_amt = 0 # option list for audience pollopt1 = [30, 24, 10, 0, 1, 72, 99, 0, 9, 2, 0, 2, 10, 1, 100, 1, 0, 3, 2, 98, 21, 35, 50, 40, 45, 65, 50, 48, 5, 70, 20, 30, 20] opt2 = [60, 32, 80, 0, 2, 5, 1, 1, 91, 94, 95, 87, 90, 96, 0, 0, 2, 12, 13, 1, 60, 20, 30, 2, 0, 20, 0, 1, 10, 12, 20, 20, 10] opt3 = [2, 4, 0, 100, 97, 0, 0, 1, 0, 2, 5, 11, 0, 3, 0, 99, 2, 82, 82, 0, 18, 40, 10, 4, 1, 10, 0, 50, 70, 15, 35, 10, 64] opt4 = [8, 40, 10, 0, 0, 23, 0, 98, 0, 2, 0, 0, 0, 0, 0, 0, 96, 3, 3, 1, 1, 5, 10, 54, 54, 5, 50, 1, 15, 3, 25, 40, 6] opts = [opt1, opt2, opt3, opt4] condition, ques_no = 1, 0 while(wrong != True): ques_no += 1 ran = random.randint(0, len(questions)-1) print(\"\\n\\nQ.\", ques_no, \":-\", end=\"\") print(questions[ran]) for num, option in enumerate(options): print(str(num+1)+\".\"+option[ran]) print(\"Would you like to take lifeline, if yes, press\\ 9\\n Choose any option: or you can quit by pressing 0 \\t\\t\") give_answer = int(input()) if give_answer == 9: # condition variable is to count lifelines used if condition <= 4: condition += 1 great = lifeline(ran, opts, op) if great == 0: if total_amt < 10000: total_amt = 0 elif total_amt < 320000: total_amt = 10000 elif total_amt < 70000000: total_amt = 320000 break elif great == -1: ques_no -= 1 pass elif great == None: print(\"Choose any option or press 0 to quit\\t\") give_ansr = int(input()) if answer[ran] == give_ansr: print(\"Correct answer, great\") correct += 1 elif great == -2: break else: correct += 1 print(\"You have won Rs=\", end=\"\") total_amt = amount(correct) else: print( \"You have used your all lifelines\\t\\n Choose any option: \\ or you can quit by pressing 0\\t\\t\") give_ans = int(input()) key = answer[ran] if give_ans == 0: total_amt = amount(correct) break elif key == give_ans: print(\"Correct, You have won Rs. =\", end=\"\") correct += 1 total_amt = amount(correct) else: print(\"Wrong Answer....\") print(\"Correct Answer is : \", options[answer[ran]-1][ran]) if total_amt < 10000: total_amt = 0 elif total_amt < 320000: total_amt = 10000 elif total_amt < 70000000: total_amt = 32000 wrong = True else: key = answer[ran] if give_answer == 0: if correct != 0: total_amt = amount(correct) break elif key == give_answer: print(\"Correct answer.., You have won Rs.=\", end=\"\") correct += 1 total_amt = amount(correct) else: print(\"Wrong Answer...Better luck next time...\") print(\"Correct Answer is :\", options[answer[ran]-1][ran]) if total_amt < 10000: total_amt = 0 elif total_amt < 320000: total_amt = 10000 elif total_amt < 70000000: total_amt = 320000 wrong = True if correct == 16: # total questions are 16 break # delete previous question and its options from list del questions[ran] del option1[ran] del option2[ran] del option3[ran] del option4[ran] del answer[ran] del opts[0][ran] del opts[1][ran] del opts[2][ran] del opts[3][ran] del op[0][ran] del op[1][ran] del op[2][ran] del op[3][ran] options = [option1, option2, option3, option4] print(\"Your winning amount is Rs. \", total_amt)",
"e": 49192,
"s": 34331,
"text": null
},
{
"code": null,
"e": 49200,
"s": 49192,
"text": "Output:"
},
{
"code": null,
"e": 49209,
"s": 49200,
"text": "sooda367"
},
{
"code": null,
"e": 49225,
"s": 49209,
"text": "Python-projects"
},
{
"code": null,
"e": 49244,
"s": 49225,
"text": "school-programming"
},
{
"code": null,
"e": 49251,
"s": 49244,
"text": "Python"
},
{
"code": null,
"e": 49349,
"s": 49251,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 49358,
"s": 49349,
"text": "Comments"
},
{
"code": null,
"e": 49371,
"s": 49358,
"text": "Old Comments"
},
{
"code": null,
"e": 49392,
"s": 49371,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 49424,
"s": 49392,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 49447,
"s": 49424,
"text": "Bar Plot in Matplotlib"
},
{
"code": null,
"e": 49469,
"s": 49447,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 49496,
"s": 49469,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 49512,
"s": 49496,
"text": "Deque in Python"
},
{
"code": null,
"e": 49554,
"s": 49512,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 49610,
"s": 49554,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 49655,
"s": 49610,
"text": "Python - Ways to remove duplicates from list"
}
] |
PHP - empty() Function | The empty() function checks whether a variable is empty.
bool empty ( mixed $var )
var
Variable to be checked.
*mixed: mixed indicates that a parameter may accept multiple (but not necessarily all) types
This function returns −
true − if the variable is empty
true − if the variable is empty
false − if variable exists or has a non-empty or non-zero value
false − if variable exists or has a non-empty or non-zero value
The following values evaluates to empty −
integer − if value is 0 then empty() returns true. For any other value returns false.
integer − if value is 0 then empty() returns true. For any other value returns false.
float − if value is 0.0 then empty() returns true. For any other value returns false.
float − if value is 0.0 then empty() returns true. For any other value returns false.
string − if string value is "0" and null ("") then empty() returns true. For any other value returns false (even "0.0").
string − if string value is "0" and null ("") then empty() returns true. For any other value returns false (even "0.0").
array − if value is empty array() then boolval() returns true. For any other value returns false.
array − if value is empty array() then boolval() returns true. For any other value returns false.
NULL − empty() always returns false when variable is NULL.
NULL − empty() always returns false when variable is NULL.
Boolean − if boolean variable is FALSE then empty() returns true.
Boolean − if boolean variable is FALSE then empty() returns true.
PHP 4.0 and above. Prior to PHP 5.5, empty() only supports variables; anything else will result in a parse error.
Following example demonstrates return values with different types of variables −
<?php
// PHP program demo for empty() function
echo 'when var is 0 function empty() returns <b>'.( empty( 0 )? 'true' : 'false').'</b>';
echo 'when var is "0.0" function empty() returns <b>'.( empty( "0.0" )? 'true' : 'false').'</b>';
echo 'when var is "0" function empty() returns <b>'.( empty( "0" )? 'true' : 'false').'</b>';
echo 'when var is "" function empty() returns <b>'.( empty( "" )? 'true' : 'false').'</b>';
echo 'when var is [] function empty() returns <b>'.( empty( [] )? 'true' : 'false').'</b>';
echo 'when var is NULL function empty() returns <b>'.( empty( NULL )? 'true' : 'false').'</b>';
echo 'when var is FALSE function empty() returns <b>'.( empty( FALSE )? 'true' : 'false').'</b>';
?>
This will produce following result −
when var is 0 function empty() returns true
when var is "0.0" function empty() returns false
when var is "0" function empty() returns true
when var is "" function empty() returns true
when var is [] function empty() returns true
when var is NULL function empty() returns true
when var is FALSE function empty() returns true
45 Lectures
9 hours
Malhar Lathkar
34 Lectures
4 hours
Syed Raza
84 Lectures
5.5 hours
Frahaan Hussain
17 Lectures
1 hours
Nivedita Jain
100 Lectures
34 hours
Azaz Patel
43 Lectures
5.5 hours
Vijay Kumar Parvatha Reddy
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2814,
"s": 2757,
"text": "The empty() function checks whether a variable is empty."
},
{
"code": null,
"e": 2841,
"s": 2814,
"text": "bool empty ( mixed $var )\n"
},
{
"code": null,
"e": 2845,
"s": 2841,
"text": "var"
},
{
"code": null,
"e": 2869,
"s": 2845,
"text": "Variable to be checked."
},
{
"code": null,
"e": 2962,
"s": 2869,
"text": "*mixed: mixed indicates that a parameter may accept multiple (but not necessarily all) types"
},
{
"code": null,
"e": 2986,
"s": 2962,
"text": "This function returns −"
},
{
"code": null,
"e": 3018,
"s": 2986,
"text": "true − if the variable is empty"
},
{
"code": null,
"e": 3050,
"s": 3018,
"text": "true − if the variable is empty"
},
{
"code": null,
"e": 3114,
"s": 3050,
"text": "false − if variable exists or has a non-empty or non-zero value"
},
{
"code": null,
"e": 3178,
"s": 3114,
"text": "false − if variable exists or has a non-empty or non-zero value"
},
{
"code": null,
"e": 3220,
"s": 3178,
"text": "The following values evaluates to empty −"
},
{
"code": null,
"e": 3306,
"s": 3220,
"text": "integer − if value is 0 then empty() returns true. For any other value returns false."
},
{
"code": null,
"e": 3392,
"s": 3306,
"text": "integer − if value is 0 then empty() returns true. For any other value returns false."
},
{
"code": null,
"e": 3478,
"s": 3392,
"text": "float − if value is 0.0 then empty() returns true. For any other value returns false."
},
{
"code": null,
"e": 3564,
"s": 3478,
"text": "float − if value is 0.0 then empty() returns true. For any other value returns false."
},
{
"code": null,
"e": 3685,
"s": 3564,
"text": "string − if string value is \"0\" and null (\"\") then empty() returns true. For any other value returns false (even \"0.0\")."
},
{
"code": null,
"e": 3806,
"s": 3685,
"text": "string − if string value is \"0\" and null (\"\") then empty() returns true. For any other value returns false (even \"0.0\")."
},
{
"code": null,
"e": 3904,
"s": 3806,
"text": "array − if value is empty array() then boolval() returns true. For any other value returns false."
},
{
"code": null,
"e": 4002,
"s": 3904,
"text": "array − if value is empty array() then boolval() returns true. For any other value returns false."
},
{
"code": null,
"e": 4061,
"s": 4002,
"text": "NULL − empty() always returns false when variable is NULL."
},
{
"code": null,
"e": 4120,
"s": 4061,
"text": "NULL − empty() always returns false when variable is NULL."
},
{
"code": null,
"e": 4186,
"s": 4120,
"text": "Boolean − if boolean variable is FALSE then empty() returns true."
},
{
"code": null,
"e": 4252,
"s": 4186,
"text": "Boolean − if boolean variable is FALSE then empty() returns true."
},
{
"code": null,
"e": 4366,
"s": 4252,
"text": "PHP 4.0 and above. Prior to PHP 5.5, empty() only supports variables; anything else will result in a parse error."
},
{
"code": null,
"e": 4447,
"s": 4366,
"text": "Following example demonstrates return values with different types of variables −"
},
{
"code": null,
"e": 5182,
"s": 4447,
"text": "<?php\n // PHP program demo for empty() function\n\n echo 'when var is 0 function empty() returns <b>'.( empty( 0 )? 'true' : 'false').'</b>';\n echo 'when var is \"0.0\" function empty() returns <b>'.( empty( \"0.0\" )? 'true' : 'false').'</b>';\n echo 'when var is \"0\" function empty() returns <b>'.( empty( \"0\" )? 'true' : 'false').'</b>';\n echo 'when var is \"\" function empty() returns <b>'.( empty( \"\" )? 'true' : 'false').'</b>';\n echo 'when var is [] function empty() returns <b>'.( empty( [] )? 'true' : 'false').'</b>';\n echo 'when var is NULL function empty() returns <b>'.( empty( NULL )? 'true' : 'false').'</b>';\n echo 'when var is FALSE function empty() returns <b>'.( empty( FALSE )? 'true' : 'false').'</b>';\n?>"
},
{
"code": null,
"e": 5219,
"s": 5182,
"text": "This will produce following result −"
},
{
"code": null,
"e": 5544,
"s": 5219,
"text": "when var is 0 function empty() returns true\nwhen var is \"0.0\" function empty() returns false\nwhen var is \"0\" function empty() returns true\nwhen var is \"\" function empty() returns true\nwhen var is [] function empty() returns true\nwhen var is NULL function empty() returns true\nwhen var is FALSE function empty() returns true\n"
},
{
"code": null,
"e": 5577,
"s": 5544,
"text": "\n 45 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 5593,
"s": 5577,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 5626,
"s": 5593,
"text": "\n 34 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 5637,
"s": 5626,
"text": " Syed Raza"
},
{
"code": null,
"e": 5672,
"s": 5637,
"text": "\n 84 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 5689,
"s": 5672,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 5722,
"s": 5689,
"text": "\n 17 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5737,
"s": 5722,
"text": " Nivedita Jain"
},
{
"code": null,
"e": 5772,
"s": 5737,
"text": "\n 100 Lectures \n 34 hours \n"
},
{
"code": null,
"e": 5784,
"s": 5772,
"text": " Azaz Patel"
},
{
"code": null,
"e": 5819,
"s": 5784,
"text": "\n 43 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 5847,
"s": 5819,
"text": " Vijay Kumar Parvatha Reddy"
},
{
"code": null,
"e": 5854,
"s": 5847,
"text": " Print"
},
{
"code": null,
"e": 5865,
"s": 5854,
"text": " Add Notes"
}
] |
A Group chat application in Java - GeeksforGeeks | 21 Nov, 2018
In this post, a group chat application using MulticastSocket (Java Platform SE 7) class is discussed. A MulticastSocket is a (UDP) DatagramSocket, with additional capabilities for joining “groups” of other multicast hosts on the internet.
Implementation
import java.net.*;import java.io.*;import java.util.*;public class GroupChat{ private static final String TERMINATE = "Exit"; static String name; static volatile boolean finished = false; public static void main(String[] args) { if (args.length != 2) System.out.println("Two arguments required: <multicast-host> <port-number>"); else { try { InetAddress group = InetAddress.getByName(args[0]); int port = Integer.parseInt(args[1]); Scanner sc = new Scanner(System.in); System.out.print("Enter your name: "); name = sc.nextLine(); MulticastSocket socket = new MulticastSocket(port); // Since we are deploying socket.setTimeToLive(0); //this on localhost only (For a subnet set it as 1) socket.joinGroup(group); Thread t = new Thread(new ReadThread(socket,group,port)); // Spawn a thread for reading messages t.start(); // sent to the current group System.out.println("Start typing messages...\n"); while(true) { String message; message = sc.nextLine(); if(message.equalsIgnoreCase(GroupChat.TERMINATE)) { finished = true; socket.leaveGroup(group); socket.close(); break; } message = name + ": " + message; byte[] buffer = message.getBytes(); DatagramPacket datagram = new DatagramPacket(buffer,buffer.length,group,port); socket.send(datagram); } } catch(SocketException se) { System.out.println("Error creating socket"); se.printStackTrace(); } catch(IOException ie) { System.out.println("Error reading/writing from/to socket"); ie.printStackTrace(); } } }}class ReadThread implements Runnable{ private MulticastSocket socket; private InetAddress group; private int port; private static final int MAX_LEN = 1000; ReadThread(MulticastSocket socket,InetAddress group,int port) { this.socket = socket; this.group = group; this.port = port; } @Override public void run() { while(!GroupChat.finished) { byte[] buffer = new byte[ReadThread.MAX_LEN]; DatagramPacket datagram = new DatagramPacket(buffer,buffer.length,group,port); String message; try { socket.receive(datagram); message = new String(buffer,0,datagram.getLength(),"UTF-8"); if(!message.startsWith(GroupChat.name)) System.out.println(message); } catch(IOException e) { System.out.println("Socket closed!"); } } }}
Save the file as GroupChat.java and compile it using javac and then run the program using two command line arguments as specified. A multicast host is specified by a class D IP address and by a standard UDP port number. Class D IP addresses are in the range 224.0.0.0 to 239.255.255.255, inclusive. The address 224.0.0.0 is reserved and should not be used.Here is a sample output of the above program:
We have used the multicast host IP address as 239.0.0.0 and the port number as 1234 (since the port numbers 0 through 1023 are reserved). There are 3 members in the group: Ironman, CaptainAmerica, and Groot. Start all three terminals first before sending the message, otherwise messages which are sent before starting the terminal are lost (since there is no facility of buffer incorporated to store the messages.) We need two threads in this application. One for accepting the user input (using the java.util.Scanner class) and the other for reading the messages sent from other clients. Hence I have separated the thread which does the reading work into ReadThreadclass. For leaving the group, any of the user can type in Exit to terminate the session.
The above program is executed on a single machine. Socket programming is meant for distributed programming. The same piece of code snippet when present on different machines which have Java installed can satisfy that requirement. This is just the bare bones service logic. The project would be even more fascinating if the front-end is developed. You can use Java’s AWT (Abstract Window Toolkit) or its advanced counterpart, Java Swing to develop the front end. Since this wouldn’t be part of Socket programming I’m leaving it untouched without getting into the details.Additional points:
You can incorporate network security feature by performing encryption before sending the message over the network.
Primitive techniques such as Caesar cipher or advanced methods such as RSA can be used to perform encryption-decryption. You can try using Java’s RMI (Remote Method Invocation) to perform the same task.
Here, you can leverage the abstraction offered by Java to maximum extent. However, if your primary objective is efficiency, then Socket programming is the best choice. Since it doesn’t require any run time support, it is a bit faster compared to RMI.
This article is contributed by Aditya ch. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.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.
AsaduzzamanAnik
GBlog
Java
Project
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Roadmap to Become a Web Developer in 2022
DSA Sheet by Love Babbar
Top 10 Angular Libraries For Web Developers
A Freshers Guide To Programming
Supervised and Unsupervised learning
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Reverse a string in Java
HashMap in Java with Examples | [
{
"code": null,
"e": 24710,
"s": 24682,
"text": "\n21 Nov, 2018"
},
{
"code": null,
"e": 24949,
"s": 24710,
"text": "In this post, a group chat application using MulticastSocket (Java Platform SE 7) class is discussed. A MulticastSocket is a (UDP) DatagramSocket, with additional capabilities for joining “groups” of other multicast hosts on the internet."
},
{
"code": null,
"e": 24964,
"s": 24949,
"text": "Implementation"
},
{
"code": "import java.net.*;import java.io.*;import java.util.*;public class GroupChat{ private static final String TERMINATE = \"Exit\"; static String name; static volatile boolean finished = false; public static void main(String[] args) { if (args.length != 2) System.out.println(\"Two arguments required: <multicast-host> <port-number>\"); else { try { InetAddress group = InetAddress.getByName(args[0]); int port = Integer.parseInt(args[1]); Scanner sc = new Scanner(System.in); System.out.print(\"Enter your name: \"); name = sc.nextLine(); MulticastSocket socket = new MulticastSocket(port); // Since we are deploying socket.setTimeToLive(0); //this on localhost only (For a subnet set it as 1) socket.joinGroup(group); Thread t = new Thread(new ReadThread(socket,group,port)); // Spawn a thread for reading messages t.start(); // sent to the current group System.out.println(\"Start typing messages...\\n\"); while(true) { String message; message = sc.nextLine(); if(message.equalsIgnoreCase(GroupChat.TERMINATE)) { finished = true; socket.leaveGroup(group); socket.close(); break; } message = name + \": \" + message; byte[] buffer = message.getBytes(); DatagramPacket datagram = new DatagramPacket(buffer,buffer.length,group,port); socket.send(datagram); } } catch(SocketException se) { System.out.println(\"Error creating socket\"); se.printStackTrace(); } catch(IOException ie) { System.out.println(\"Error reading/writing from/to socket\"); ie.printStackTrace(); } } }}class ReadThread implements Runnable{ private MulticastSocket socket; private InetAddress group; private int port; private static final int MAX_LEN = 1000; ReadThread(MulticastSocket socket,InetAddress group,int port) { this.socket = socket; this.group = group; this.port = port; } @Override public void run() { while(!GroupChat.finished) { byte[] buffer = new byte[ReadThread.MAX_LEN]; DatagramPacket datagram = new DatagramPacket(buffer,buffer.length,group,port); String message; try { socket.receive(datagram); message = new String(buffer,0,datagram.getLength(),\"UTF-8\"); if(!message.startsWith(GroupChat.name)) System.out.println(message); } catch(IOException e) { System.out.println(\"Socket closed!\"); } } }}",
"e": 28283,
"s": 24964,
"text": null
},
{
"code": null,
"e": 28685,
"s": 28283,
"text": "Save the file as GroupChat.java and compile it using javac and then run the program using two command line arguments as specified. A multicast host is specified by a class D IP address and by a standard UDP port number. Class D IP addresses are in the range 224.0.0.0 to 239.255.255.255, inclusive. The address 224.0.0.0 is reserved and should not be used.Here is a sample output of the above program:"
},
{
"code": null,
"e": 29440,
"s": 28685,
"text": "We have used the multicast host IP address as 239.0.0.0 and the port number as 1234 (since the port numbers 0 through 1023 are reserved). There are 3 members in the group: Ironman, CaptainAmerica, and Groot. Start all three terminals first before sending the message, otherwise messages which are sent before starting the terminal are lost (since there is no facility of buffer incorporated to store the messages.) We need two threads in this application. One for accepting the user input (using the java.util.Scanner class) and the other for reading the messages sent from other clients. Hence I have separated the thread which does the reading work into ReadThreadclass. For leaving the group, any of the user can type in Exit to terminate the session."
},
{
"code": null,
"e": 30029,
"s": 29440,
"text": "The above program is executed on a single machine. Socket programming is meant for distributed programming. The same piece of code snippet when present on different machines which have Java installed can satisfy that requirement. This is just the bare bones service logic. The project would be even more fascinating if the front-end is developed. You can use Java’s AWT (Abstract Window Toolkit) or its advanced counterpart, Java Swing to develop the front end. Since this wouldn’t be part of Socket programming I’m leaving it untouched without getting into the details.Additional points:"
},
{
"code": null,
"e": 30144,
"s": 30029,
"text": "You can incorporate network security feature by performing encryption before sending the message over the network."
},
{
"code": null,
"e": 30347,
"s": 30144,
"text": "Primitive techniques such as Caesar cipher or advanced methods such as RSA can be used to perform encryption-decryption. You can try using Java’s RMI (Remote Method Invocation) to perform the same task."
},
{
"code": null,
"e": 30598,
"s": 30347,
"text": "Here, you can leverage the abstraction offered by Java to maximum extent. However, if your primary objective is efficiency, then Socket programming is the best choice. Since it doesn’t require any run time support, it is a bit faster compared to RMI."
},
{
"code": null,
"e": 30895,
"s": 30598,
"text": "This article is contributed by Aditya ch. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.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": 31020,
"s": 30895,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 31036,
"s": 31020,
"text": "AsaduzzamanAnik"
},
{
"code": null,
"e": 31042,
"s": 31036,
"text": "GBlog"
},
{
"code": null,
"e": 31047,
"s": 31042,
"text": "Java"
},
{
"code": null,
"e": 31055,
"s": 31047,
"text": "Project"
},
{
"code": null,
"e": 31060,
"s": 31055,
"text": "Java"
},
{
"code": null,
"e": 31158,
"s": 31060,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31167,
"s": 31158,
"text": "Comments"
},
{
"code": null,
"e": 31180,
"s": 31167,
"text": "Old Comments"
},
{
"code": null,
"e": 31222,
"s": 31180,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 31247,
"s": 31222,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 31291,
"s": 31247,
"text": "Top 10 Angular Libraries For Web Developers"
},
{
"code": null,
"e": 31323,
"s": 31291,
"text": "A Freshers Guide To Programming"
},
{
"code": null,
"e": 31360,
"s": 31323,
"text": "Supervised and Unsupervised learning"
},
{
"code": null,
"e": 31375,
"s": 31360,
"text": "Arrays in Java"
},
{
"code": null,
"e": 31419,
"s": 31375,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 31441,
"s": 31419,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 31466,
"s": 31441,
"text": "Reverse a string in Java"
}
] |
How to sort an HTML list using JavaScript? | To sort an HTML list using JavaScript, the code is as follows −
Live Demo
<!DOCTYPE html>
<html>
<body>
<h1>Sorting list example</h1>
<button>Click to sort</button>
<ul class="animalList">
<li>Giraffe</li>
<li>Camel</li>
<li>Dog</li>
<li>Lion</li>
<li>Cheetah</li>
<li>Cat</li>
</ul>
<script>
document .getElementsByTagName("button")[0] .addEventListener("click", sortList);
function sortList() {
var list, i, sortFlag, LiEle, sorted;
list = document.querySelector(".animalList");
sortFlag = true;
while (sortFlag) {
sortFlag = false;
LiEle = list.getElementsByTagName("LI");
for (i = 0; i < LiEle.length - 1; i++) {
sorted = false;
if ( LiEle[i].innerHTML.toLowerCase() > LiEle[i + 1].innerHTML.toLowerCase() ) {
sorted = true;
break;
}
}
if (sorted) {
LiEle[i].parentNode.insertBefore(LiEle[i + 1], LiEle[i]);
sortFlag = true;
}
}
}
</script>
</body>
</html>
The above code will produce the following output −
On clicking the “Click to sort” button − | [
{
"code": null,
"e": 1126,
"s": 1062,
"text": "To sort an HTML list using JavaScript, the code is as follows −"
},
{
"code": null,
"e": 1137,
"s": 1126,
"text": " Live Demo"
},
{
"code": null,
"e": 2107,
"s": 1137,
"text": "<!DOCTYPE html>\n<html>\n<body>\n<h1>Sorting list example</h1>\n<button>Click to sort</button>\n<ul class=\"animalList\">\n<li>Giraffe</li>\n<li>Camel</li>\n<li>Dog</li>\n<li>Lion</li>\n<li>Cheetah</li>\n<li>Cat</li>\n</ul>\n<script>\n document .getElementsByTagName(\"button\")[0] .addEventListener(\"click\", sortList);\n function sortList() {\n var list, i, sortFlag, LiEle, sorted;\n list = document.querySelector(\".animalList\");\n sortFlag = true;\n while (sortFlag) {\n sortFlag = false;\n LiEle = list.getElementsByTagName(\"LI\");\n for (i = 0; i < LiEle.length - 1; i++) {\n sorted = false;\n if ( LiEle[i].innerHTML.toLowerCase() > LiEle[i + 1].innerHTML.toLowerCase() ) {\n sorted = true;\n break;\n }\n }\n if (sorted) {\n LiEle[i].parentNode.insertBefore(LiEle[i + 1], LiEle[i]);\n sortFlag = true;\n }\n }\n }\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 2158,
"s": 2107,
"text": "The above code will produce the following output −"
},
{
"code": null,
"e": 2199,
"s": 2158,
"text": "On clicking the “Click to sort” button −"
}
] |
Are values returned by static method are static in java? | Whenever you return values from a static method they are either static nor instance by default, they are just values.
The user invoking the method can use them as he wants. i.e. you can retrieve the values and declare them static.
But, since you cannot declare variables of a method static if you need to declare the vales returned by a method static you need to invoke it in the class outside the methods.
Assume we have a class with name Demo as −
class Demo{
int data = 20;
public Demo(int data){
this.data = data;
}
public int getData(){
return this.data;
}
}
In the following Java example, we have two methods getObject() and getInt() returning an object and an integer respectively.
We are invoking these methods twice in the class and within a method. In the class we have declared the values returned by them as static.
And in the method we are using them (values returned by the methods) as local variables (obviously non-static).
public class StaticExample{
static int data = StaticExample.getInt();
static Demo obj = StaticExample.getObject();
public static Demo getObject(){
Demo obj = new Demo(300);
return obj;
}
public static int getInt(){
return 20;
}
public static void main(String args[]) {
System.out.println(StaticExample.data);
System.out.println(StaticExample.obj.data);
StaticExample obj = new StaticExample();
System.out.println(obj.getInt());
Demo demo = obj.getObject();
System.out.println(demo.data);
}
}
20
300
20
300 | [
{
"code": null,
"e": 1180,
"s": 1062,
"text": "Whenever you return values from a static method they are either static nor instance by default, they are just values."
},
{
"code": null,
"e": 1293,
"s": 1180,
"text": "The user invoking the method can use them as he wants. i.e. you can retrieve the values and declare them static."
},
{
"code": null,
"e": 1469,
"s": 1293,
"text": "But, since you cannot declare variables of a method static if you need to declare the vales returned by a method static you need to invoke it in the class outside the methods."
},
{
"code": null,
"e": 1512,
"s": 1469,
"text": "Assume we have a class with name Demo as −"
},
{
"code": null,
"e": 1653,
"s": 1512,
"text": "class Demo{\n int data = 20;\n public Demo(int data){\n this.data = data;\n }\n public int getData(){\n return this.data;\n }\n}"
},
{
"code": null,
"e": 1778,
"s": 1653,
"text": "In the following Java example, we have two methods getObject() and getInt() returning an object and an integer respectively."
},
{
"code": null,
"e": 1917,
"s": 1778,
"text": "We are invoking these methods twice in the class and within a method. In the class we have declared the values returned by them as static."
},
{
"code": null,
"e": 2029,
"s": 1917,
"text": "And in the method we are using them (values returned by the methods) as local variables (obviously non-static)."
},
{
"code": null,
"e": 2599,
"s": 2029,
"text": "public class StaticExample{\n static int data = StaticExample.getInt();\n static Demo obj = StaticExample.getObject();\n public static Demo getObject(){\n Demo obj = new Demo(300);\n return obj;\n }\n public static int getInt(){\n return 20;\n }\n public static void main(String args[]) {\n System.out.println(StaticExample.data);\n System.out.println(StaticExample.obj.data);\n StaticExample obj = new StaticExample();\n System.out.println(obj.getInt());\n Demo demo = obj.getObject();\n System.out.println(demo.data);\n }\n}"
},
{
"code": null,
"e": 2613,
"s": 2599,
"text": "20\n300\n20\n300"
}
] |
How to retrieve a value from MongoDB by its key name? | To retrieve a value from MongoDB by its key name, use the following syntax −
db.yourCollectionName.find({},{"yourFieldName":1}).pretty();
To understand the above syntax, let us create a collection with the document. The query to create a collection with a document is as follows −
> db.retrieveValueFromAKeyDemo.insertOne({"CustomerName":"Larry","CustomerAge":21,"CustomerCountryName":"US"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9163b5a56efcc0f9e69048")
}
> db.retrieveValueFromAKeyDemo.insertOne({"CustomerName":"Chris","CustomerAge":24,"CustomerCountryName":"AUS"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9163c4a56efcc0f9e69049")
}
> db.retrieveValueFromAKeyDemo.insertOne({"CustomerName":"Mike","CustomerAge":26,"CustomerCountryName":"UK"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9163d3a56efcc0f9e6904a")
}
Display all documents from a collection with the help of find() method. The query is as follows −
> db.retrieveValueFromAKeyDemo.find().pretty();
The following is the output −
{
"_id" : ObjectId("5c9163b5a56efcc0f9e69048"),
"CustomerName" : "Larry",
"CustomerAge" : 21,
"CustomerCountryName" : "US"
}
{
"_id" : ObjectId("5c9163c4a56efcc0f9e69049"),
"CustomerName" : "Chris",
"CustomerAge" : 24,
"CustomerCountryName" : "AUS"
}
{
"_id" : ObjectId("5c9163d3a56efcc0f9e6904a"),
"CustomerName" : "Mike",
"CustomerAge" : 26,
"CustomerCountryName" : "UK"
}
Here is the query to retrieve a value from MongoDB by its key name i.e. we have considered the key ‘CustomerCountryName’ −
> db.retrieveValueFromAKeyDemo.find({},{"CustomerCountryName":1}).pretty();
The following is the output:
{
"_id" : ObjectId("5c9163b5a56efcc0f9e69048"),
"CustomerCountryName" : "US"
}
{
"_id" : ObjectId("5c9163c4a56efcc0f9e69049"),
"CustomerCountryName" : "AUS"
}
{
"_id" : ObjectId("5c9163d3a56efcc0f9e6904a"),
"CustomerCountryName" : "UK"
} | [
{
"code": null,
"e": 1139,
"s": 1062,
"text": "To retrieve a value from MongoDB by its key name, use the following syntax −"
},
{
"code": null,
"e": 1200,
"s": 1139,
"text": "db.yourCollectionName.find({},{\"yourFieldName\":1}).pretty();"
},
{
"code": null,
"e": 1343,
"s": 1200,
"text": "To understand the above syntax, let us create a collection with the document. The query to create a collection with a document is as follows −"
},
{
"code": null,
"e": 1934,
"s": 1343,
"text": "> db.retrieveValueFromAKeyDemo.insertOne({\"CustomerName\":\"Larry\",\"CustomerAge\":21,\"CustomerCountryName\":\"US\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c9163b5a56efcc0f9e69048\")\n}\n> db.retrieveValueFromAKeyDemo.insertOne({\"CustomerName\":\"Chris\",\"CustomerAge\":24,\"CustomerCountryName\":\"AUS\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c9163c4a56efcc0f9e69049\")\n}\n> db.retrieveValueFromAKeyDemo.insertOne({\"CustomerName\":\"Mike\",\"CustomerAge\":26,\"CustomerCountryName\":\"UK\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c9163d3a56efcc0f9e6904a\")\n}"
},
{
"code": null,
"e": 2032,
"s": 1934,
"text": "Display all documents from a collection with the help of find() method. The query is as follows −"
},
{
"code": null,
"e": 2080,
"s": 2032,
"text": "> db.retrieveValueFromAKeyDemo.find().pretty();"
},
{
"code": null,
"e": 2110,
"s": 2080,
"text": "The following is the output −"
},
{
"code": null,
"e": 2521,
"s": 2110,
"text": "{\n \"_id\" : ObjectId(\"5c9163b5a56efcc0f9e69048\"),\n \"CustomerName\" : \"Larry\",\n \"CustomerAge\" : 21,\n \"CustomerCountryName\" : \"US\"\n}\n{\n \"_id\" : ObjectId(\"5c9163c4a56efcc0f9e69049\"),\n \"CustomerName\" : \"Chris\",\n \"CustomerAge\" : 24,\n \"CustomerCountryName\" : \"AUS\"\n}\n{\n \"_id\" : ObjectId(\"5c9163d3a56efcc0f9e6904a\"),\n \"CustomerName\" : \"Mike\",\n \"CustomerAge\" : 26,\n \"CustomerCountryName\" : \"UK\"\n}"
},
{
"code": null,
"e": 2644,
"s": 2521,
"text": "Here is the query to retrieve a value from MongoDB by its key name i.e. we have considered the key ‘CustomerCountryName’ −"
},
{
"code": null,
"e": 2720,
"s": 2644,
"text": "> db.retrieveValueFromAKeyDemo.find({},{\"CustomerCountryName\":1}).pretty();"
},
{
"code": null,
"e": 2749,
"s": 2720,
"text": "The following is the output:"
},
{
"code": null,
"e": 3005,
"s": 2749,
"text": "{\n \"_id\" : ObjectId(\"5c9163b5a56efcc0f9e69048\"),\n \"CustomerCountryName\" : \"US\"\n}\n{\n \"_id\" : ObjectId(\"5c9163c4a56efcc0f9e69049\"),\n \"CustomerCountryName\" : \"AUS\"\n}\n{\n \"_id\" : ObjectId(\"5c9163d3a56efcc0f9e6904a\"),\n \"CustomerCountryName\" : \"UK\"\n}"
}
] |
Computer Programming - File I/O | A computer file is used to store data in digital format like plain text, image data, or any other content. Computer files can be organized inside different directories. Files are used to keep digital data, whereas directories are used to keep files.
Computer files can be considered as the digital counterpart of paper documents. While programming, you keep your source code in text files with different extensions, for example, C programming files end with the extension .c, Java programming files with .java, and Python files with .py.
Usually, you create files using text editors such as notepad, MS Word, MS Excel or MS Powerpoint, etc. However, many times, we need to create files using computer programs as well. We can modify an existing file using a computer program.
File input means data that is written into a file and file output means data that is read from a file. Actually, input and output terms are more related to screen input and output. When we display a result on the screen, it is called output. Similarly, if we provide some input to our program from the command prompt, then it is called input.
For now, it is enough to remember that writing into a file is file input and reading something from a file is file output.
Before we start working with any file using a computer program, either we need to create a new file if it does not exist or open an already existing file. In either case, we can open a file in the following modes −
Read-Only Mode − If you are going to just read an existing file and you do not want to write any further content in the file, then you will open the file in read-only mode. Almost all the programming languages provide syntax to open files in read-only mode.
Read-Only Mode − If you are going to just read an existing file and you do not want to write any further content in the file, then you will open the file in read-only mode. Almost all the programming languages provide syntax to open files in read-only mode.
Write-Only Mode − If you are going to write into either an existing file or a newly created file but you do not want to read any written content from that file, then you will open the file in write-only mode. All the programming languages provide syntax to open files in write-only mode.
Write-Only Mode − If you are going to write into either an existing file or a newly created file but you do not want to read any written content from that file, then you will open the file in write-only mode. All the programming languages provide syntax to open files in write-only mode.
Read & Write Mode − If you are going to read as well as write into the same file, then you will open file in read & write mode.
Read & Write Mode − If you are going to read as well as write into the same file, then you will open file in read & write mode.
Append Mode − When you open a file for writing, it allows you to start writing from the beginning of the file; however it will overwrite existing content, if any. Suppose we don’t want to overwrite any existing content, then we open the file in append mode. Append mode is ultimately a write mode, which allows content to be appended at the end of the file. Almost all the programming languages provide syntax to open files in append mode.
Append Mode − When you open a file for writing, it allows you to start writing from the beginning of the file; however it will overwrite existing content, if any. Suppose we don’t want to overwrite any existing content, then we open the file in append mode. Append mode is ultimately a write mode, which allows content to be appended at the end of the file. Almost all the programming languages provide syntax to open files in append mode.
In the following sections, we will learn how to open a fresh new file, how to write into it, and later, how to read and append more content into the same file.
You can use the fopen() function to create a new file or to open an existing file. This call will initialize an object of the type FILE, which contains all the information necessary to control the stream. Here is the prototype, i.e., signature of this function call −
FILE *fopen( const char * filename, const char * mode );
Here, filename is string literal, which you will use to name your file and access mode can have one of the following values −
r
Opens an existing text file for reading purpose.
w
Opens a text file for writing. If it does not exist, then a new file is created. Here, your program will start writing content from the beginning of the file.
a
Opens a text file for writing in appending mode. If it does not exist, then a new file is created. Here, your program will start appending content in the existing file content.
r+
Opens a text file for reading and writing both.
w+
Opens a text file for both reading and writing. It first truncates the file to zero length, if it exists; otherwise creates the file if it does not exist.
a+
Opens a text file for both reading and writing. It creates a file, if it does not exist. The reading will start from the beginning, but writing can only be appended.
To close a file, use the fclose( ) function. The prototype of this function is −
int fclose( FILE *fp );
The fclose( ) function returns zero on success, or EOF, special character, if there is an error in closing the file. This function actually flushes any data still pending in the buffer to the file, closes the file, and releases any memory used for the file. The EOF is a constant defined in the header file stdio.h.
There are various functions provided by C standard library to read and write a file character by character or in the form of a fixed length string. Let us see a few of them in the next section.
Given below is the simplest function to write individual characters to a stream −
int fputc( int c, FILE *fp );
The function fputc() writes the character value of the argument c to the output stream referenced by fp. It returns the written character written on success, otherwise EOF if there is an error. You can use the following functions to write a null-terminated string to a stream −
int fputs( const char *s, FILE *fp );
The function fputs() writes the string s into the file referenced by fp. It returns a non-negative value on success, otherwise EOF is returned in case of any error. You can also use the function int fprintf(FILE *fp,const char *format, ...) to write a string into a file. Try the following example −
#include <stdio.h>
int main() {
FILE *fp;
fp = fopen("/tmp/test.txt", "w+");
fprintf(fp, "This is testing for fprintf...\n");
fputs("This is testing for fputs...\n", fp);
fclose(fp);
}
When the above code is compiled and executed, it creates a new file test.txt in /tmp directory and writes two lines using two different functions. Let us read this file in the next section.
Given below is the simplest function to read a text file character by character −
int fgetc( FILE * fp );
The fgetc() function reads a character from the input file referenced by fp. The return value is the character read; or in case of any error, it returns EOF. The following function allows you to read a string from a stream −
char *fgets( char *buf, int n, FILE *fp );
The function fgets() reads up to n - 1 characters from the input stream referenced by fp. It copies the read string into the buffer buf, appending a null character to terminate the string.
If this function encounters a newline character '\n' or EOF before they have read the maximum number of characters, then it returns only the characters read up to that point including the new line character. You can also use int fscanf(FILE *fp, const char *format, ...) to read strings from a file, but it stops reading after encountering the first space character.
#include <stdio.h>
main() {
FILE *fp;
char buff[255];
fp = fopen("/tmp/test.txt", "r");
fscanf(fp, "%s", buff);
printf("1 : %s\n", buff );
fgets(buff, 255, (FILE*)fp);
printf("2: %s\n", buff );
fgets(buff, 255, (FILE*)fp);
printf("3: %s\n", buff );
fclose(fp);
}
When the above code is compiled and executed, it reads the file created in the previous section and produces the following result −
1 : This
2 : is testing for fprintf...
3 : This is testing for fputs...
Let's analyze what happened here. First, the fscanf() method reads This because after that, it encountered a space. The second call is for fgets(), which reads the remaining line till it encountered end of line. Finally, the last call fgets() reads the second line completely.
Java provides even richer set of functions to handle File I/O. For more on this topic, we suggest you to check our Java Tutorials.
Here, we will see a simple Java program, which is equivalent to the C program explained above. This program will open a text file, write a few text lines into it, and close the file. Finally, the same file is opened and then read from an already created file. You can try to execute the following program to see the output −
import java.io.*;
public class DemoJava {
public static void main(String []args) throws IOException {
File file = new File("/tmp/java.txt");
// Create a File
file.createNewFile();
// Creates a FileWriter Object using file object
FileWriter writer = new FileWriter(file);
// Writes the content to the file
writer.write("This is testing for Java write...\n");
writer.write("This is second line...\n");
// Flush the memory and close the file
writer.flush();
writer.close();
// Creates a FileReader Object
FileReader reader = new FileReader(file);
char [] a = new char[100];
// Read file content in the array
reader.read(a);
System.out.println( a );
// Close the file
reader.close();
}
}
When the above program is executed, it produces the following result −
This is testing for Java write...
This is second line...
The following program shows the same functionality to open a new file, write some content into it, and finally, read the same file −
# Create a new file
fo = open("/tmp/python.txt", "w")
# Writes the content to the file
fo.write( "This is testing for Python write...\n");
fo.write( "This is second line...\n");
# Close the file
fo.close()
# Open existing file
fo = open("/tmp/python.txt", "r")
# Read file content in a variable
str = fo.read(100);
print str
# Close opened file
fo.close()
When the above code is executed, it produces the following result −
This is testing for Python write...
This is second line...
107 Lectures
13.5 hours
Arnab Chakraborty
106 Lectures
8 hours
Arnab Chakraborty
99 Lectures
6 hours
Arnab Chakraborty
46 Lectures
2.5 hours
Shweta
70 Lectures
9 hours
Abhilash Nelson
52 Lectures
7 hours
Abhishek And Pukhraj
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2390,
"s": 2140,
"text": "A computer file is used to store data in digital format like plain text, image data, or any other content. Computer files can be organized inside different directories. Files are used to keep digital data, whereas directories are used to keep files."
},
{
"code": null,
"e": 2678,
"s": 2390,
"text": "Computer files can be considered as the digital counterpart of paper documents. While programming, you keep your source code in text files with different extensions, for example, C programming files end with the extension .c, Java programming files with .java, and Python files with .py."
},
{
"code": null,
"e": 2916,
"s": 2678,
"text": "Usually, you create files using text editors such as notepad, MS Word, MS Excel or MS Powerpoint, etc. However, many times, we need to create files using computer programs as well. We can modify an existing file using a computer program."
},
{
"code": null,
"e": 3259,
"s": 2916,
"text": "File input means data that is written into a file and file output means data that is read from a file. Actually, input and output terms are more related to screen input and output. When we display a result on the screen, it is called output. Similarly, if we provide some input to our program from the command prompt, then it is called input."
},
{
"code": null,
"e": 3382,
"s": 3259,
"text": "For now, it is enough to remember that writing into a file is file input and reading something from a file is file output."
},
{
"code": null,
"e": 3597,
"s": 3382,
"text": "Before we start working with any file using a computer program, either we need to create a new file if it does not exist or open an already existing file. In either case, we can open a file in the following modes −"
},
{
"code": null,
"e": 3855,
"s": 3597,
"text": "Read-Only Mode − If you are going to just read an existing file and you do not want to write any further content in the file, then you will open the file in read-only mode. Almost all the programming languages provide syntax to open files in read-only mode."
},
{
"code": null,
"e": 4113,
"s": 3855,
"text": "Read-Only Mode − If you are going to just read an existing file and you do not want to write any further content in the file, then you will open the file in read-only mode. Almost all the programming languages provide syntax to open files in read-only mode."
},
{
"code": null,
"e": 4401,
"s": 4113,
"text": "Write-Only Mode − If you are going to write into either an existing file or a newly created file but you do not want to read any written content from that file, then you will open the file in write-only mode. All the programming languages provide syntax to open files in write-only mode."
},
{
"code": null,
"e": 4689,
"s": 4401,
"text": "Write-Only Mode − If you are going to write into either an existing file or a newly created file but you do not want to read any written content from that file, then you will open the file in write-only mode. All the programming languages provide syntax to open files in write-only mode."
},
{
"code": null,
"e": 4817,
"s": 4689,
"text": "Read & Write Mode − If you are going to read as well as write into the same file, then you will open file in read & write mode."
},
{
"code": null,
"e": 4945,
"s": 4817,
"text": "Read & Write Mode − If you are going to read as well as write into the same file, then you will open file in read & write mode."
},
{
"code": null,
"e": 5385,
"s": 4945,
"text": "Append Mode − When you open a file for writing, it allows you to start writing from the beginning of the file; however it will overwrite existing content, if any. Suppose we don’t want to overwrite any existing content, then we open the file in append mode. Append mode is ultimately a write mode, which allows content to be appended at the end of the file. Almost all the programming languages provide syntax to open files in append mode."
},
{
"code": null,
"e": 5825,
"s": 5385,
"text": "Append Mode − When you open a file for writing, it allows you to start writing from the beginning of the file; however it will overwrite existing content, if any. Suppose we don’t want to overwrite any existing content, then we open the file in append mode. Append mode is ultimately a write mode, which allows content to be appended at the end of the file. Almost all the programming languages provide syntax to open files in append mode."
},
{
"code": null,
"e": 5985,
"s": 5825,
"text": "In the following sections, we will learn how to open a fresh new file, how to write into it, and later, how to read and append more content into the same file."
},
{
"code": null,
"e": 6253,
"s": 5985,
"text": "You can use the fopen() function to create a new file or to open an existing file. This call will initialize an object of the type FILE, which contains all the information necessary to control the stream. Here is the prototype, i.e., signature of this function call −"
},
{
"code": null,
"e": 6311,
"s": 6253,
"text": "FILE *fopen( const char * filename, const char * mode );\n"
},
{
"code": null,
"e": 6437,
"s": 6311,
"text": "Here, filename is string literal, which you will use to name your file and access mode can have one of the following values −"
},
{
"code": null,
"e": 6439,
"s": 6437,
"text": "r"
},
{
"code": null,
"e": 6488,
"s": 6439,
"text": "Opens an existing text file for reading purpose."
},
{
"code": null,
"e": 6490,
"s": 6488,
"text": "w"
},
{
"code": null,
"e": 6649,
"s": 6490,
"text": "Opens a text file for writing. If it does not exist, then a new file is created. Here, your program will start writing content from the beginning of the file."
},
{
"code": null,
"e": 6651,
"s": 6649,
"text": "a"
},
{
"code": null,
"e": 6828,
"s": 6651,
"text": "Opens a text file for writing in appending mode. If it does not exist, then a new file is created. Here, your program will start appending content in the existing file content."
},
{
"code": null,
"e": 6831,
"s": 6828,
"text": "r+"
},
{
"code": null,
"e": 6879,
"s": 6831,
"text": "Opens a text file for reading and writing both."
},
{
"code": null,
"e": 6882,
"s": 6879,
"text": "w+"
},
{
"code": null,
"e": 7037,
"s": 6882,
"text": "Opens a text file for both reading and writing. It first truncates the file to zero length, if it exists; otherwise creates the file if it does not exist."
},
{
"code": null,
"e": 7040,
"s": 7037,
"text": "a+"
},
{
"code": null,
"e": 7206,
"s": 7040,
"text": "Opens a text file for both reading and writing. It creates a file, if it does not exist. The reading will start from the beginning, but writing can only be appended."
},
{
"code": null,
"e": 7287,
"s": 7206,
"text": "To close a file, use the fclose( ) function. The prototype of this function is −"
},
{
"code": null,
"e": 7312,
"s": 7287,
"text": " int fclose( FILE *fp );"
},
{
"code": null,
"e": 7628,
"s": 7312,
"text": "The fclose( ) function returns zero on success, or EOF, special character, if there is an error in closing the file. This function actually flushes any data still pending in the buffer to the file, closes the file, and releases any memory used for the file. The EOF is a constant defined in the header file stdio.h."
},
{
"code": null,
"e": 7822,
"s": 7628,
"text": "There are various functions provided by C standard library to read and write a file character by character or in the form of a fixed length string. Let us see a few of them in the next section."
},
{
"code": null,
"e": 7904,
"s": 7822,
"text": "Given below is the simplest function to write individual characters to a stream −"
},
{
"code": null,
"e": 7934,
"s": 7904,
"text": "int fputc( int c, FILE *fp );"
},
{
"code": null,
"e": 8212,
"s": 7934,
"text": "The function fputc() writes the character value of the argument c to the output stream referenced by fp. It returns the written character written on success, otherwise EOF if there is an error. You can use the following functions to write a null-terminated string to a stream −"
},
{
"code": null,
"e": 8250,
"s": 8212,
"text": "int fputs( const char *s, FILE *fp );"
},
{
"code": null,
"e": 8550,
"s": 8250,
"text": "The function fputs() writes the string s into the file referenced by fp. It returns a non-negative value on success, otherwise EOF is returned in case of any error. You can also use the function int fprintf(FILE *fp,const char *format, ...) to write a string into a file. Try the following example −"
},
{
"code": null,
"e": 8752,
"s": 8550,
"text": "#include <stdio.h>\n\nint main() {\n FILE *fp;\n\n fp = fopen(\"/tmp/test.txt\", \"w+\");\n fprintf(fp, \"This is testing for fprintf...\\n\");\n fputs(\"This is testing for fputs...\\n\", fp);\n fclose(fp);\n}"
},
{
"code": null,
"e": 8942,
"s": 8752,
"text": "When the above code is compiled and executed, it creates a new file test.txt in /tmp directory and writes two lines using two different functions. Let us read this file in the next section."
},
{
"code": null,
"e": 9024,
"s": 8942,
"text": "Given below is the simplest function to read a text file character by character −"
},
{
"code": null,
"e": 9049,
"s": 9024,
"text": "int fgetc( FILE * fp );\n"
},
{
"code": null,
"e": 9274,
"s": 9049,
"text": "The fgetc() function reads a character from the input file referenced by fp. The return value is the character read; or in case of any error, it returns EOF. The following function allows you to read a string from a stream −"
},
{
"code": null,
"e": 9318,
"s": 9274,
"text": "char *fgets( char *buf, int n, FILE *fp );\n"
},
{
"code": null,
"e": 9507,
"s": 9318,
"text": "The function fgets() reads up to n - 1 characters from the input stream referenced by fp. It copies the read string into the buffer buf, appending a null character to terminate the string."
},
{
"code": null,
"e": 9874,
"s": 9507,
"text": "If this function encounters a newline character '\\n' or EOF before they have read the maximum number of characters, then it returns only the characters read up to that point including the new line character. You can also use int fscanf(FILE *fp, const char *format, ...) to read strings from a file, but it stops reading after encountering the first space character."
},
{
"code": null,
"e": 10175,
"s": 9874,
"text": "#include <stdio.h>\n\nmain() {\n\n FILE *fp;\n char buff[255];\n\n fp = fopen(\"/tmp/test.txt\", \"r\");\n fscanf(fp, \"%s\", buff);\n printf(\"1 : %s\\n\", buff );\n\n fgets(buff, 255, (FILE*)fp);\n printf(\"2: %s\\n\", buff );\n \n fgets(buff, 255, (FILE*)fp);\n printf(\"3: %s\\n\", buff );\n fclose(fp);\n}"
},
{
"code": null,
"e": 10307,
"s": 10175,
"text": "When the above code is compiled and executed, it reads the file created in the previous section and produces the following result −"
},
{
"code": null,
"e": 10381,
"s": 10307,
"text": "1 : This\n2 : is testing for fprintf...\n\n3 : This is testing for fputs...\n"
},
{
"code": null,
"e": 10658,
"s": 10381,
"text": "Let's analyze what happened here. First, the fscanf() method reads This because after that, it encountered a space. The second call is for fgets(), which reads the remaining line till it encountered end of line. Finally, the last call fgets() reads the second line completely."
},
{
"code": null,
"e": 10789,
"s": 10658,
"text": "Java provides even richer set of functions to handle File I/O. For more on this topic, we suggest you to check our Java Tutorials."
},
{
"code": null,
"e": 11114,
"s": 10789,
"text": "Here, we will see a simple Java program, which is equivalent to the C program explained above. This program will open a text file, write a few text lines into it, and close the file. Finally, the same file is opened and then read from an already created file. You can try to execute the following program to see the output −"
},
{
"code": null,
"e": 11971,
"s": 11114,
"text": "import java.io.*;\n\npublic class DemoJava {\n public static void main(String []args) throws IOException {\n File file = new File(\"/tmp/java.txt\");\n \n // Create a File\n file.createNewFile();\n \n // Creates a FileWriter Object using file object\n FileWriter writer = new FileWriter(file); \n \n // Writes the content to the file\n writer.write(\"This is testing for Java write...\\n\");\n writer.write(\"This is second line...\\n\");\n \n // Flush the memory and close the file\n writer.flush();\n writer.close();\n \n // Creates a FileReader Object\n FileReader reader = new FileReader(file); \n char [] a = new char[100];\n \n // Read file content in the array\n reader.read(a);\n System.out.println( a );\n \n // Close the file\n reader.close();\n }\n}"
},
{
"code": null,
"e": 12042,
"s": 11971,
"text": "When the above program is executed, it produces the following result −"
},
{
"code": null,
"e": 12100,
"s": 12042,
"text": "This is testing for Java write...\nThis is second line...\n"
},
{
"code": null,
"e": 12233,
"s": 12100,
"text": "The following program shows the same functionality to open a new file, write some content into it, and finally, read the same file −"
},
{
"code": null,
"e": 12594,
"s": 12233,
"text": "# Create a new file\nfo = open(\"/tmp/python.txt\", \"w\")\n\n# Writes the content to the file\nfo.write( \"This is testing for Python write...\\n\");\nfo.write( \"This is second line...\\n\");\n\n# Close the file\nfo.close()\n\n# Open existing file\nfo = open(\"/tmp/python.txt\", \"r\")\n\n# Read file content in a variable\nstr = fo.read(100);\nprint str\n\n# Close opened file\nfo.close()"
},
{
"code": null,
"e": 12662,
"s": 12594,
"text": "When the above code is executed, it produces the following result −"
},
{
"code": null,
"e": 12722,
"s": 12662,
"text": "This is testing for Python write...\nThis is second line...\n"
},
{
"code": null,
"e": 12759,
"s": 12722,
"text": "\n 107 Lectures \n 13.5 hours \n"
},
{
"code": null,
"e": 12778,
"s": 12759,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 12812,
"s": 12778,
"text": "\n 106 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 12831,
"s": 12812,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 12864,
"s": 12831,
"text": "\n 99 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 12883,
"s": 12864,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 12918,
"s": 12883,
"text": "\n 46 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 12926,
"s": 12918,
"text": " Shweta"
},
{
"code": null,
"e": 12959,
"s": 12926,
"text": "\n 70 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 12976,
"s": 12959,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 13009,
"s": 12976,
"text": "\n 52 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 13031,
"s": 13009,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 13038,
"s": 13031,
"text": " Print"
},
{
"code": null,
"e": 13049,
"s": 13038,
"text": " Add Notes"
}
] |
How to create transparent bar plot using ggplot2 in R? | To create transparent barplot using ggplot2, we can use alpha argument inside geom_bar function. For example, if we have a data frame called df that contains a categorical column say x and a numerical column say count then the bar plot with transparency can be created by using the command ggplot(df,aes(x,y))+geom_bar(alpha=0.1,stat="identity")
Consider the below data frame −
Live Demo
x<-c("A","B","C")
y<-c(24,21,26)
df<-data.frame(x,y)
df
x y
1 A 24
2 B 21
3 C 26
Loading ggplot2 package and creating bar plot for data in df −
library(ggplot2)
ggplot(df,aes(x,y))+geom_bar(stat="identity")
Creating bar plot for data in df with transparent bars −
ggplot(df,aes(x,y))+geom_bar(alpha=0.1,stat="identity") | [
{
"code": null,
"e": 1408,
"s": 1062,
"text": "To create transparent barplot using ggplot2, we can use alpha argument inside geom_bar function. For example, if we have a data frame called df that contains a categorical column say x and a numerical column say count then the bar plot with transparency can be created by using the command ggplot(df,aes(x,y))+geom_bar(alpha=0.1,stat=\"identity\")"
},
{
"code": null,
"e": 1440,
"s": 1408,
"text": "Consider the below data frame −"
},
{
"code": null,
"e": 1451,
"s": 1440,
"text": " Live Demo"
},
{
"code": null,
"e": 1507,
"s": 1451,
"text": "x<-c(\"A\",\"B\",\"C\")\ny<-c(24,21,26)\ndf<-data.frame(x,y)\ndf"
},
{
"code": null,
"e": 1542,
"s": 1507,
"text": " x y\n1 A 24\n2 B 21\n3 C 26"
},
{
"code": null,
"e": 1605,
"s": 1542,
"text": "Loading ggplot2 package and creating bar plot for data in df −"
},
{
"code": null,
"e": 1668,
"s": 1605,
"text": "library(ggplot2)\nggplot(df,aes(x,y))+geom_bar(stat=\"identity\")"
},
{
"code": null,
"e": 1725,
"s": 1668,
"text": "Creating bar plot for data in df with transparent bars −"
},
{
"code": null,
"e": 1781,
"s": 1725,
"text": "ggplot(df,aes(x,y))+geom_bar(alpha=0.1,stat=\"identity\")"
}
] |
Maximum number of buckets that can be filled | 10 Mar, 2022
Given an array arr[] consisting of capacities of N buckets where arr[i] denotes the capacity of the ith bucket. If the total amount of water available is the sum of array indices (1-based indexing), the task is to find the maximum number of buckets that can be filled with the available water. The bucket will be considered filled if it has at least 1 liter in it.
Examples:
Input: arr[] = {1, 5, 3, 4, 7, 9}Output: 4Explanation:Total available water = Sum of arrayindices of arr[] = 1 + 2 + 3 + 4 + 5 = 15.Sorting the array in ascending order modifies the array to {1, 3, 4, 5, 7, 9}.Fill the bucket having capacity 1, then . Now, available water = 14. Fill the bucket having capacity 3 . Now, available water = 11.Fill bucket having capacity 4. Now, available water = 7.Fill bucket having capacity 5. Now, available water = 2. in this case it is filled with more than 1 liter so this bucket is also considered.Therefore, the total buckets that can be fully filled with water is 4.
Input: arr[] = {2, 5, 8, 3, 2, 10, 8}Output: 5
Approach: The given problem can be solved Greedily. Follow the steps below to solve the given problem:
Calculate the total water availability by calculating the sum of first N natural numbers.
Sort the array arr[] in ascending order.
Traverse the given array arr[] and find the sum of array elementsy till that index, say i, where the sum exceeds the total availability.
After completing the above steps, print the value of index i as the maximum number of buckets that can be filled.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find the maximum number// of buckets that can be filled with// the amount of water availableint getBuckets(int arr[], int N){ // Find the total available water int availableWater = N * (N - 1) / 2; // Sort the array in ascending order sort(arr, arr + N); int i = 0, sum = 0; // Check if bucket can be // filled with available water while (sum <= availableWater) { sum += arr[i]; i++; } // Print count of buckets cout << i - 1;} // Driver Codeint main(){ int arr[] = { 1, 5, 3, 4, 7, 9 }; int N = sizeof(arr) / sizeof(arr[0]); getBuckets(arr, N); return 0;}
// Java program for the above approachimport java.util.*;public class GFG{ // Function to find the maximum number // of buckets that can be filled with // the amount of water available static void getBuckets(int[] arr, int N) { // Find the total available water int availableWater = N * (N - 1) / 2; // Sort the array in ascending order Arrays.sort(arr); int i = 0, sum = 0; // Check if bucket can be // filled with available water while (sum <= availableWater) { sum += arr[i]; i++; } // Print count of buckets System.out.println(i - 1); } // Driver code public static void main(String[] args) { int[] arr = { 1, 5, 3, 4, 7, 9 }; int N = arr.length; getBuckets(arr, N); }} // This code is contributed by divyesh072019.
# Python3 program for the above approach # Function to find the maximum number# of buckets that can be filled with# the amount of water availabledef getBuckets(arr, N) : # Find the total available water availableWater = N * (N - 1) // 2 # Sort the array in ascending order arr.sort() i, Sum = 0, 0 # Check if bucket can be # filled with available water while (Sum <= availableWater) : Sum += arr[i] i += 1 # Print count of buckets print(i - 1, end = "") arr = [ 1, 5, 3, 4, 7, 9 ]N = len(arr) getBuckets(arr, N); # This code is contributed by divyeshrabadiya07.
// C# program to implement// the above approachusing System;using System.Collections.Generic;using System.Linq; class GFG{ // Function to find the maximum number // of buckets that can be filled with // the amount of water available static void getBuckets(int[] arr, int N) { // Find the total available water int availableWater = N * (N - 1) / 2; // Sort the array in ascending order Array.Sort(arr); int i = 0, sum = 0; // Check if bucket can be // filled with available water while (sum <= availableWater) { sum += arr[i]; i++; } // Print count of buckets Console.Write(i - 1); } // Driver Codepublic static void Main(String[] args){ int[] arr = { 1, 5, 3, 4, 7, 9 }; int N = arr.Length; getBuckets(arr, N);}} // This code is contributed by splevel62.
<script> // Javascript program to implement // the above approach // Function to find the maximum number // of buckets that can be filled with // the amount of water available function getBuckets(arr, N) { // Find the total available water let availableWater = N * (N - 1) / 2; // Sort the array in ascending order arr.sort(function(a, b){return a - b}); let i = 0, sum = 0; // Check if bucket can be // filled with available water while (sum <= availableWater) { sum += arr[i]; i++; } // Print count of buckets document.write(i - 1); } let arr = [ 1, 5, 3, 4, 7, 9 ]; let N = arr.length; getBuckets(arr, N); </script>
4
Time Complexity: O(N*log N)Auxiliary Space: O(1)
divyesh072019
splevel62
divyeshrabadiya07
decode2207
nandinigujral
sweetyty
prefix-sum
Arrays
Greedy
Mathematical
Sorting
prefix-sum
Arrays
Greedy
Mathematical
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
Search, insert and delete in an unsorted array
Window Sliding Technique
Chocolate Distribution Problem
Longest Consecutive Subsequence
Dijkstra's shortest path algorithm | Greedy Algo-7
Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5
Write a program to print all permutations of a given string
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Huffman Coding | Greedy Algo-3 | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n10 Mar, 2022"
},
{
"code": null,
"e": 418,
"s": 52,
"text": "Given an array arr[] consisting of capacities of N buckets where arr[i] denotes the capacity of the ith bucket. If the total amount of water available is the sum of array indices (1-based indexing), the task is to find the maximum number of buckets that can be filled with the available water. The bucket will be considered filled if it has at least 1 liter in it. "
},
{
"code": null,
"e": 428,
"s": 418,
"text": "Examples:"
},
{
"code": null,
"e": 1037,
"s": 428,
"text": "Input: arr[] = {1, 5, 3, 4, 7, 9}Output: 4Explanation:Total available water = Sum of arrayindices of arr[] = 1 + 2 + 3 + 4 + 5 = 15.Sorting the array in ascending order modifies the array to {1, 3, 4, 5, 7, 9}.Fill the bucket having capacity 1, then . Now, available water = 14. Fill the bucket having capacity 3 . Now, available water = 11.Fill bucket having capacity 4. Now, available water = 7.Fill bucket having capacity 5. Now, available water = 2. in this case it is filled with more than 1 liter so this bucket is also considered.Therefore, the total buckets that can be fully filled with water is 4."
},
{
"code": null,
"e": 1084,
"s": 1037,
"text": "Input: arr[] = {2, 5, 8, 3, 2, 10, 8}Output: 5"
},
{
"code": null,
"e": 1187,
"s": 1084,
"text": "Approach: The given problem can be solved Greedily. Follow the steps below to solve the given problem:"
},
{
"code": null,
"e": 1277,
"s": 1187,
"text": "Calculate the total water availability by calculating the sum of first N natural numbers."
},
{
"code": null,
"e": 1318,
"s": 1277,
"text": "Sort the array arr[] in ascending order."
},
{
"code": null,
"e": 1455,
"s": 1318,
"text": "Traverse the given array arr[] and find the sum of array elementsy till that index, say i, where the sum exceeds the total availability."
},
{
"code": null,
"e": 1569,
"s": 1455,
"text": "After completing the above steps, print the value of index i as the maximum number of buckets that can be filled."
},
{
"code": null,
"e": 1620,
"s": 1569,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 1624,
"s": 1620,
"text": "C++"
},
{
"code": null,
"e": 1629,
"s": 1624,
"text": "Java"
},
{
"code": null,
"e": 1637,
"s": 1629,
"text": "Python3"
},
{
"code": null,
"e": 1640,
"s": 1637,
"text": "C#"
},
{
"code": null,
"e": 1651,
"s": 1640,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find the maximum number// of buckets that can be filled with// the amount of water availableint getBuckets(int arr[], int N){ // Find the total available water int availableWater = N * (N - 1) / 2; // Sort the array in ascending order sort(arr, arr + N); int i = 0, sum = 0; // Check if bucket can be // filled with available water while (sum <= availableWater) { sum += arr[i]; i++; } // Print count of buckets cout << i - 1;} // Driver Codeint main(){ int arr[] = { 1, 5, 3, 4, 7, 9 }; int N = sizeof(arr) / sizeof(arr[0]); getBuckets(arr, N); return 0;}",
"e": 2371,
"s": 1651,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.*;public class GFG{ // Function to find the maximum number // of buckets that can be filled with // the amount of water available static void getBuckets(int[] arr, int N) { // Find the total available water int availableWater = N * (N - 1) / 2; // Sort the array in ascending order Arrays.sort(arr); int i = 0, sum = 0; // Check if bucket can be // filled with available water while (sum <= availableWater) { sum += arr[i]; i++; } // Print count of buckets System.out.println(i - 1); } // Driver code public static void main(String[] args) { int[] arr = { 1, 5, 3, 4, 7, 9 }; int N = arr.length; getBuckets(arr, N); }} // This code is contributed by divyesh072019.",
"e": 3162,
"s": 2371,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to find the maximum number# of buckets that can be filled with# the amount of water availabledef getBuckets(arr, N) : # Find the total available water availableWater = N * (N - 1) // 2 # Sort the array in ascending order arr.sort() i, Sum = 0, 0 # Check if bucket can be # filled with available water while (Sum <= availableWater) : Sum += arr[i] i += 1 # Print count of buckets print(i - 1, end = \"\") arr = [ 1, 5, 3, 4, 7, 9 ]N = len(arr) getBuckets(arr, N); # This code is contributed by divyeshrabadiya07.",
"e": 3773,
"s": 3162,
"text": null
},
{
"code": "// C# program to implement// the above approachusing System;using System.Collections.Generic;using System.Linq; class GFG{ // Function to find the maximum number // of buckets that can be filled with // the amount of water available static void getBuckets(int[] arr, int N) { // Find the total available water int availableWater = N * (N - 1) / 2; // Sort the array in ascending order Array.Sort(arr); int i = 0, sum = 0; // Check if bucket can be // filled with available water while (sum <= availableWater) { sum += arr[i]; i++; } // Print count of buckets Console.Write(i - 1); } // Driver Codepublic static void Main(String[] args){ int[] arr = { 1, 5, 3, 4, 7, 9 }; int N = arr.Length; getBuckets(arr, N);}} // This code is contributed by splevel62.",
"e": 4601,
"s": 3773,
"text": null
},
{
"code": "<script> // Javascript program to implement // the above approach // Function to find the maximum number // of buckets that can be filled with // the amount of water available function getBuckets(arr, N) { // Find the total available water let availableWater = N * (N - 1) / 2; // Sort the array in ascending order arr.sort(function(a, b){return a - b}); let i = 0, sum = 0; // Check if bucket can be // filled with available water while (sum <= availableWater) { sum += arr[i]; i++; } // Print count of buckets document.write(i - 1); } let arr = [ 1, 5, 3, 4, 7, 9 ]; let N = arr.length; getBuckets(arr, N); </script>",
"e": 5346,
"s": 4601,
"text": null
},
{
"code": null,
"e": 5348,
"s": 5346,
"text": "4"
},
{
"code": null,
"e": 5399,
"s": 5350,
"text": "Time Complexity: O(N*log N)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 5413,
"s": 5399,
"text": "divyesh072019"
},
{
"code": null,
"e": 5423,
"s": 5413,
"text": "splevel62"
},
{
"code": null,
"e": 5441,
"s": 5423,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 5452,
"s": 5441,
"text": "decode2207"
},
{
"code": null,
"e": 5466,
"s": 5452,
"text": "nandinigujral"
},
{
"code": null,
"e": 5475,
"s": 5466,
"text": "sweetyty"
},
{
"code": null,
"e": 5486,
"s": 5475,
"text": "prefix-sum"
},
{
"code": null,
"e": 5493,
"s": 5486,
"text": "Arrays"
},
{
"code": null,
"e": 5500,
"s": 5493,
"text": "Greedy"
},
{
"code": null,
"e": 5513,
"s": 5500,
"text": "Mathematical"
},
{
"code": null,
"e": 5521,
"s": 5513,
"text": "Sorting"
},
{
"code": null,
"e": 5532,
"s": 5521,
"text": "prefix-sum"
},
{
"code": null,
"e": 5539,
"s": 5532,
"text": "Arrays"
},
{
"code": null,
"e": 5546,
"s": 5539,
"text": "Greedy"
},
{
"code": null,
"e": 5559,
"s": 5546,
"text": "Mathematical"
},
{
"code": null,
"e": 5567,
"s": 5559,
"text": "Sorting"
},
{
"code": null,
"e": 5665,
"s": 5567,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5697,
"s": 5665,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 5744,
"s": 5697,
"text": "Search, insert and delete in an unsorted array"
},
{
"code": null,
"e": 5769,
"s": 5744,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 5800,
"s": 5769,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 5832,
"s": 5800,
"text": "Longest Consecutive Subsequence"
},
{
"code": null,
"e": 5883,
"s": 5832,
"text": "Dijkstra's shortest path algorithm | Greedy Algo-7"
},
{
"code": null,
"e": 5934,
"s": 5883,
"text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5"
},
{
"code": null,
"e": 5994,
"s": 5934,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 6052,
"s": 5994,
"text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2"
}
] |
What is CommonModule in Angular 10 ? | 30 Apr, 2021
In this article, we are going to see what is CommonModule in Angular 10 and how to use it.
CommonModule is used to export all the basic Angular directives and pipes. It is re-exported when we import BrowserModule into our angular application, BrowserModule is automatically imported into our application when we create our Angular application using ‘ng new’ command
Syntax: CommonModule is automatically imported by BrowserModule when the app is created.
import { BrowserModule } from '@angular/platform-browser';
@NgModule({
imports: [
BrowserModule,
]
})
export class AppModule { }
Directives Imported:
NgClass
NgComponentOutlet
NgForOf
NgIf
NgPluralCase:
NgStyle
NgSwitch
NgSwitchCase
NgSwitchDefault
NgTemplateOutlet
Pipes Imported:
AsyncPipe
CurrencyPipe
DatePipe
DecimalPipe
I18nPluralPipe
I18nSelectPipe
JsonPipe
KeyValuePipe
LowerCasePipe
PercentPipe
SlicePipe
TitleCasePipe
UpperCasePipe
Approach:
Create the Angular app to be used
There is no need for any import for the CommonModule to be used
In app.module.ts CommonModule is imported through BrowserModule.
Pipes and directives will be imported automatically, so we can use them easily.
Make the necessary files for desired output.
Serve the angular app using ng serve to see the output.
Example 1:
app.module.ts
import { NgModule } from '@angular/core';// BrowserModule automatically imports all CommonModule Dependencies import { BrowserModule } from '@angular/platform-browser';import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent ], imports: [ // Adding Imports BrowserModule, ], providers: [], bootstrap: [AppComponent]})export class AppModule { }
app.component.ts
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html'})export class AppComponent { geek = "GeekClass"; g = document.getElementsByClassName(this.geek);}
app.component.html
<!-- use of ngClass directive --><h1 [ngClass] = "geek"> GeeksforGeeks</h1> Upper Heading's class is : "{{ g[0].className }}"
Output:
Angular10
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Routing in Angular 9/10
Angular PrimeNG Dropdown Component
Angular 10 (blur) Event
How to make a Bootstrap Modal Popup in Angular 9/8 ?
How to setup 404 page in angular routing ?
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ? | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n30 Apr, 2021"
},
{
"code": null,
"e": 143,
"s": 52,
"text": "In this article, we are going to see what is CommonModule in Angular 10 and how to use it."
},
{
"code": null,
"e": 418,
"s": 143,
"text": "CommonModule is used to export all the basic Angular directives and pipes. It is re-exported when we import BrowserModule into our angular application, BrowserModule is automatically imported into our application when we create our Angular application using ‘ng new’ command"
},
{
"code": null,
"e": 507,
"s": 418,
"text": "Syntax: CommonModule is automatically imported by BrowserModule when the app is created."
},
{
"code": null,
"e": 649,
"s": 507,
"text": " import { BrowserModule } from '@angular/platform-browser';\n \n @NgModule({\n\n imports: [\n BrowserModule,\n ]\n})\nexport class AppModule { }"
},
{
"code": null,
"e": 670,
"s": 649,
"text": "Directives Imported:"
},
{
"code": null,
"e": 678,
"s": 670,
"text": "NgClass"
},
{
"code": null,
"e": 696,
"s": 678,
"text": "NgComponentOutlet"
},
{
"code": null,
"e": 704,
"s": 696,
"text": "NgForOf"
},
{
"code": null,
"e": 709,
"s": 704,
"text": "NgIf"
},
{
"code": null,
"e": 723,
"s": 709,
"text": "NgPluralCase:"
},
{
"code": null,
"e": 731,
"s": 723,
"text": "NgStyle"
},
{
"code": null,
"e": 740,
"s": 731,
"text": "NgSwitch"
},
{
"code": null,
"e": 753,
"s": 740,
"text": "NgSwitchCase"
},
{
"code": null,
"e": 769,
"s": 753,
"text": "NgSwitchDefault"
},
{
"code": null,
"e": 786,
"s": 769,
"text": "NgTemplateOutlet"
},
{
"code": null,
"e": 802,
"s": 786,
"text": "Pipes Imported:"
},
{
"code": null,
"e": 812,
"s": 802,
"text": "AsyncPipe"
},
{
"code": null,
"e": 825,
"s": 812,
"text": "CurrencyPipe"
},
{
"code": null,
"e": 834,
"s": 825,
"text": "DatePipe"
},
{
"code": null,
"e": 846,
"s": 834,
"text": "DecimalPipe"
},
{
"code": null,
"e": 861,
"s": 846,
"text": "I18nPluralPipe"
},
{
"code": null,
"e": 876,
"s": 861,
"text": "I18nSelectPipe"
},
{
"code": null,
"e": 885,
"s": 876,
"text": "JsonPipe"
},
{
"code": null,
"e": 898,
"s": 885,
"text": "KeyValuePipe"
},
{
"code": null,
"e": 912,
"s": 898,
"text": "LowerCasePipe"
},
{
"code": null,
"e": 924,
"s": 912,
"text": "PercentPipe"
},
{
"code": null,
"e": 934,
"s": 924,
"text": "SlicePipe"
},
{
"code": null,
"e": 948,
"s": 934,
"text": "TitleCasePipe"
},
{
"code": null,
"e": 962,
"s": 948,
"text": "UpperCasePipe"
},
{
"code": null,
"e": 973,
"s": 962,
"text": "Approach: "
},
{
"code": null,
"e": 1007,
"s": 973,
"text": "Create the Angular app to be used"
},
{
"code": null,
"e": 1071,
"s": 1007,
"text": "There is no need for any import for the CommonModule to be used"
},
{
"code": null,
"e": 1136,
"s": 1071,
"text": "In app.module.ts CommonModule is imported through BrowserModule."
},
{
"code": null,
"e": 1216,
"s": 1136,
"text": "Pipes and directives will be imported automatically, so we can use them easily."
},
{
"code": null,
"e": 1261,
"s": 1216,
"text": "Make the necessary files for desired output."
},
{
"code": null,
"e": 1317,
"s": 1261,
"text": "Serve the angular app using ng serve to see the output."
},
{
"code": null,
"e": 1328,
"s": 1317,
"text": "Example 1:"
},
{
"code": null,
"e": 1342,
"s": 1328,
"text": "app.module.ts"
},
{
"code": "import { NgModule } from '@angular/core';// BrowserModule automatically imports all CommonModule Dependencies import { BrowserModule } from '@angular/platform-browser';import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent ], imports: [ // Adding Imports BrowserModule, ], providers: [], bootstrap: [AppComponent]})export class AppModule { }",
"e": 1735,
"s": 1342,
"text": null
},
{
"code": null,
"e": 1752,
"s": 1735,
"text": "app.component.ts"
},
{
"code": "import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html'})export class AppComponent { geek = \"GeekClass\"; g = document.getElementsByClassName(this.geek);}",
"e": 1985,
"s": 1752,
"text": null
},
{
"code": null,
"e": 2004,
"s": 1985,
"text": "app.component.html"
},
{
"code": "<!-- use of ngClass directive --><h1 [ngClass] = \"geek\"> GeeksforGeeks</h1> Upper Heading's class is : \"{{ g[0].className }}\"",
"e": 2132,
"s": 2004,
"text": null
},
{
"code": null,
"e": 2140,
"s": 2132,
"text": "Output:"
},
{
"code": null,
"e": 2150,
"s": 2140,
"text": "Angular10"
},
{
"code": null,
"e": 2160,
"s": 2150,
"text": "AngularJS"
},
{
"code": null,
"e": 2177,
"s": 2160,
"text": "Web Technologies"
},
{
"code": null,
"e": 2275,
"s": 2177,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2299,
"s": 2275,
"text": "Routing in Angular 9/10"
},
{
"code": null,
"e": 2334,
"s": 2299,
"text": "Angular PrimeNG Dropdown Component"
},
{
"code": null,
"e": 2358,
"s": 2334,
"text": "Angular 10 (blur) Event"
},
{
"code": null,
"e": 2411,
"s": 2358,
"text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?"
},
{
"code": null,
"e": 2454,
"s": 2411,
"text": "How to setup 404 page in angular routing ?"
},
{
"code": null,
"e": 2487,
"s": 2454,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2549,
"s": 2487,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2610,
"s": 2549,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2660,
"s": 2610,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
How to overwrite a file to hide file contents, and make original contents unrecoverable in Linux? | To overwrite and file contents in the Linux system, we use the shred command using the terminal.
shred – The shred command is used to securely delete files and devices. This command overwrites a file to hide file contents, and optionally delete the file so that it is very difficult to recover the file for any software in the Linux/Unix system.
As usual, to remove files from the system, we use the rm command using the terminal. After removal files through the rm command, it may be recoverable using the software whereas after removing files through the shred command files are unrecoverable because the shred command overwrites the files three times with multiple patterns.
The general syntax of the shred command is as follows −
shred [OPTION]... FILE...
Brief description of option available in the shred command.
Overwrite the contents of the file and make it unrecoverable in the Linux system.
To overwrite the contents of the file and make it unrecoverable, we use the shred command in the Linux/Unix system using the terminal as shown below.
$ shred file.txt
After executing this command, the file ‘file.txt’ is unrecoverable.
Overwrite the contents of the file and print what is being done in the Linux system.
To overwrite the contents of the file and print what is being done, we use --verbose option with the shred command in the Linux/Unix system using the terminal as shown in below.
vikash@tutorialspoint:~/shadow$ shred --verbose file.txt
shred: file.txt: pass 1/3 (random)...
shred: file.txt: pass 2/3 (random)...
shred: file.txt: pass 3/3 (random)...
Overwrite only specific byte of the file in the Linux system.
To overwrite only specific byte of the file, we use -s option with the shred command in the Linux/Unix system as shown below.
vikash@tutorialspoint:~/shadow$ cat file.txt
Hey, welcome to tutorialspoint...
vikash@tutorialspoint:~/shadow$ shred -s 2 file.txt
vikash@tutorialspoint:~/shadow$ cat file.txt
y, welcome to tutorialspoint...
Display the help of the shred command and exit.
To check more information about the shred command, we use the –help option with the shred command in the Linux system as shown below.
$ shred --help
Conclusion – In this article, we learned to overwrite a file to hide its contents and optionally delete it using the shred command with available options and suitable examples. The rm command also used toremove the file in the Linux system. | [
{
"code": null,
"e": 1159,
"s": 1062,
"text": "To overwrite and file contents in the Linux system, we use the shred command using the terminal."
},
{
"code": null,
"e": 1408,
"s": 1159,
"text": "shred – The shred command is used to securely delete files and devices. This command overwrites a file to hide file contents, and optionally delete the file so that it is very difficult to recover the file for any software in the Linux/Unix system."
},
{
"code": null,
"e": 1740,
"s": 1408,
"text": "As usual, to remove files from the system, we use the rm command using the terminal. After removal files through the rm command, it may be recoverable using the software whereas after removing files through the shred command files are unrecoverable because the shred command overwrites the files three times with multiple patterns."
},
{
"code": null,
"e": 1796,
"s": 1740,
"text": "The general syntax of the shred command is as follows −"
},
{
"code": null,
"e": 1822,
"s": 1796,
"text": "shred [OPTION]... FILE..."
},
{
"code": null,
"e": 1882,
"s": 1822,
"text": "Brief description of option available in the shred command."
},
{
"code": null,
"e": 1964,
"s": 1882,
"text": "Overwrite the contents of the file and make it unrecoverable in the Linux system."
},
{
"code": null,
"e": 2114,
"s": 1964,
"text": "To overwrite the contents of the file and make it unrecoverable, we use the shred command in the Linux/Unix system using the terminal as shown below."
},
{
"code": null,
"e": 2131,
"s": 2114,
"text": "$ shred file.txt"
},
{
"code": null,
"e": 2199,
"s": 2131,
"text": "After executing this command, the file ‘file.txt’ is unrecoverable."
},
{
"code": null,
"e": 2284,
"s": 2199,
"text": "Overwrite the contents of the file and print what is being done in the Linux system."
},
{
"code": null,
"e": 2462,
"s": 2284,
"text": "To overwrite the contents of the file and print what is being done, we use --verbose option with the shred command in the Linux/Unix system using the terminal as shown in below."
},
{
"code": null,
"e": 2633,
"s": 2462,
"text": "vikash@tutorialspoint:~/shadow$ shred --verbose file.txt\nshred: file.txt: pass 1/3 (random)...\nshred: file.txt: pass 2/3 (random)...\nshred: file.txt: pass 3/3 (random)..."
},
{
"code": null,
"e": 2695,
"s": 2633,
"text": "Overwrite only specific byte of the file in the Linux system."
},
{
"code": null,
"e": 2821,
"s": 2695,
"text": "To overwrite only specific byte of the file, we use -s option with the shred command in the Linux/Unix system as shown below."
},
{
"code": null,
"e": 3029,
"s": 2821,
"text": "vikash@tutorialspoint:~/shadow$ cat file.txt\nHey, welcome to tutorialspoint...\nvikash@tutorialspoint:~/shadow$ shred -s 2 file.txt\nvikash@tutorialspoint:~/shadow$ cat file.txt\ny, welcome to tutorialspoint..."
},
{
"code": null,
"e": 3077,
"s": 3029,
"text": "Display the help of the shred command and exit."
},
{
"code": null,
"e": 3211,
"s": 3077,
"text": "To check more information about the shred command, we use the –help option with the shred command in the Linux system as shown below."
},
{
"code": null,
"e": 3226,
"s": 3211,
"text": "$ shred --help"
},
{
"code": null,
"e": 3467,
"s": 3226,
"text": "Conclusion – In this article, we learned to overwrite a file to hide its contents and optionally delete it using the shred command with available options and suitable examples. The rm command also used toremove the file in the Linux system."
}
] |
5 New Features in pandas 1.0 You Should Know About | by Roman Orac | Towards Data Science | pandas 1.0 was released on January 29, 2020. The version jumped from 0.25 to 1.0 there aren’t any drastic changes as some pandas users expect. The version increase merely echoes the maturity of the data processing library.
While there aren’t many groundbreaking changes, there are a few that you should know about.
Here are a few links that might interest you:
- Labeling and Data Engineering for Conversational AI and Analytics- Data Science for Business Leaders [Course]- Intro to Machine Learning with PyTorch [Course]- Become a Growth Product Manager [Course]- Deep Learning (Adaptive Computation and ML series) [Ebook]- Free skill tests for Data Scientists & Machine Learning Engineers
Some of the links above are affiliate links and if you go through them to make a purchase I’ll earn a commission. Keep in mind that I link courses because of their quality and not because of the commission I receive from your purchases.
To Step Up Your Pandas Game, read:
towardsdatascience.com
Rolling window functions are very useful when working with time-series data (eg. calculation of moving average). The previous version of pandas required that we pass the window size parameter, eg. calculate moving average on 3 periods. With pandas 1.0 we can bypass this requirement as we show in the example below.
Let’s calculate the moving average of values until the current number is not greater than 10. First, we create a DataFrame with 3 values greater or equal than 10.
df = pd.DataFrame({'col1': [1, 2, 3, 10, 2, 3, 11, 2, 3, 12, 1, 2]})df
Window function should expand until a value greater or equal to 10 is not reached.
use_expanding = (df.col1 >= 10).tolist()use_expanding # output[False, False, False, True, False, False, True, False, False, True, False, False]
For dynamic size window functions, we need to implement a custom indexer, which inherits from pandas BaseIndexer class. BaseIndexer class has a get_window_bounds function, which calculates the start and end for each window.
from pandas.api.indexers import BaseIndexerclass CustomIndexer(BaseIndexer): def get_window_bounds(self, num_values, min_periods, center, closed): start = np.empty(num_values, dtype=np.int64) end = np.empty(num_values, dtype=np.int64) start_i = 0 for i in range(num_values): if self.use_expanding[i]: start[i] = start_i start_i = end[i] = i + 1 else: start[i] = start_i end[i] = i + self.window_size print('start', start) print('end', end) return start, endindexer = CustomIndexer(window_size=1, use_expanding=use_expanding)
We put the indexer class in the rolling function and we calculate the mean for each window. We can also observe the start and the end indices of each window.
df.rolling(indexer).mean()
Pandas uses Cython as a default execution engine with rolling apply. In pandas 1.0, we can specify Numba as an execution engine and get a decent speedup.
There are a few things to note:
Numba dependency needs to be installed: pip install numba,
the first time a function is run using the Numba engine will be slow as Numba will have some function compilation overhead. However, rolling objects will cache the function and subsequent calls will be fast,
the Numba engine is performant with a larger amount of data points (e.g. 1+ million),
the raw argument needs to be set to True, which means that the function will receive numpy objects instead of pandas Series to achieve better performance.
Let’s create a DataFrame with 1 million values.
df = pd.DataFrame({"col1": pd.Series(range(1_000_000))})df.head()
some_function calculates the sum of values and adds 5.
def some_function(x): return np.sum(x) + 5
Let’s measure execution time with the Cython execution engine.
%%timeitdf.col1.rolling(100).apply(some_function, engine='cython', raw=True)4.03 s ± 76.3 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
Cython needed 4.03 seconds to calculate the function. Is Numba faster? Let’s try it.
%%timeitdf.col1.rolling(100).apply(some_function, engine='numba', raw=True)500 ms ± 11.5 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
We see that Numba is 8 times faster with this toy example.
pandas 1.0 introduces a new experimental pd.NA value to represent scalar missing values.
I know what you are thinking — yet another null value? There are nan, None and NaT already!
The goal of pd.NA is to provide consistency across data types. It is currently used by the Int64, boolean and the new string data type
Let’s create a Series of integers with None.
s = pd.Series([3, 6, 9, None], dtype="Int64")s
What surprises me is that the NA == NA produces NA while np.nan == np.nan produces False.
s.loc[3] == s.loc[3]# output<NA>np.nan == np.nan# outputFalse
pandas 1.0 has finally a dedicated (experimental) string type. Before 1.0, strings were stored as objects, so we couldn’t be sure if the series contains just strings or it is mixed with other data types as I demonstrate below.
s = pd.Series(['an', 'ban', 'pet', 'podgan', None])s
Storing strings as objects become a problem, when we unintentionally mix them with integers or floats — data type stays object.
s = pd.Series(['an', 'ban', 5, 'pet', 5.0, 'podgan', None])s
To test the new string dtype we need to set dtype=’string’.
New string data type returns an exception with integers or floats in the series. Great improvement!
s = pd.Series(['an', 'ban', 'pet', 'podgan', None], dtype='string')s
When we sort a DataFrame by a certain column, the index also gets sorted. Sometimes we don’t want that. In pandas 1.0, sort_values function takes ignore index, which does as the name of the argument suggests.
df = pd.DataFrame({"col1": [1, 3, 5, 2, 3, 7, 1, 2]})df.sort_values('col1')
df.sort_values('col1', ignore_index=True)
These were the 5 most interesting pandas features based on my opinion. In the long term, new NA for missing values could bring a lot of clarity to pandas. Eg. how functions handle missing values, do they skip them or not.
There is also a change in deprecation policy:
deprecations will be introduced in minor releases (e.g. 1.1.0),
deprecations and API-breaking changes will be enforced in major releases (e.g. 2.0.0). Should we upgrade or stay with the current pandas version
The new deprecation policy makes this question: “should I update pandas?” easier to answer. It also seems that we can expect more frequent major releases in the future. To learn more about new features in pandas 1.0 read What’s new in 1.0.0.
Follow me on Twitter, where I regularly tweet about Data Science and Machine Learning. | [
{
"code": null,
"e": 394,
"s": 171,
"text": "pandas 1.0 was released on January 29, 2020. The version jumped from 0.25 to 1.0 there aren’t any drastic changes as some pandas users expect. The version increase merely echoes the maturity of the data processing library."
},
{
"code": null,
"e": 486,
"s": 394,
"text": "While there aren’t many groundbreaking changes, there are a few that you should know about."
},
{
"code": null,
"e": 532,
"s": 486,
"text": "Here are a few links that might interest you:"
},
{
"code": null,
"e": 862,
"s": 532,
"text": "- Labeling and Data Engineering for Conversational AI and Analytics- Data Science for Business Leaders [Course]- Intro to Machine Learning with PyTorch [Course]- Become a Growth Product Manager [Course]- Deep Learning (Adaptive Computation and ML series) [Ebook]- Free skill tests for Data Scientists & Machine Learning Engineers"
},
{
"code": null,
"e": 1099,
"s": 862,
"text": "Some of the links above are affiliate links and if you go through them to make a purchase I’ll earn a commission. Keep in mind that I link courses because of their quality and not because of the commission I receive from your purchases."
},
{
"code": null,
"e": 1134,
"s": 1099,
"text": "To Step Up Your Pandas Game, read:"
},
{
"code": null,
"e": 1157,
"s": 1134,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 1473,
"s": 1157,
"text": "Rolling window functions are very useful when working with time-series data (eg. calculation of moving average). The previous version of pandas required that we pass the window size parameter, eg. calculate moving average on 3 periods. With pandas 1.0 we can bypass this requirement as we show in the example below."
},
{
"code": null,
"e": 1636,
"s": 1473,
"text": "Let’s calculate the moving average of values until the current number is not greater than 10. First, we create a DataFrame with 3 values greater or equal than 10."
},
{
"code": null,
"e": 1707,
"s": 1636,
"text": "df = pd.DataFrame({'col1': [1, 2, 3, 10, 2, 3, 11, 2, 3, 12, 1, 2]})df"
},
{
"code": null,
"e": 1790,
"s": 1707,
"text": "Window function should expand until a value greater or equal to 10 is not reached."
},
{
"code": null,
"e": 1935,
"s": 1790,
"text": "use_expanding = (df.col1 >= 10).tolist()use_expanding # output[False, False, False, True, False, False, True, False, False, True, False, False]"
},
{
"code": null,
"e": 2159,
"s": 1935,
"text": "For dynamic size window functions, we need to implement a custom indexer, which inherits from pandas BaseIndexer class. BaseIndexer class has a get_window_bounds function, which calculates the start and end for each window."
},
{
"code": null,
"e": 2818,
"s": 2159,
"text": "from pandas.api.indexers import BaseIndexerclass CustomIndexer(BaseIndexer): def get_window_bounds(self, num_values, min_periods, center, closed): start = np.empty(num_values, dtype=np.int64) end = np.empty(num_values, dtype=np.int64) start_i = 0 for i in range(num_values): if self.use_expanding[i]: start[i] = start_i start_i = end[i] = i + 1 else: start[i] = start_i end[i] = i + self.window_size print('start', start) print('end', end) return start, endindexer = CustomIndexer(window_size=1, use_expanding=use_expanding)"
},
{
"code": null,
"e": 2976,
"s": 2818,
"text": "We put the indexer class in the rolling function and we calculate the mean for each window. We can also observe the start and the end indices of each window."
},
{
"code": null,
"e": 3003,
"s": 2976,
"text": "df.rolling(indexer).mean()"
},
{
"code": null,
"e": 3157,
"s": 3003,
"text": "Pandas uses Cython as a default execution engine with rolling apply. In pandas 1.0, we can specify Numba as an execution engine and get a decent speedup."
},
{
"code": null,
"e": 3189,
"s": 3157,
"text": "There are a few things to note:"
},
{
"code": null,
"e": 3248,
"s": 3189,
"text": "Numba dependency needs to be installed: pip install numba,"
},
{
"code": null,
"e": 3456,
"s": 3248,
"text": "the first time a function is run using the Numba engine will be slow as Numba will have some function compilation overhead. However, rolling objects will cache the function and subsequent calls will be fast,"
},
{
"code": null,
"e": 3542,
"s": 3456,
"text": "the Numba engine is performant with a larger amount of data points (e.g. 1+ million),"
},
{
"code": null,
"e": 3697,
"s": 3542,
"text": "the raw argument needs to be set to True, which means that the function will receive numpy objects instead of pandas Series to achieve better performance."
},
{
"code": null,
"e": 3745,
"s": 3697,
"text": "Let’s create a DataFrame with 1 million values."
},
{
"code": null,
"e": 3811,
"s": 3745,
"text": "df = pd.DataFrame({\"col1\": pd.Series(range(1_000_000))})df.head()"
},
{
"code": null,
"e": 3866,
"s": 3811,
"text": "some_function calculates the sum of values and adds 5."
},
{
"code": null,
"e": 3912,
"s": 3866,
"text": "def some_function(x): return np.sum(x) + 5"
},
{
"code": null,
"e": 3975,
"s": 3912,
"text": "Let’s measure execution time with the Cython execution engine."
},
{
"code": null,
"e": 4119,
"s": 3975,
"text": "%%timeitdf.col1.rolling(100).apply(some_function, engine='cython', raw=True)4.03 s ± 76.3 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)"
},
{
"code": null,
"e": 4204,
"s": 4119,
"text": "Cython needed 4.03 seconds to calculate the function. Is Numba faster? Let’s try it."
},
{
"code": null,
"e": 4347,
"s": 4204,
"text": "%%timeitdf.col1.rolling(100).apply(some_function, engine='numba', raw=True)500 ms ± 11.5 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)"
},
{
"code": null,
"e": 4406,
"s": 4347,
"text": "We see that Numba is 8 times faster with this toy example."
},
{
"code": null,
"e": 4495,
"s": 4406,
"text": "pandas 1.0 introduces a new experimental pd.NA value to represent scalar missing values."
},
{
"code": null,
"e": 4587,
"s": 4495,
"text": "I know what you are thinking — yet another null value? There are nan, None and NaT already!"
},
{
"code": null,
"e": 4722,
"s": 4587,
"text": "The goal of pd.NA is to provide consistency across data types. It is currently used by the Int64, boolean and the new string data type"
},
{
"code": null,
"e": 4767,
"s": 4722,
"text": "Let’s create a Series of integers with None."
},
{
"code": null,
"e": 4814,
"s": 4767,
"text": "s = pd.Series([3, 6, 9, None], dtype=\"Int64\")s"
},
{
"code": null,
"e": 4904,
"s": 4814,
"text": "What surprises me is that the NA == NA produces NA while np.nan == np.nan produces False."
},
{
"code": null,
"e": 4966,
"s": 4904,
"text": "s.loc[3] == s.loc[3]# output<NA>np.nan == np.nan# outputFalse"
},
{
"code": null,
"e": 5193,
"s": 4966,
"text": "pandas 1.0 has finally a dedicated (experimental) string type. Before 1.0, strings were stored as objects, so we couldn’t be sure if the series contains just strings or it is mixed with other data types as I demonstrate below."
},
{
"code": null,
"e": 5246,
"s": 5193,
"text": "s = pd.Series(['an', 'ban', 'pet', 'podgan', None])s"
},
{
"code": null,
"e": 5374,
"s": 5246,
"text": "Storing strings as objects become a problem, when we unintentionally mix them with integers or floats — data type stays object."
},
{
"code": null,
"e": 5435,
"s": 5374,
"text": "s = pd.Series(['an', 'ban', 5, 'pet', 5.0, 'podgan', None])s"
},
{
"code": null,
"e": 5495,
"s": 5435,
"text": "To test the new string dtype we need to set dtype=’string’."
},
{
"code": null,
"e": 5595,
"s": 5495,
"text": "New string data type returns an exception with integers or floats in the series. Great improvement!"
},
{
"code": null,
"e": 5664,
"s": 5595,
"text": "s = pd.Series(['an', 'ban', 'pet', 'podgan', None], dtype='string')s"
},
{
"code": null,
"e": 5873,
"s": 5664,
"text": "When we sort a DataFrame by a certain column, the index also gets sorted. Sometimes we don’t want that. In pandas 1.0, sort_values function takes ignore index, which does as the name of the argument suggests."
},
{
"code": null,
"e": 5949,
"s": 5873,
"text": "df = pd.DataFrame({\"col1\": [1, 3, 5, 2, 3, 7, 1, 2]})df.sort_values('col1')"
},
{
"code": null,
"e": 5991,
"s": 5949,
"text": "df.sort_values('col1', ignore_index=True)"
},
{
"code": null,
"e": 6213,
"s": 5991,
"text": "These were the 5 most interesting pandas features based on my opinion. In the long term, new NA for missing values could bring a lot of clarity to pandas. Eg. how functions handle missing values, do they skip them or not."
},
{
"code": null,
"e": 6259,
"s": 6213,
"text": "There is also a change in deprecation policy:"
},
{
"code": null,
"e": 6323,
"s": 6259,
"text": "deprecations will be introduced in minor releases (e.g. 1.1.0),"
},
{
"code": null,
"e": 6468,
"s": 6323,
"text": "deprecations and API-breaking changes will be enforced in major releases (e.g. 2.0.0). Should we upgrade or stay with the current pandas version"
},
{
"code": null,
"e": 6710,
"s": 6468,
"text": "The new deprecation policy makes this question: “should I update pandas?” easier to answer. It also seems that we can expect more frequent major releases in the future. To learn more about new features in pandas 1.0 read What’s new in 1.0.0."
}
] |
Generate a random array of integers in Java | In order to generate random array of integers in Java, we use the nextInt() method of the java.util.Random class. This returns the next random integer value from this random number generator sequence.
Declaration − The java.util.Random.nextInt() method is declared as follows −
public int nextInt()
Let us see a program to generate a random array of integers in Java −
Live Demo
import java.util.Random;
public class Example {
public static void main(String[] args) {
Random rd = new Random(); // creating Random object
int[] arr = new int[5];
for (int i = 0; i < arr.length; i++) {
arr[i] = rd.nextInt(); // storing random integers in an array
System.out.println(arr[i]); // printing each array element
}
}
}
-1848681552
39846826
858647196
1805220077
-360491047
Note − The output might vary on Online Compilers.
Here we use the nextInt() method in a loop to get a random integer for each element.
for (int i = 0; i < arr.length; i++)
arr[i] = rd.nextInt(); | [
{
"code": null,
"e": 1263,
"s": 1062,
"text": "In order to generate random array of integers in Java, we use the nextInt() method of the java.util.Random class. This returns the next random integer value from this random number generator sequence."
},
{
"code": null,
"e": 1340,
"s": 1263,
"text": "Declaration − The java.util.Random.nextInt() method is declared as follows −"
},
{
"code": null,
"e": 1361,
"s": 1340,
"text": "public int nextInt()"
},
{
"code": null,
"e": 1431,
"s": 1361,
"text": "Let us see a program to generate a random array of integers in Java −"
},
{
"code": null,
"e": 1442,
"s": 1431,
"text": " Live Demo"
},
{
"code": null,
"e": 1821,
"s": 1442,
"text": "import java.util.Random;\npublic class Example {\n public static void main(String[] args) {\n Random rd = new Random(); // creating Random object\n int[] arr = new int[5];\n for (int i = 0; i < arr.length; i++) {\n arr[i] = rd.nextInt(); // storing random integers in an array\n System.out.println(arr[i]); // printing each array element\n }\n }\n}"
},
{
"code": null,
"e": 1874,
"s": 1821,
"text": "-1848681552\n39846826\n858647196\n1805220077\n-360491047"
},
{
"code": null,
"e": 1924,
"s": 1874,
"text": "Note − The output might vary on Online Compilers."
},
{
"code": null,
"e": 2009,
"s": 1924,
"text": "Here we use the nextInt() method in a loop to get a random integer for each element."
},
{
"code": null,
"e": 2069,
"s": 2009,
"text": "for (int i = 0; i < arr.length; i++)\narr[i] = rd.nextInt();"
}
] |
Index with Minimum sum of prefix and suffix sums in an Array | 06 Nov, 2021
Given an array of integers. The task is to find the index in the array at which the value of prefixSum(i) + suffixSum(i) is minimum.Note:
PrefixSum(i) = The sum of first i numbers of the array.
SuffixSum(i) = the sum of last N – i + 1 numbers of the array.
1-based indexing is considered for the array. That is an index of the first element in the array is 1.
Examples:
Input : arr[] = {3, 5, 1, 6, 6 }
Output : 3
Explanation:
Presum[] = {3, 8, 9, 15, 21}
Postsum[] = { 21, 18, 13, 12, 6}
Presum[] + Postsum[] = {24, 26, 22, 27, 27}
It is clear that the min value of sum of
prefix and suffix sum is 22 at index 3.
Input : arr[] = { 3, 2, 5, 7, 3 }
Output : 2
Given that we need to minimize the value of PrefixSum[i] + SuffixSum[i]. That is sum of first elements and elements from end. If observed carefully, it can be seen that:
PrefixSum[i] + SuffixSum[i] = Sum of all elements in array + arr[i](Element at i-th index)
Since sum of all elements of the array will be the same for every index, therefore the value of PrefixSum[i] + SuffixSum[i] will be minimum for the minimum value of arr[i]. Therefore, the task reduces to find only the index of the minimum element of the array.Below is the implementation of the above approach:
C++
Java
Python 3
C#
PHP
Javascript
// C++ program to find the index with// minimum sum of prefix and suffix// sums in an Array #include <bits/stdc++.h>using namespace std; int indexMinSum(int arr[], int n){ // Initialization of the min value int min = arr[0]; int index = 0; // Find minimum element in the array for (int i = 1; i < n; i++) { if (arr[i] < min) { // store the index of the // current minimum element min = arr[i]; index = i; } } // return the index of min element // 1-based index return index + 1;} // Driver Codeint main(){ int arr[] = { 6, 8, 2, 3, 5 }; int n = sizeof(arr) / sizeof(arr[0]); cout << indexMinSum(arr, n); return 0;}
// Java program to find the index with// minimum sum of prefix and suffix// sums in an Array import java.io.*; class GFG { static int indexMinSum(int arr[], int n){ // Initialization of the min value int min = arr[0]; int index = 0; // Find minimum element in the array for (int i = 1; i < n; i++) { if (arr[i] < min) { // store the index of the // current minimum element min = arr[i]; index = i; } } // return the index of min element // 1-based index return index + 1;} // Driver Code public static void main (String[] args) { int arr[] = { 6, 8, 2, 3, 5 }; int n =arr.length; System.out.println( indexMinSum(arr, n)); }}// This code is contributed by inder_verma..
# Python 3 program to find the index with# minimum sum of prefix and suffix# sums in an Array def indexMinSum(arr, n): # Initialization of the min value min = arr[0] index = 0 # Find minimum element in the array for i in range(1, n) : if (arr[i] < min) : # store the index of the # current minimum element min = arr[i] index = i # return the index of min element # 1-based index return index + 1 # Driver Codeif __name__ == "__main__": arr = [ 6, 8, 2, 3, 5 ] n = len(arr) print(indexMinSum(arr, n)) # This code is contributed by ita_c
// C# program to find the index with// minimum sum of prefix and suffix// sums in an Array using System;class GFG{ static int indexMinSum(int []arr, int n) { // Initialization of the min value int min = arr[0]; int index = 0; // Find minimum element in the array for (int i = 1; i < n; i++) { if (arr[i] < min) { // store the index of the // current minimum element min = arr[i]; index = i; } } // return the index of min element // 1-based index return index + 1; } // Driver Code static void Main() { int []arr = { 6, 8, 2, 3, 5 }; int n =arr.Length; Console.WriteLine(indexMinSum(arr, n)); } // This code is contributed by ANKITRAI1}
<?php// PHP program to find the index with// minimum sum of prefix and suffix// sums in an Arrayfunction indexMinSum($arr, $n){ // Initialization of the // min value $min = $arr[0]; $index = 0; // Find minimum element in // the array for ($i = 1; $i < $n; $i++) { if ($arr[$i] < $min) { // store the index of the // current minimum element $min = $arr[$i]; $index = $i; } } // return the index of min // element 1-based index return ($index + 1);} // Driver Code$arr = array(6, 8, 2, 3, 5 );$n = sizeof($arr);echo indexMinSum($arr, $n); // This code is contributed by Sachin?>
<script> // JavaScript program to find the index with// minimum sum of prefix and suffix// sums in an Array function indexMinSum(arr,n) { // Initialization of the min value let min = arr[0]; let index = 0; // Find minimum element in the array for (let i = 1; i < n; i++) { if (arr[i] < min) { // store the index of the // current minimum element min = arr[i]; index = i; } } // return the index of min element // 1-based index return index + 1; } // Driver Code let arr=[6, 8, 2, 3, 5]; let n =arr.length; document.write( indexMinSum(arr, n)); // This code is contributed by avanitrachhadiya2155 </script>
3
Time Complexity: O(N)
Auxiliary Space: O(1)
inderDuMCA
ankthon
Sach_Code
ukasp
avanitrachhadiya2155
rohan07
array-traversal-question
prefix-sum
Arrays
prefix-sum
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n06 Nov, 2021"
},
{
"code": null,
"e": 193,
"s": 53,
"text": "Given an array of integers. The task is to find the index in the array at which the value of prefixSum(i) + suffixSum(i) is minimum.Note: "
},
{
"code": null,
"e": 249,
"s": 193,
"text": "PrefixSum(i) = The sum of first i numbers of the array."
},
{
"code": null,
"e": 312,
"s": 249,
"text": "SuffixSum(i) = the sum of last N – i + 1 numbers of the array."
},
{
"code": null,
"e": 415,
"s": 312,
"text": "1-based indexing is considered for the array. That is an index of the first element in the array is 1."
},
{
"code": null,
"e": 429,
"s": 417,
"text": "Examples: "
},
{
"code": null,
"e": 720,
"s": 429,
"text": "Input : arr[] = {3, 5, 1, 6, 6 }\nOutput : 3\nExplanation: \nPresum[] = {3, 8, 9, 15, 21}\nPostsum[] = { 21, 18, 13, 12, 6}\nPresum[] + Postsum[] = {24, 26, 22, 27, 27}\nIt is clear that the min value of sum of\nprefix and suffix sum is 22 at index 3.\n\nInput : arr[] = { 3, 2, 5, 7, 3 }\nOutput : 2"
},
{
"code": null,
"e": 894,
"s": 722,
"text": "Given that we need to minimize the value of PrefixSum[i] + SuffixSum[i]. That is sum of first elements and elements from end. If observed carefully, it can be seen that: "
},
{
"code": null,
"e": 987,
"s": 894,
"text": "PrefixSum[i] + SuffixSum[i] = Sum of all elements in array + arr[i](Element at i-th index) "
},
{
"code": null,
"e": 1300,
"s": 987,
"text": "Since sum of all elements of the array will be the same for every index, therefore the value of PrefixSum[i] + SuffixSum[i] will be minimum for the minimum value of arr[i]. Therefore, the task reduces to find only the index of the minimum element of the array.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1304,
"s": 1300,
"text": "C++"
},
{
"code": null,
"e": 1309,
"s": 1304,
"text": "Java"
},
{
"code": null,
"e": 1318,
"s": 1309,
"text": "Python 3"
},
{
"code": null,
"e": 1321,
"s": 1318,
"text": "C#"
},
{
"code": null,
"e": 1325,
"s": 1321,
"text": "PHP"
},
{
"code": null,
"e": 1336,
"s": 1325,
"text": "Javascript"
},
{
"code": "// C++ program to find the index with// minimum sum of prefix and suffix// sums in an Array #include <bits/stdc++.h>using namespace std; int indexMinSum(int arr[], int n){ // Initialization of the min value int min = arr[0]; int index = 0; // Find minimum element in the array for (int i = 1; i < n; i++) { if (arr[i] < min) { // store the index of the // current minimum element min = arr[i]; index = i; } } // return the index of min element // 1-based index return index + 1;} // Driver Codeint main(){ int arr[] = { 6, 8, 2, 3, 5 }; int n = sizeof(arr) / sizeof(arr[0]); cout << indexMinSum(arr, n); return 0;}",
"e": 2051,
"s": 1336,
"text": null
},
{
"code": "// Java program to find the index with// minimum sum of prefix and suffix// sums in an Array import java.io.*; class GFG { static int indexMinSum(int arr[], int n){ // Initialization of the min value int min = arr[0]; int index = 0; // Find minimum element in the array for (int i = 1; i < n; i++) { if (arr[i] < min) { // store the index of the // current minimum element min = arr[i]; index = i; } } // return the index of min element // 1-based index return index + 1;} // Driver Code public static void main (String[] args) { int arr[] = { 6, 8, 2, 3, 5 }; int n =arr.length; System.out.println( indexMinSum(arr, n)); }}// This code is contributed by inder_verma..",
"e": 2823,
"s": 2051,
"text": null
},
{
"code": "# Python 3 program to find the index with# minimum sum of prefix and suffix# sums in an Array def indexMinSum(arr, n): # Initialization of the min value min = arr[0] index = 0 # Find minimum element in the array for i in range(1, n) : if (arr[i] < min) : # store the index of the # current minimum element min = arr[i] index = i # return the index of min element # 1-based index return index + 1 # Driver Codeif __name__ == \"__main__\": arr = [ 6, 8, 2, 3, 5 ] n = len(arr) print(indexMinSum(arr, n)) # This code is contributed by ita_c",
"e": 3452,
"s": 2823,
"text": null
},
{
"code": "// C# program to find the index with// minimum sum of prefix and suffix// sums in an Array using System;class GFG{ static int indexMinSum(int []arr, int n) { // Initialization of the min value int min = arr[0]; int index = 0; // Find minimum element in the array for (int i = 1; i < n; i++) { if (arr[i] < min) { // store the index of the // current minimum element min = arr[i]; index = i; } } // return the index of min element // 1-based index return index + 1; } // Driver Code static void Main() { int []arr = { 6, 8, 2, 3, 5 }; int n =arr.Length; Console.WriteLine(indexMinSum(arr, n)); } // This code is contributed by ANKITRAI1}",
"e": 4304,
"s": 3452,
"text": null
},
{
"code": "<?php// PHP program to find the index with// minimum sum of prefix and suffix// sums in an Arrayfunction indexMinSum($arr, $n){ // Initialization of the // min value $min = $arr[0]; $index = 0; // Find minimum element in // the array for ($i = 1; $i < $n; $i++) { if ($arr[$i] < $min) { // store the index of the // current minimum element $min = $arr[$i]; $index = $i; } } // return the index of min // element 1-based index return ($index + 1);} // Driver Code$arr = array(6, 8, 2, 3, 5 );$n = sizeof($arr);echo indexMinSum($arr, $n); // This code is contributed by Sachin?>",
"e": 4985,
"s": 4304,
"text": null
},
{
"code": "<script> // JavaScript program to find the index with// minimum sum of prefix and suffix// sums in an Array function indexMinSum(arr,n) { // Initialization of the min value let min = arr[0]; let index = 0; // Find minimum element in the array for (let i = 1; i < n; i++) { if (arr[i] < min) { // store the index of the // current minimum element min = arr[i]; index = i; } } // return the index of min element // 1-based index return index + 1; } // Driver Code let arr=[6, 8, 2, 3, 5]; let n =arr.length; document.write( indexMinSum(arr, n)); // This code is contributed by avanitrachhadiya2155 </script>",
"e": 5720,
"s": 4985,
"text": null
},
{
"code": null,
"e": 5722,
"s": 5720,
"text": "3"
},
{
"code": null,
"e": 5746,
"s": 5724,
"text": "Time Complexity: O(N)"
},
{
"code": null,
"e": 5768,
"s": 5746,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 5779,
"s": 5768,
"text": "inderDuMCA"
},
{
"code": null,
"e": 5787,
"s": 5779,
"text": "ankthon"
},
{
"code": null,
"e": 5797,
"s": 5787,
"text": "Sach_Code"
},
{
"code": null,
"e": 5803,
"s": 5797,
"text": "ukasp"
},
{
"code": null,
"e": 5824,
"s": 5803,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 5832,
"s": 5824,
"text": "rohan07"
},
{
"code": null,
"e": 5857,
"s": 5832,
"text": "array-traversal-question"
},
{
"code": null,
"e": 5868,
"s": 5857,
"text": "prefix-sum"
},
{
"code": null,
"e": 5875,
"s": 5868,
"text": "Arrays"
},
{
"code": null,
"e": 5886,
"s": 5875,
"text": "prefix-sum"
},
{
"code": null,
"e": 5893,
"s": 5886,
"text": "Arrays"
}
] |
How to plot data from a text file using Matplotlib? | 13 Jan, 2022
Perquisites: Matplotlib, NumPy
In this article, we will see how to load data files for Matplotlib. Matplotlib is a 2D Python library used for Date Visualization. We can plot different types of graphs using the same data like:
Bar Graph
Line Graph
Scatter Graph
Histogram Graph and many.
In this article, we will learn how we can load data from a file to make a graph using the “Matplotlib” python module. Here we will also discuss two different ways to extract data from a file. In the First Module, we will discuss extracting data using the inbuild CVS module and In the Second Module, we will use a third-party “NumPy” Module to extract data from a file.
Requirement:
A text file from where data should be extracted. Let the file name = GFG.txt
Method 1: In this method, we will extract data using CSV module to load CVS files. Step 1:
Import all required modules.
Python3
import matplotlib.pyplot as pltimport csv
Step 2: Create X and Y variables to store X-axis data and Y-axis data from a text file.
Python3
import matplotlib.pyplot as pltimport csv X = []Y = []
Step 3: Open text file in read mode. Pass ‘file_name’ and delimiter in reader function and store returned data in a new variable.
Python3
import matplotlib.pyplot as pltimport csv X = []Y = [] with open('GFG.txt', 'r') as datafile: plotting = csv.reader(datafile, delimiter=',')
Step 4: Create a loop, that will append the data in X and Y variable.
Python3
import matplotlib.pyplot as pltimport csv X = []Y = [] with open('GFG.txt', 'r') as datafile: plotting = csv.reader(datafile, delimiter=',') for ROWS in plotting: X.append(int(ROWS[0])) Y.append(int(ROWS[1]))
Step 5: Now pass all the parameter in their respective functions.
Python3
import matplotlib.pyplot as pltimport csv X = []Y = [] with open('GFG.txt', 'r') as datafile: plotting = csv.reader(datafile, delimiter=',') for ROWS in plotting: X.append(int(ROWS[0])) Y.append(int(ROWS[1])) plt.plot(X, Y)plt.title('Line Graph using CSV')plt.xlabel('X')plt.ylabel('Y')plt.show()
Output:
Method 2: In this method, we will extract data using numpy module to load files. Here you will notice that Step 2,3 and 4 are replaced by np.loadtxt( )
Python3
import matplotlib.pyplot as pltimport numpy as np X, Y = np.loadtxt('GFG.txt', delimiter=',', unpack=True) plt.bar(X, Y)plt.title('Line Graph using NUMPY')plt.xlabel('X')plt.ylabel('Y')plt.show()
Output:
You can also try other different graphs by just changing 1 line
plt.plot(X,Y) to plt.scatter(X,Y) or plt.plot(X,Y)
Using plt.bar()
Python3
import matplotlib.pyplot as pltimport numpy as np X, Y = np.loadtxt('GFG.txt', delimiter=',', unpack=True) plt.plot(X, Y)plt.title('Line Graph using NUMPY')plt.xlabel('X')plt.ylabel('Y')plt.show()
Output:
Using plt.scatter()
Python3
import matplotlib.pyplot as pltimport numpy as np X, Y = np.loadtxt('GFG.txt', delimiter=',', unpack=True) plt.scatter(X, Y)plt.title('Line Graph using NUMPY')plt.xlabel('X')plt.ylabel('Y')plt.show()
Output:
adnanirshad158
Picked
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n13 Jan, 2022"
},
{
"code": null,
"e": 59,
"s": 28,
"text": "Perquisites: Matplotlib, NumPy"
},
{
"code": null,
"e": 254,
"s": 59,
"text": "In this article, we will see how to load data files for Matplotlib. Matplotlib is a 2D Python library used for Date Visualization. We can plot different types of graphs using the same data like:"
},
{
"code": null,
"e": 264,
"s": 254,
"text": "Bar Graph"
},
{
"code": null,
"e": 275,
"s": 264,
"text": "Line Graph"
},
{
"code": null,
"e": 289,
"s": 275,
"text": "Scatter Graph"
},
{
"code": null,
"e": 315,
"s": 289,
"text": "Histogram Graph and many."
},
{
"code": null,
"e": 687,
"s": 315,
"text": "In this article, we will learn how we can load data from a file to make a graph using the “Matplotlib” python module. Here we will also discuss two different ways to extract data from a file. In the First Module, we will discuss extracting data using the inbuild CVS module and In the Second Module, we will use a third-party “NumPy” Module to extract data from a file. "
},
{
"code": null,
"e": 700,
"s": 687,
"text": "Requirement:"
},
{
"code": null,
"e": 778,
"s": 700,
"text": "A text file from where data should be extracted. Let the file name = GFG.txt"
},
{
"code": null,
"e": 870,
"s": 778,
"text": "Method 1: In this method, we will extract data using CSV module to load CVS files. Step 1:"
},
{
"code": null,
"e": 899,
"s": 870,
"text": "Import all required modules."
},
{
"code": null,
"e": 907,
"s": 899,
"text": "Python3"
},
{
"code": "import matplotlib.pyplot as pltimport csv",
"e": 949,
"s": 907,
"text": null
},
{
"code": null,
"e": 1039,
"s": 949,
"text": "Step 2: Create X and Y variables to store X-axis data and Y-axis data from a text file. "
},
{
"code": null,
"e": 1047,
"s": 1039,
"text": "Python3"
},
{
"code": "import matplotlib.pyplot as pltimport csv X = []Y = []",
"e": 1102,
"s": 1047,
"text": null
},
{
"code": null,
"e": 1233,
"s": 1102,
"text": "Step 3: Open text file in read mode. Pass ‘file_name’ and delimiter in reader function and store returned data in a new variable. "
},
{
"code": null,
"e": 1241,
"s": 1233,
"text": "Python3"
},
{
"code": "import matplotlib.pyplot as pltimport csv X = []Y = [] with open('GFG.txt', 'r') as datafile: plotting = csv.reader(datafile, delimiter=',')",
"e": 1385,
"s": 1241,
"text": null
},
{
"code": null,
"e": 1455,
"s": 1385,
"text": "Step 4: Create a loop, that will append the data in X and Y variable."
},
{
"code": null,
"e": 1463,
"s": 1455,
"text": "Python3"
},
{
"code": "import matplotlib.pyplot as pltimport csv X = []Y = [] with open('GFG.txt', 'r') as datafile: plotting = csv.reader(datafile, delimiter=',') for ROWS in plotting: X.append(int(ROWS[0])) Y.append(int(ROWS[1]))",
"e": 1697,
"s": 1463,
"text": null
},
{
"code": null,
"e": 1763,
"s": 1697,
"text": "Step 5: Now pass all the parameter in their respective functions."
},
{
"code": null,
"e": 1771,
"s": 1763,
"text": "Python3"
},
{
"code": "import matplotlib.pyplot as pltimport csv X = []Y = [] with open('GFG.txt', 'r') as datafile: plotting = csv.reader(datafile, delimiter=',') for ROWS in plotting: X.append(int(ROWS[0])) Y.append(int(ROWS[1])) plt.plot(X, Y)plt.title('Line Graph using CSV')plt.xlabel('X')plt.ylabel('Y')plt.show()",
"e": 2093,
"s": 1771,
"text": null
},
{
"code": null,
"e": 2101,
"s": 2093,
"text": "Output:"
},
{
"code": null,
"e": 2253,
"s": 2101,
"text": "Method 2: In this method, we will extract data using numpy module to load files. Here you will notice that Step 2,3 and 4 are replaced by np.loadtxt( )"
},
{
"code": null,
"e": 2261,
"s": 2253,
"text": "Python3"
},
{
"code": "import matplotlib.pyplot as pltimport numpy as np X, Y = np.loadtxt('GFG.txt', delimiter=',', unpack=True) plt.bar(X, Y)plt.title('Line Graph using NUMPY')plt.xlabel('X')plt.ylabel('Y')plt.show()",
"e": 2457,
"s": 2261,
"text": null
},
{
"code": null,
"e": 2469,
"s": 2461,
"text": "Output:"
},
{
"code": null,
"e": 2537,
"s": 2473,
"text": "You can also try other different graphs by just changing 1 line"
},
{
"code": null,
"e": 2590,
"s": 2539,
"text": "plt.plot(X,Y) to plt.scatter(X,Y) or plt.plot(X,Y)"
},
{
"code": null,
"e": 2606,
"s": 2590,
"text": "Using plt.bar()"
},
{
"code": null,
"e": 2616,
"s": 2608,
"text": "Python3"
},
{
"code": "import matplotlib.pyplot as pltimport numpy as np X, Y = np.loadtxt('GFG.txt', delimiter=',', unpack=True) plt.plot(X, Y)plt.title('Line Graph using NUMPY')plt.xlabel('X')plt.ylabel('Y')plt.show()",
"e": 2813,
"s": 2616,
"text": null
},
{
"code": null,
"e": 2821,
"s": 2813,
"text": "Output:"
},
{
"code": null,
"e": 2841,
"s": 2821,
"text": "Using plt.scatter()"
},
{
"code": null,
"e": 2849,
"s": 2841,
"text": "Python3"
},
{
"code": "import matplotlib.pyplot as pltimport numpy as np X, Y = np.loadtxt('GFG.txt', delimiter=',', unpack=True) plt.scatter(X, Y)plt.title('Line Graph using NUMPY')plt.xlabel('X')plt.ylabel('Y')plt.show()",
"e": 3049,
"s": 2849,
"text": null
},
{
"code": null,
"e": 3061,
"s": 3053,
"text": "Output:"
},
{
"code": null,
"e": 3080,
"s": 3065,
"text": "adnanirshad158"
},
{
"code": null,
"e": 3087,
"s": 3080,
"text": "Picked"
},
{
"code": null,
"e": 3105,
"s": 3087,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 3112,
"s": 3105,
"text": "Python"
}
] |
How to find the current capacity of a list in Python | 01 May, 2020
List in Python is mainly implementation of dynamic sized arrays (like ArrayList in Java or vector in C++). Capacity of a list means number of elements a list can store at a specific time. When we append an element to a list, it will store the element if there is size is less than capacity. If current capacity exceeds, then lists resize and allocate extra space for future insertions (Please see how lists work in Python for details)The formula for finding the capacity of a list and space left in the list:
Here,size of an empty list means how many bits are allocated to an empty list and it varies system to system .size of one block of the list also varies from system to system.
Length of the list means the number of blocks of space which is filled
Example 1:
# program to find capacity of the list import sysl = []size = sys.getsizeof(l)print("size of an empty list :", size) # append an element in the listl.append(1) # calculate total size of the list after appending one elementprint("Now total size of a list :", sys.getsizeof(l)) # calculate capacity of the list after appending one element# Considering block size as 8.capacity = (sys.getsizeof(l)-size)//8print("capacity of the list is:", capacity)print("length of the list is :", len(l)) # calculate space left the list after appending one elementspaceleft = ((sys.getsizeof(l)-size)-len(l)*8)//8print("space left in the list is:", spaceleft)
OUTPUT
size of an empty list : 64
Now total size of a list : 96
capacity of the list is: 4
length of the list is: 1
space left in the list is: 3
Example 2:
# program to find capacity of the listimport sysl = []size = sys.getsizeof(l)print("size of an empty list :", size) # append four element in the listl.append(1)l.append(2)l.append(3)l.append(4) # calculate total size of the list after appending four elementprint("Now total size of a list :", sys.getsizeof(l)) # calculate capacity of the list after appending four elementc = (sys.getsizeof(l)-size)//8print("capacity of the list is:", c)print("length of the list is:", len(l)) # calculate space left the list after appending four elementspaceleft =((sys.getsizeof(l)-size)-len(l)*8)//8print("space left in the list is:", spaceleft)
OUTPUT
size of an empty list : 64
Now total size of a list : 96
capacity of the list is: 4
length of the list is: 4
space left in the list is: 0
Example 3:
# program to find capacity of the listimport sysl = []size = sys.getsizeof(l)print("size of an empty list :", size) # append five element in the listl.append(1)l.append(2)l.append(3)l.append(4)l.append(5) # calculate total size of the list after appending five elementprint("Now total size of a list :", sys.getsizeof(l)) # calculate capacity of the list after appending five elementc = (sys.getsizeof(l)-size)//8print("capacity of the list is:", c)print("length of the list is:", len(l)) # calculate space left the list after appending five elementspaceleft =((sys.getsizeof(l)-size)-len(l)*8)//8print("space left in the list is:", spaceleft)
OUTPUT
size of an empty list : 64
Now total size of a list : 128
capacity of the list is: 8
length of the list is: 5
space left in the list is: 3
python-list
python-list-functions
Python
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 May, 2020"
},
{
"code": null,
"e": 537,
"s": 28,
"text": "List in Python is mainly implementation of dynamic sized arrays (like ArrayList in Java or vector in C++). Capacity of a list means number of elements a list can store at a specific time. When we append an element to a list, it will store the element if there is size is less than capacity. If current capacity exceeds, then lists resize and allocate extra space for future insertions (Please see how lists work in Python for details)The formula for finding the capacity of a list and space left in the list:"
},
{
"code": null,
"e": 712,
"s": 537,
"text": "Here,size of an empty list means how many bits are allocated to an empty list and it varies system to system .size of one block of the list also varies from system to system."
},
{
"code": null,
"e": 783,
"s": 712,
"text": "Length of the list means the number of blocks of space which is filled"
},
{
"code": null,
"e": 794,
"s": 783,
"text": "Example 1:"
},
{
"code": "# program to find capacity of the list import sysl = []size = sys.getsizeof(l)print(\"size of an empty list :\", size) # append an element in the listl.append(1) # calculate total size of the list after appending one elementprint(\"Now total size of a list :\", sys.getsizeof(l)) # calculate capacity of the list after appending one element# Considering block size as 8.capacity = (sys.getsizeof(l)-size)//8print(\"capacity of the list is:\", capacity)print(\"length of the list is :\", len(l)) # calculate space left the list after appending one elementspaceleft = ((sys.getsizeof(l)-size)-len(l)*8)//8print(\"space left in the list is:\", spaceleft)",
"e": 1441,
"s": 794,
"text": null
},
{
"code": null,
"e": 1448,
"s": 1441,
"text": "OUTPUT"
},
{
"code": null,
"e": 1586,
"s": 1448,
"text": "size of an empty list : 64\nNow total size of a list : 96\ncapacity of the list is: 4\nlength of the list is: 1\nspace left in the list is: 3"
},
{
"code": null,
"e": 1597,
"s": 1586,
"text": "Example 2:"
},
{
"code": "# program to find capacity of the listimport sysl = []size = sys.getsizeof(l)print(\"size of an empty list :\", size) # append four element in the listl.append(1)l.append(2)l.append(3)l.append(4) # calculate total size of the list after appending four elementprint(\"Now total size of a list :\", sys.getsizeof(l)) # calculate capacity of the list after appending four elementc = (sys.getsizeof(l)-size)//8print(\"capacity of the list is:\", c)print(\"length of the list is:\", len(l)) # calculate space left the list after appending four elementspaceleft =((sys.getsizeof(l)-size)-len(l)*8)//8print(\"space left in the list is:\", spaceleft)",
"e": 2234,
"s": 1597,
"text": null
},
{
"code": null,
"e": 2241,
"s": 2234,
"text": "OUTPUT"
},
{
"code": null,
"e": 2380,
"s": 2241,
"text": "size of an empty list : 64\nNow total size of a list : 96\ncapacity of the list is: 4\nlength of the list is: 4\nspace left in the list is: 0\n"
},
{
"code": null,
"e": 2391,
"s": 2380,
"text": "Example 3:"
},
{
"code": "# program to find capacity of the listimport sysl = []size = sys.getsizeof(l)print(\"size of an empty list :\", size) # append five element in the listl.append(1)l.append(2)l.append(3)l.append(4)l.append(5) # calculate total size of the list after appending five elementprint(\"Now total size of a list :\", sys.getsizeof(l)) # calculate capacity of the list after appending five elementc = (sys.getsizeof(l)-size)//8print(\"capacity of the list is:\", c)print(\"length of the list is:\", len(l)) # calculate space left the list after appending five elementspaceleft =((sys.getsizeof(l)-size)-len(l)*8)//8print(\"space left in the list is:\", spaceleft)",
"e": 3039,
"s": 2391,
"text": null
},
{
"code": null,
"e": 3046,
"s": 3039,
"text": "OUTPUT"
},
{
"code": null,
"e": 3186,
"s": 3046,
"text": "size of an empty list : 64\nNow total size of a list : 128\ncapacity of the list is: 8\nlength of the list is: 5\nspace left in the list is: 3\n"
},
{
"code": null,
"e": 3198,
"s": 3186,
"text": "python-list"
},
{
"code": null,
"e": 3220,
"s": 3198,
"text": "python-list-functions"
},
{
"code": null,
"e": 3227,
"s": 3220,
"text": "Python"
},
{
"code": null,
"e": 3239,
"s": 3227,
"text": "python-list"
}
] |
vector max_size() function in C++ STL | 09 Jun, 2022
The vector::max_size() is a built-in function in C++ STL which returns the maximum number of elements that can be held by the vector container. Syntax:
vector_name.max_size()
Parameters: The function does not accept any parameters. Return value: The function returns the maximum numbers that can fit into the vector container. Time Complexity – Constant O(1)
Program below illustrates the above function:
CPP
// C++ program to illustrate the// vector::max_size() function#include <bits/stdc++.h>using namespace std; int main(){ // initialize a vector vector<int> vec; // returns the max_size of vector cout << "max_size of vector 1 = " << vec.max_size() << endl; vector<int> vec1; // returns the max_size of vector cout << "max_size of vector 2 = " << vec1.max_size() << endl; return 0;}
max_size of vector 1 = 4611686018427387903
max_size of vector 2 = 4611686018427387903
utkarshgupta110092
CPP-Functions
cpp-vector
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n09 Jun, 2022"
},
{
"code": null,
"e": 205,
"s": 53,
"text": "The vector::max_size() is a built-in function in C++ STL which returns the maximum number of elements that can be held by the vector container. Syntax:"
},
{
"code": null,
"e": 228,
"s": 205,
"text": "vector_name.max_size()"
},
{
"code": null,
"e": 413,
"s": 228,
"text": "Parameters: The function does not accept any parameters. Return value: The function returns the maximum numbers that can fit into the vector container. Time Complexity – Constant O(1) "
},
{
"code": null,
"e": 460,
"s": 413,
"text": "Program below illustrates the above function: "
},
{
"code": null,
"e": 464,
"s": 460,
"text": "CPP"
},
{
"code": "// C++ program to illustrate the// vector::max_size() function#include <bits/stdc++.h>using namespace std; int main(){ // initialize a vector vector<int> vec; // returns the max_size of vector cout << \"max_size of vector 1 = \" << vec.max_size() << endl; vector<int> vec1; // returns the max_size of vector cout << \"max_size of vector 2 = \" << vec1.max_size() << endl; return 0;}",
"e": 870,
"s": 464,
"text": null
},
{
"code": null,
"e": 956,
"s": 870,
"text": "max_size of vector 1 = 4611686018427387903\nmax_size of vector 2 = 4611686018427387903"
},
{
"code": null,
"e": 975,
"s": 956,
"text": "utkarshgupta110092"
},
{
"code": null,
"e": 989,
"s": 975,
"text": "CPP-Functions"
},
{
"code": null,
"e": 1000,
"s": 989,
"text": "cpp-vector"
},
{
"code": null,
"e": 1004,
"s": 1000,
"text": "STL"
},
{
"code": null,
"e": 1008,
"s": 1004,
"text": "C++"
},
{
"code": null,
"e": 1012,
"s": 1008,
"text": "STL"
},
{
"code": null,
"e": 1016,
"s": 1012,
"text": "CPP"
}
] |
How to validate if input in input field has alphanumeric characters only using express-validator ? | 27 Dec, 2021
In HTML forms, we often required validation of different types. Validate existing email, validate password length, validate confirm password, validate to allow only integer inputs, these are some examples of validation. In a certain input field, only alphanumeric characters are allowed i.e. there not allowed any special characters. We can also validate these input fields to accept only alphanumeric characters using express-validator middleware.
Command to install express-validator:
npm install express-validator
Steps to use express-validator to implement the logic:
Install express-validator middleware.
Create a validator.js file to code all the validation logic.
Validate input by validateInputField: check(input field name) and chain on the validation isAlphanumeric() with ‘ . ‘
Use the validation name(validateInputField) in the routes as a middleware as an array of validations.
Destructure ‘validationResult’ function from express-validator to use it to find any errors.
If error occurs redirect to the same page passing the error information.
If error list is empty, give access to the user for the subsequent request.
Note: Here we use local or custom database to implement the logic, the same steps can be followed to implement the logic in a regular database like MongoDB or MySql.
Example: This example illustrates how to validate a input field to only allow the alphabets.
Filename – index.js
const express = require('express')const bodyParser = require('body-parser')const {validationResult} = require('express-validator')const repo = require('./repository')const { validateUsername } = require('./validator')const signupTemplet = require('./signup') const app = express()const port = process.env.PORT || 3000 // The body-parser middleware to parse form dataapp.use(bodyParser.urlencoded({extended : true})) // Get route to display HTML form to sign upapp.get('/signup', (req, res) => { res.send(signupTemplet({}))}) // Post route to handle form submission logic and app.post( '/signup', [validateUsername], async (req, res) => { const errors = validationResult(req) if(!errors.isEmpty()) { return res.send(signupTemplet({errors})) } const {email, username, password} = req.body await repo.create({ email, username, password }) res.send('Sign Up successfully')}) // Server setupapp.listen(port, () => { console.log(`Server start on port ${port}`)})
Filename – repository.js: This file contains all the logic to create a local database and interact with it.
// Importing node.js file system module const fs = require('fs') class Repository { constructor(filename) { // Filename where datas are going to store if(!filename) { throw new Error('Filename is required to create a datastore!') } this.filename = filename try { fs.accessSync(this.filename) } catch(err) { // If file not exist it is created with empty array fs.writeFileSync(this.filename, '[]') } } // Get all existing records async getAll(){ return JSON.parse( await fs.promises.readFile(this.filename, { encoding : 'utf8' }) ) } // Create new record async create(attrs){ const records = await this.getAll() records.push(attrs) await fs.promises.writeFile( this.filename, JSON.stringify(records, null, 2) ) return attrs }} // The 'datastore.json' file created at runtime // and all the information provided via signup form// store in this file in JSON format.module.exports = new Repository('datastore.json')
Filename – signup.js: This file contains logic to show sign up form.
const getError = (errors, prop) => { try { return errors.mapped()[prop].msg } catch (error) { return '' } } module.exports = ({errors}) => { return ` <!DOCTYPE html> <html> <head> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.9.0/css/bulma.min.css'> <style> div.columns{ margin-top: 100px; } .button{ margin-top : 10px } </style> </head> <body> <div class='container'> <div class='columns is-centered'> <div class='column is-5'> <h1 class='title'>Sign Up<h1> <form method='POST'> <div> <div> <label class='label' id='email'>Email</label> </div> <input class='input' type='text' name='email' placeholder='Email' for='email'> </div> <div> <div> <label class='label' id='fn'>Username</label> </div> <input class='input' type='text' name='username' placeholder='Username' for='username'> <p class="help is-danger">${getError(errors, 'username')}</p> </div> <div> <div> <label class='label' id='password'>Password</label> </div> <input class='input' type='password' name='password' placeholder='Password' for='password'> </div> <div> <button class='button is-primary'>Sign Up</button> </div> </form> </div> </div> </div> </body> </html> `}
Filename – validator.js: This file contain all the validation logic(Logic to validate a input field to only allow the alphanumeric characters).
const {check} = require('express-validator')const repo = require('./repository')module.exports = { validateUsername : check('username') // To delete leading and trailing space .trim() // Validate minimum length of password // Optional for this context .isLength({min:4}) // Custom message .withMessage('Username must be minimum 4 characters long') // Validate username to be alphanumeric .isAlphanumeric() // Custom message .withMessage('Username must be alphanumeric') }
Filename – package.json
package.json file
Database:
Database
Output:
Attempt to sign up when username input field is not alphanumeric
Response when attempt to sign up with username input field which is not alphanumeric
Attempt to sign up when username input field contains only alphanumeric character
Response when attempt to sign up with username input field which contains only alphanumeric characters
Database after successful Sign Up:
Database after successful Sign Up
Note: We have used some Bulma classes(CSS framework) in the signup.js file to design the content.
kk9826225
Express.js
Node.js-Misc
Node.js
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 Dec, 2021"
},
{
"code": null,
"e": 477,
"s": 28,
"text": "In HTML forms, we often required validation of different types. Validate existing email, validate password length, validate confirm password, validate to allow only integer inputs, these are some examples of validation. In a certain input field, only alphanumeric characters are allowed i.e. there not allowed any special characters. We can also validate these input fields to accept only alphanumeric characters using express-validator middleware."
},
{
"code": null,
"e": 515,
"s": 477,
"text": "Command to install express-validator:"
},
{
"code": null,
"e": 545,
"s": 515,
"text": "npm install express-validator"
},
{
"code": null,
"e": 600,
"s": 545,
"text": "Steps to use express-validator to implement the logic:"
},
{
"code": null,
"e": 638,
"s": 600,
"text": "Install express-validator middleware."
},
{
"code": null,
"e": 699,
"s": 638,
"text": "Create a validator.js file to code all the validation logic."
},
{
"code": null,
"e": 817,
"s": 699,
"text": "Validate input by validateInputField: check(input field name) and chain on the validation isAlphanumeric() with ‘ . ‘"
},
{
"code": null,
"e": 919,
"s": 817,
"text": "Use the validation name(validateInputField) in the routes as a middleware as an array of validations."
},
{
"code": null,
"e": 1012,
"s": 919,
"text": "Destructure ‘validationResult’ function from express-validator to use it to find any errors."
},
{
"code": null,
"e": 1085,
"s": 1012,
"text": "If error occurs redirect to the same page passing the error information."
},
{
"code": null,
"e": 1161,
"s": 1085,
"text": "If error list is empty, give access to the user for the subsequent request."
},
{
"code": null,
"e": 1327,
"s": 1161,
"text": "Note: Here we use local or custom database to implement the logic, the same steps can be followed to implement the logic in a regular database like MongoDB or MySql."
},
{
"code": null,
"e": 1420,
"s": 1327,
"text": "Example: This example illustrates how to validate a input field to only allow the alphabets."
},
{
"code": null,
"e": 1440,
"s": 1420,
"text": "Filename – index.js"
},
{
"code": "const express = require('express')const bodyParser = require('body-parser')const {validationResult} = require('express-validator')const repo = require('./repository')const { validateUsername } = require('./validator')const signupTemplet = require('./signup') const app = express()const port = process.env.PORT || 3000 // The body-parser middleware to parse form dataapp.use(bodyParser.urlencoded({extended : true})) // Get route to display HTML form to sign upapp.get('/signup', (req, res) => { res.send(signupTemplet({}))}) // Post route to handle form submission logic and app.post( '/signup', [validateUsername], async (req, res) => { const errors = validationResult(req) if(!errors.isEmpty()) { return res.send(signupTemplet({errors})) } const {email, username, password} = req.body await repo.create({ email, username, password }) res.send('Sign Up successfully')}) // Server setupapp.listen(port, () => { console.log(`Server start on port ${port}`)})",
"e": 2449,
"s": 1440,
"text": null
},
{
"code": null,
"e": 2557,
"s": 2449,
"text": "Filename – repository.js: This file contains all the logic to create a local database and interact with it."
},
{
"code": "// Importing node.js file system module const fs = require('fs') class Repository { constructor(filename) { // Filename where datas are going to store if(!filename) { throw new Error('Filename is required to create a datastore!') } this.filename = filename try { fs.accessSync(this.filename) } catch(err) { // If file not exist it is created with empty array fs.writeFileSync(this.filename, '[]') } } // Get all existing records async getAll(){ return JSON.parse( await fs.promises.readFile(this.filename, { encoding : 'utf8' }) ) } // Create new record async create(attrs){ const records = await this.getAll() records.push(attrs) await fs.promises.writeFile( this.filename, JSON.stringify(records, null, 2) ) return attrs }} // The 'datastore.json' file created at runtime // and all the information provided via signup form// store in this file in JSON format.module.exports = new Repository('datastore.json')",
"e": 3585,
"s": 2557,
"text": null
},
{
"code": null,
"e": 3654,
"s": 3585,
"text": "Filename – signup.js: This file contains logic to show sign up form."
},
{
"code": "const getError = (errors, prop) => { try { return errors.mapped()[prop].msg } catch (error) { return '' } } module.exports = ({errors}) => { return ` <!DOCTYPE html> <html> <head> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.9.0/css/bulma.min.css'> <style> div.columns{ margin-top: 100px; } .button{ margin-top : 10px } </style> </head> <body> <div class='container'> <div class='columns is-centered'> <div class='column is-5'> <h1 class='title'>Sign Up<h1> <form method='POST'> <div> <div> <label class='label' id='email'>Email</label> </div> <input class='input' type='text' name='email' placeholder='Email' for='email'> </div> <div> <div> <label class='label' id='fn'>Username</label> </div> <input class='input' type='text' name='username' placeholder='Username' for='username'> <p class=\"help is-danger\">${getError(errors, 'username')}</p> </div> <div> <div> <label class='label' id='password'>Password</label> </div> <input class='input' type='password' name='password' placeholder='Password' for='password'> </div> <div> <button class='button is-primary'>Sign Up</button> </div> </form> </div> </div> </div> </body> </html> `}",
"e": 5465,
"s": 3654,
"text": null
},
{
"code": null,
"e": 5609,
"s": 5465,
"text": "Filename – validator.js: This file contain all the validation logic(Logic to validate a input field to only allow the alphanumeric characters)."
},
{
"code": "const {check} = require('express-validator')const repo = require('./repository')module.exports = { validateUsername : check('username') // To delete leading and trailing space .trim() // Validate minimum length of password // Optional for this context .isLength({min:4}) // Custom message .withMessage('Username must be minimum 4 characters long') // Validate username to be alphanumeric .isAlphanumeric() // Custom message .withMessage('Username must be alphanumeric') }",
"e": 6126,
"s": 5609,
"text": null
},
{
"code": null,
"e": 6150,
"s": 6126,
"text": "Filename – package.json"
},
{
"code": null,
"e": 6168,
"s": 6150,
"text": "package.json file"
},
{
"code": null,
"e": 6178,
"s": 6168,
"text": "Database:"
},
{
"code": null,
"e": 6187,
"s": 6178,
"text": "Database"
},
{
"code": null,
"e": 6195,
"s": 6187,
"text": "Output:"
},
{
"code": null,
"e": 6260,
"s": 6195,
"text": "Attempt to sign up when username input field is not alphanumeric"
},
{
"code": null,
"e": 6345,
"s": 6260,
"text": "Response when attempt to sign up with username input field which is not alphanumeric"
},
{
"code": null,
"e": 6427,
"s": 6345,
"text": "Attempt to sign up when username input field contains only alphanumeric character"
},
{
"code": null,
"e": 6530,
"s": 6427,
"text": "Response when attempt to sign up with username input field which contains only alphanumeric characters"
},
{
"code": null,
"e": 6565,
"s": 6530,
"text": "Database after successful Sign Up:"
},
{
"code": null,
"e": 6599,
"s": 6565,
"text": "Database after successful Sign Up"
},
{
"code": null,
"e": 6697,
"s": 6599,
"text": "Note: We have used some Bulma classes(CSS framework) in the signup.js file to design the content."
},
{
"code": null,
"e": 6707,
"s": 6697,
"text": "kk9826225"
},
{
"code": null,
"e": 6718,
"s": 6707,
"text": "Express.js"
},
{
"code": null,
"e": 6731,
"s": 6718,
"text": "Node.js-Misc"
},
{
"code": null,
"e": 6739,
"s": 6731,
"text": "Node.js"
},
{
"code": null,
"e": 6756,
"s": 6739,
"text": "Web Technologies"
},
{
"code": null,
"e": 6783,
"s": 6756,
"text": "Web technologies Questions"
}
] |
JavaScript Array filter() Method | 27 May, 2022
The arr.filter() method is used to create a new array from a given array consisting of only those elements from the given array which satisfy a condition set by the argument method.
Syntax:
array.filter(callback(element, index, arr), thisValue)
Parameters: This method accepts five parameter as mentioned above and described below:
callback: This parameter holds the function to be called for each element of the array.
element: The parameter holds the value of the elements being processed currently.
index: This parameter is optional, it holds the index of the currentValue element in the array starting from 0.
arr: This parameter is optional, it holds the complete array on which Array.every is called.
thisValue: This parameter is optional, it holds the context to be passed as this to be used while executing the callback function. If the context is passed, it will be used like this for each invocation of the callback function, otherwise undefined is used as default.
Return value: This method returns a new array consisting of only those elements that satisfied the condition of the arg_function.
Example1: In this example, the method filter() creates a new array consisting of only those elements that satisfy the condition checked by canVote() function.
JavaScript
<script> // JavaScript to illustrate findIndex() method function canVote(age) { return age >= 18; } function func() { var filtered = [24, 33, 16, 40].filter(canVote); document.write(filtered); } func();</script>
Output:
[24,33,40]
Example 2: In this example, the method filter() creates a new array consisting of only those elements that satisfy the condition checked by isPositive() function.
Javascript
function isPositive(value) { return value > 0;} var filtered = [112, 52, 0, -1, 944].filter(isPositive);print(filtered);
Output:
[112,52,944]
Example 3: In this example, the method filter() creates a new array consisting of only those elements that satisfy the condition checked by isEven() function.
Javascript
function isEven(value) { return value % 2 == 0;} var filtered = [11, 98, 31, 23, 944].filter(isEven);print(filtered);
Output:
[98,944]
Supported Browsers: The browsers supported by JavaScript Array filter() method are listed below:
Google Chrome
Microsoft Edge 9.0
Mozilla Firefox 1.5
Safari
Opera
jain_chirag
arorakashish0911
surbhikumaridav
javascript-array
JavaScript-Methods
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": "\n27 May, 2022"
},
{
"code": null,
"e": 211,
"s": 28,
"text": "The arr.filter() method is used to create a new array from a given array consisting of only those elements from the given array which satisfy a condition set by the argument method. "
},
{
"code": null,
"e": 220,
"s": 211,
"text": "Syntax: "
},
{
"code": null,
"e": 275,
"s": 220,
"text": "array.filter(callback(element, index, arr), thisValue)"
},
{
"code": null,
"e": 363,
"s": 275,
"text": "Parameters: This method accepts five parameter as mentioned above and described below: "
},
{
"code": null,
"e": 451,
"s": 363,
"text": "callback: This parameter holds the function to be called for each element of the array."
},
{
"code": null,
"e": 533,
"s": 451,
"text": "element: The parameter holds the value of the elements being processed currently."
},
{
"code": null,
"e": 645,
"s": 533,
"text": "index: This parameter is optional, it holds the index of the currentValue element in the array starting from 0."
},
{
"code": null,
"e": 738,
"s": 645,
"text": "arr: This parameter is optional, it holds the complete array on which Array.every is called."
},
{
"code": null,
"e": 1007,
"s": 738,
"text": "thisValue: This parameter is optional, it holds the context to be passed as this to be used while executing the callback function. If the context is passed, it will be used like this for each invocation of the callback function, otherwise undefined is used as default."
},
{
"code": null,
"e": 1138,
"s": 1007,
"text": "Return value: This method returns a new array consisting of only those elements that satisfied the condition of the arg_function. "
},
{
"code": null,
"e": 1298,
"s": 1138,
"text": "Example1: In this example, the method filter() creates a new array consisting of only those elements that satisfy the condition checked by canVote() function."
},
{
"code": null,
"e": 1309,
"s": 1298,
"text": "JavaScript"
},
{
"code": "<script> // JavaScript to illustrate findIndex() method function canVote(age) { return age >= 18; } function func() { var filtered = [24, 33, 16, 40].filter(canVote); document.write(filtered); } func();</script> ",
"e": 1580,
"s": 1309,
"text": null
},
{
"code": null,
"e": 1590,
"s": 1580,
"text": "Output: "
},
{
"code": null,
"e": 1601,
"s": 1590,
"text": "[24,33,40]"
},
{
"code": null,
"e": 1765,
"s": 1601,
"text": "Example 2: In this example, the method filter() creates a new array consisting of only those elements that satisfy the condition checked by isPositive() function. "
},
{
"code": null,
"e": 1776,
"s": 1765,
"text": "Javascript"
},
{
"code": "function isPositive(value) { return value > 0;} var filtered = [112, 52, 0, -1, 944].filter(isPositive);print(filtered);",
"e": 1898,
"s": 1776,
"text": null
},
{
"code": null,
"e": 1908,
"s": 1898,
"text": "Output: "
},
{
"code": null,
"e": 1921,
"s": 1908,
"text": "[112,52,944]"
},
{
"code": null,
"e": 2081,
"s": 1921,
"text": "Example 3: In this example, the method filter() creates a new array consisting of only those elements that satisfy the condition checked by isEven() function. "
},
{
"code": null,
"e": 2092,
"s": 2081,
"text": "Javascript"
},
{
"code": "function isEven(value) { return value % 2 == 0;} var filtered = [11, 98, 31, 23, 944].filter(isEven);print(filtered);",
"e": 2211,
"s": 2092,
"text": null
},
{
"code": null,
"e": 2220,
"s": 2211,
"text": "Output: "
},
{
"code": null,
"e": 2229,
"s": 2220,
"text": "[98,944]"
},
{
"code": null,
"e": 2328,
"s": 2229,
"text": "Supported Browsers: The browsers supported by JavaScript Array filter() method are listed below: "
},
{
"code": null,
"e": 2342,
"s": 2328,
"text": "Google Chrome"
},
{
"code": null,
"e": 2361,
"s": 2342,
"text": "Microsoft Edge 9.0"
},
{
"code": null,
"e": 2381,
"s": 2361,
"text": "Mozilla Firefox 1.5"
},
{
"code": null,
"e": 2388,
"s": 2381,
"text": "Safari"
},
{
"code": null,
"e": 2394,
"s": 2388,
"text": "Opera"
},
{
"code": null,
"e": 2408,
"s": 2396,
"text": "jain_chirag"
},
{
"code": null,
"e": 2425,
"s": 2408,
"text": "arorakashish0911"
},
{
"code": null,
"e": 2441,
"s": 2425,
"text": "surbhikumaridav"
},
{
"code": null,
"e": 2458,
"s": 2441,
"text": "javascript-array"
},
{
"code": null,
"e": 2477,
"s": 2458,
"text": "JavaScript-Methods"
},
{
"code": null,
"e": 2488,
"s": 2477,
"text": "JavaScript"
},
{
"code": null,
"e": 2505,
"s": 2488,
"text": "Web Technologies"
}
] |
Flutter – Sending Data To The Internet | 23 Jun, 2022
Interacting with the Internet is crucial for most apps to function. In Flutter the http package is used to send the data to the internet. In this article, we will explore the same topic in detail. To send data to the internet through your application follow the below steps:
Import the http packageSend data to the server through the http packageChange the response into custom dart objectDisplay the response
Import the http package
Send data to the server through the http package
Change the response into custom dart object
Display the response
To install the http package use the below command in your command prompt:
pub get
or, if you are using the flutter cmd use the below command:
flutter pub get
After the installation add the dependency to the pubsec.yml file as shown below:
import 'package:http/http.dart' as http;
In this article, we will create an Album data and send it to JSONPlaceholder through the http.post() method.
Dart
Future<Album> createAlbum(String title) async { final http.Response response = await http.post( Uri.parse('https://jsonplaceholder.typicode.com/albums'), headers: <String, String>{ 'Content-Type': 'application/json; charset=UTF-8', }, body: jsonEncode(<String, String>{ 'title': title, }), );
Though making a network request is no big deal, working with the raw response data can be inconvenient. To make your life easier, convert the raw data (ie, http.response) into dart object. Here we will create an Album class that contains the JSON data as shown below:
Dart
class Album { final int id; final String title; Album({required this.id, required this.title}); factory Album.fromJson(Map<String, dynamic> json) { return Album( id: json['id'], title: json['title'], ); }}
Now, follow the below steps to update the fetchAlbum() function to return a Future<Album>:
Use the dart: convert package to convert the response body into a JSON Map.Use the fromJSON() factory method to convert JSON Map into Album if the server returns an OK response with a status code of 200.Throw an exception if the server doesn’t return an OK response with a status code of 200.
Use the dart: convert package to convert the response body into a JSON Map.
Use the fromJSON() factory method to convert JSON Map into Album if the server returns an OK response with a status code of 200.
Throw an exception if the server doesn’t return an OK response with a status code of 200.
Dart
Future<Album> createAlbum(String title) async { final http.Response response = await http.post( 'https://jsonplaceholder.typicode.com/albums', headers: <String, String>{ 'Content-Type': 'application/json; charset=UTF-8', }, body: jsonEncode(<String, String>{ 'title': title, }), ); // Dispatch action depending upon // the server response if (response.statusCode == 201) { return Album.fromJson(json.decode(response.body)); } else { throw Exception('Album loading failed!'); }}
Now create a TextField for the user to enter a title and a RaisedButton to send data to the server. Also, define a TextEditingController to read the user input from a TextField as shown below:
Dart
Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ TextField( controller: _controller, decoration: const InputDecoration(hintText: 'Enter Title'), ), ElevatedButton( child: const Text('Create Data'), onPressed: () { setState(() { _futureAlbum = createAlbum(_controller.text); }); }, ), // RiisedButton is deprecated and shouldn't be used. Use ElevatedButton. // RaisedButton( // child: Text('Create Data'), // onPressed: () { // setState(() { // _futureAlbum = createAlbum(_controller.text); // }); // }, // ), ],)
Use the FlutterBuilder widget to display the data on the screen as shown below:
Dart
FutureBuilder<Album>( future: _futureAlbum, builder: (context, snapshot) { if (snapshot.hasData) { return Text(snapshot.data!.title); } else if (snapshot.hasError) { return Text("${snapshot.error}"); } return const CircularProgressIndicator(); },),
Complete Source Code:
Dart
import 'dart:async';import 'dart:convert'; import 'package:flutter/material.dart';import 'package:http/http.dart' as http; Future<Album> createAlbum(String title) async { final http.Response response = await http.post( Uri.parse('https://jsonplaceholder.typicode.com/albums'), headers: <String, String>{ 'Content-Type': 'application/json; charset=UTF-8', }, body: jsonEncode(<String, String>{ 'title': title, }), ); if (response.statusCode == 201) { return Album.fromJson(json.decode(response.body)); } else { throw Exception('Failed to create album.'); }} class Album { final int id; final String title; Album({required this.id, required this.title}); factory Album.fromJson(Map<String, dynamic> json) { return Album( id: json['id'], title: json['title'], ); }} void main() { runApp(const MyApp());} class MyApp extends StatefulWidget { const MyApp({Key? key}) : super(key: key); @override // ignore: library_private_types_in_public_api _MyAppState createState() { return _MyAppState(); }} class _MyAppState extends State<MyApp> { final TextEditingController _controller = TextEditingController(); late Future<Album> _futureAlbum; @override Widget build(BuildContext context) { return MaterialApp( title: 'Creating Data', theme: ThemeData( primarySwatch: Colors.blue, ), home: Scaffold( appBar: AppBar( title: const Text('GeeksForGeeks'), backgroundColor: Colors.green, ), body: Container( alignment: Alignment.center, padding: const EdgeInsets.all(8.0), // ignore: unnecessary_null_comparison child: (_futureAlbum == null) ? Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ TextField( controller: _controller, decoration: const InputDecoration(hintText: 'Enter Title'), ), ElevatedButton( child: const Text('Create Data'), onPressed: () { setState(() { _futureAlbum = createAlbum(_controller.text); }); }, ), // RiisedButton is deprecated and shouldn't be used. Use ElevatedButton. // RaisedButton( // child: Text('Create Data'), // onPressed: () { // setState(() { // _futureAlbum = createAlbum(_controller.text); // }); // }, // ), ], ) : FutureBuilder<Album>( future: _futureAlbum, builder: (context, snapshot) { if (snapshot.hasData) { return Text(snapshot.data!.title); } else if (snapshot.hasError) { return Text("${snapshot.error}"); } return const CircularProgressIndicator(); }, ), ), ), ); }}
Output:
sumitgumber28
ankit_kumar_
android
Flutter
Dart
Flutter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 Jun, 2022"
},
{
"code": null,
"e": 303,
"s": 28,
"text": "Interacting with the Internet is crucial for most apps to function. In Flutter the http package is used to send the data to the internet. In this article, we will explore the same topic in detail. To send data to the internet through your application follow the below steps:"
},
{
"code": null,
"e": 438,
"s": 303,
"text": "Import the http packageSend data to the server through the http packageChange the response into custom dart objectDisplay the response"
},
{
"code": null,
"e": 462,
"s": 438,
"text": "Import the http package"
},
{
"code": null,
"e": 511,
"s": 462,
"text": "Send data to the server through the http package"
},
{
"code": null,
"e": 555,
"s": 511,
"text": "Change the response into custom dart object"
},
{
"code": null,
"e": 576,
"s": 555,
"text": "Display the response"
},
{
"code": null,
"e": 650,
"s": 576,
"text": "To install the http package use the below command in your command prompt:"
},
{
"code": null,
"e": 658,
"s": 650,
"text": "pub get"
},
{
"code": null,
"e": 718,
"s": 658,
"text": "or, if you are using the flutter cmd use the below command:"
},
{
"code": null,
"e": 734,
"s": 718,
"text": "flutter pub get"
},
{
"code": null,
"e": 815,
"s": 734,
"text": "After the installation add the dependency to the pubsec.yml file as shown below:"
},
{
"code": null,
"e": 856,
"s": 815,
"text": "import 'package:http/http.dart' as http;"
},
{
"code": null,
"e": 965,
"s": 856,
"text": "In this article, we will create an Album data and send it to JSONPlaceholder through the http.post() method."
},
{
"code": null,
"e": 970,
"s": 965,
"text": "Dart"
},
{
"code": "Future<Album> createAlbum(String title) async { final http.Response response = await http.post( Uri.parse('https://jsonplaceholder.typicode.com/albums'), headers: <String, String>{ 'Content-Type': 'application/json; charset=UTF-8', }, body: jsonEncode(<String, String>{ 'title': title, }), );",
"e": 1290,
"s": 970,
"text": null
},
{
"code": null,
"e": 1558,
"s": 1290,
"text": "Though making a network request is no big deal, working with the raw response data can be inconvenient. To make your life easier, convert the raw data (ie, http.response) into dart object. Here we will create an Album class that contains the JSON data as shown below:"
},
{
"code": null,
"e": 1563,
"s": 1558,
"text": "Dart"
},
{
"code": "class Album { final int id; final String title; Album({required this.id, required this.title}); factory Album.fromJson(Map<String, dynamic> json) { return Album( id: json['id'], title: json['title'], ); }}",
"e": 1792,
"s": 1563,
"text": null
},
{
"code": null,
"e": 1888,
"s": 1797,
"text": "Now, follow the below steps to update the fetchAlbum() function to return a Future<Album>:"
},
{
"code": null,
"e": 2183,
"s": 1890,
"text": "Use the dart: convert package to convert the response body into a JSON Map.Use the fromJSON() factory method to convert JSON Map into Album if the server returns an OK response with a status code of 200.Throw an exception if the server doesn’t return an OK response with a status code of 200."
},
{
"code": null,
"e": 2259,
"s": 2183,
"text": "Use the dart: convert package to convert the response body into a JSON Map."
},
{
"code": null,
"e": 2388,
"s": 2259,
"text": "Use the fromJSON() factory method to convert JSON Map into Album if the server returns an OK response with a status code of 200."
},
{
"code": null,
"e": 2478,
"s": 2388,
"text": "Throw an exception if the server doesn’t return an OK response with a status code of 200."
},
{
"code": null,
"e": 2485,
"s": 2480,
"text": "Dart"
},
{
"code": "Future<Album> createAlbum(String title) async { final http.Response response = await http.post( 'https://jsonplaceholder.typicode.com/albums', headers: <String, String>{ 'Content-Type': 'application/json; charset=UTF-8', }, body: jsonEncode(<String, String>{ 'title': title, }), ); // Dispatch action depending upon // the server response if (response.statusCode == 201) { return Album.fromJson(json.decode(response.body)); } else { throw Exception('Album loading failed!'); }}",
"e": 3004,
"s": 2485,
"text": null
},
{
"code": null,
"e": 3198,
"s": 3004,
"text": "Now create a TextField for the user to enter a title and a RaisedButton to send data to the server. Also, define a TextEditingController to read the user input from a TextField as shown below:"
},
{
"code": null,
"e": 3203,
"s": 3198,
"text": "Dart"
},
{
"code": "Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ TextField( controller: _controller, decoration: const InputDecoration(hintText: 'Enter Title'), ), ElevatedButton( child: const Text('Create Data'), onPressed: () { setState(() { _futureAlbum = createAlbum(_controller.text); }); }, ), // RiisedButton is deprecated and shouldn't be used. Use ElevatedButton. // RaisedButton( // child: Text('Create Data'), // onPressed: () { // setState(() { // _futureAlbum = createAlbum(_controller.text); // }); // }, // ), ],)",
"e": 3861,
"s": 3203,
"text": null
},
{
"code": null,
"e": 3941,
"s": 3861,
"text": "Use the FlutterBuilder widget to display the data on the screen as shown below:"
},
{
"code": null,
"e": 3946,
"s": 3941,
"text": "Dart"
},
{
"code": "FutureBuilder<Album>( future: _futureAlbum, builder: (context, snapshot) { if (snapshot.hasData) { return Text(snapshot.data!.title); } else if (snapshot.hasError) { return Text(\"${snapshot.error}\"); } return const CircularProgressIndicator(); },),",
"e": 4221,
"s": 3946,
"text": null
},
{
"code": null,
"e": 4243,
"s": 4221,
"text": "Complete Source Code:"
},
{
"code": null,
"e": 4248,
"s": 4243,
"text": "Dart"
},
{
"code": "import 'dart:async';import 'dart:convert'; import 'package:flutter/material.dart';import 'package:http/http.dart' as http; Future<Album> createAlbum(String title) async { final http.Response response = await http.post( Uri.parse('https://jsonplaceholder.typicode.com/albums'), headers: <String, String>{ 'Content-Type': 'application/json; charset=UTF-8', }, body: jsonEncode(<String, String>{ 'title': title, }), ); if (response.statusCode == 201) { return Album.fromJson(json.decode(response.body)); } else { throw Exception('Failed to create album.'); }} class Album { final int id; final String title; Album({required this.id, required this.title}); factory Album.fromJson(Map<String, dynamic> json) { return Album( id: json['id'], title: json['title'], ); }} void main() { runApp(const MyApp());} class MyApp extends StatefulWidget { const MyApp({Key? key}) : super(key: key); @override // ignore: library_private_types_in_public_api _MyAppState createState() { return _MyAppState(); }} class _MyAppState extends State<MyApp> { final TextEditingController _controller = TextEditingController(); late Future<Album> _futureAlbum; @override Widget build(BuildContext context) { return MaterialApp( title: 'Creating Data', theme: ThemeData( primarySwatch: Colors.blue, ), home: Scaffold( appBar: AppBar( title: const Text('GeeksForGeeks'), backgroundColor: Colors.green, ), body: Container( alignment: Alignment.center, padding: const EdgeInsets.all(8.0), // ignore: unnecessary_null_comparison child: (_futureAlbum == null) ? Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ TextField( controller: _controller, decoration: const InputDecoration(hintText: 'Enter Title'), ), ElevatedButton( child: const Text('Create Data'), onPressed: () { setState(() { _futureAlbum = createAlbum(_controller.text); }); }, ), // RiisedButton is deprecated and shouldn't be used. Use ElevatedButton. // RaisedButton( // child: Text('Create Data'), // onPressed: () { // setState(() { // _futureAlbum = createAlbum(_controller.text); // }); // }, // ), ], ) : FutureBuilder<Album>( future: _futureAlbum, builder: (context, snapshot) { if (snapshot.hasData) { return Text(snapshot.data!.title); } else if (snapshot.hasError) { return Text(\"${snapshot.error}\"); } return const CircularProgressIndicator(); }, ), ), ), ); }}",
"e": 7520,
"s": 4248,
"text": null
},
{
"code": null,
"e": 7528,
"s": 7520,
"text": "Output:"
},
{
"code": null,
"e": 7542,
"s": 7528,
"text": "sumitgumber28"
},
{
"code": null,
"e": 7555,
"s": 7542,
"text": "ankit_kumar_"
},
{
"code": null,
"e": 7563,
"s": 7555,
"text": "android"
},
{
"code": null,
"e": 7571,
"s": 7563,
"text": "Flutter"
},
{
"code": null,
"e": 7576,
"s": 7571,
"text": "Dart"
},
{
"code": null,
"e": 7584,
"s": 7576,
"text": "Flutter"
}
] |
Python Try Except | 28 Jan, 2022
Error in Python can be of two types i.e. Syntax errors and Exceptions. Errors are the problems in a program due to which the program will stop the execution. On the other hand, exceptions are raised when some internal events occur which changes the normal flow of the program.Note: For more information, refer to Errors and Exceptions in PythonSome of the common Exception Errors are :
IOError: if the file can’t be opened
KeyboardInterrupt: when an unrequired key is pressed by the user
ValueError: when built-in function receives a wrong argument
EOFError: if End-Of-File is hit without reading any data
ImportError: if it is unable to find the module
Try and Except statement is used to handle these errors within our code in Python. The try block is used to check some code for errors i.e the code inside the try block will execute when there is no error in the program. Whereas the code inside the except block will execute whenever the program encounters some error in the preceding try block.
Syntax:
try:
# Some Code
except:
# Executed if error in the
# try block
How try() works?
First, the try clause is executed i.e. the code between try and except clause.
If there is no exception, then only the try clause will run, except the clause is finished.
If any exception occurs, the try clause will be skipped and except clause will run.
If any exception occurs, but the except clause within the code doesn’t handle it, it is passed on to the outer try statements. If the exception is left unhandled, then the execution stops.
A try statement can have more than one except clause
Code 1: No exception, so the try clause will run.
Python3
# Python code to illustrate# working of try()def divide(x, y): try: # Floor Division : Gives only Fractional Part as Answer result = x // y print("Yeah ! Your answer is :", result) except ZeroDivisionError: print("Sorry ! You are dividing by zero ") # Look at parameters and note the working of Programdivide(3, 2)
Output :
('Yeah ! Your answer is :', 1)
Code 1: There is an exception so only except clause will run.
Python3
# Python code to illustrate# working of try()def divide(x, y): try: # Floor Division : Gives only Fractional Part as Answer result = x // y print("Yeah ! Your answer is :", result) except ZeroDivisionError: print("Sorry ! You are dividing by zero ") # Look at parameters and note the working of Programdivide(3, 0)
Output :
Sorry ! You are dividing by zero
In python, you can also use the else clause on the try-except block which must be present after all the except clauses. The code enters the else block only if the try clause does not raise an exception.
Syntax:
try:
# Some Code
except:
# Executed if error in the
# try block
else:
# execute if no exception
Code:
Python3
# Program to depict else clause with try-except # Function which returns a/bdef AbyB(a , b): try: c = ((a+b) // (a-b)) except ZeroDivisionError: print ("a/b result in 0") else: print (c) # Driver program to test above functionAbyB(2.0, 3.0)AbyB(3.0, 3.0)
Output:
-5.0
a/b result in 0
Python provides a keyword finally, which is always executed after the try and except blocks. The final block always executes after normal termination of try block or after try block terminates due to some exceptions.
Syntax:
try:
# Some Code
except:
# Executed if error in the
# try block
else:
# execute if no exception
finally:
# Some code .....(always executed)
Code:
Python3
# Python program to demonstrate finally # No exception Exception raised in try blocktry: k = 5//0 # raises divide by zero exception. print(k) # handles zerodivision exception except ZeroDivisionError: print("Can't divide by zero") finally: # this block is always executed # regardless of exception generation. print('This is always executed')
Output:
Can't divide by zero
This is always executed
Related Articles:
Output Questions
Exception Handling in Python
User-Defined Exceptions
This article is contributed by Mohit Gupta_OMG . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
nikhilaggarwal3
punamsingh628700
amartyaghoshgfg
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": "\n28 Jan, 2022"
},
{
"code": null,
"e": 441,
"s": 53,
"text": "Error in Python can be of two types i.e. Syntax errors and Exceptions. Errors are the problems in a program due to which the program will stop the execution. On the other hand, exceptions are raised when some internal events occur which changes the normal flow of the program.Note: For more information, refer to Errors and Exceptions in PythonSome of the common Exception Errors are : "
},
{
"code": null,
"e": 478,
"s": 441,
"text": "IOError: if the file can’t be opened"
},
{
"code": null,
"e": 543,
"s": 478,
"text": "KeyboardInterrupt: when an unrequired key is pressed by the user"
},
{
"code": null,
"e": 604,
"s": 543,
"text": "ValueError: when built-in function receives a wrong argument"
},
{
"code": null,
"e": 661,
"s": 604,
"text": "EOFError: if End-Of-File is hit without reading any data"
},
{
"code": null,
"e": 709,
"s": 661,
"text": "ImportError: if it is unable to find the module"
},
{
"code": null,
"e": 1058,
"s": 711,
"text": "Try and Except statement is used to handle these errors within our code in Python. The try block is used to check some code for errors i.e the code inside the try block will execute when there is no error in the program. Whereas the code inside the except block will execute whenever the program encounters some error in the preceding try block. "
},
{
"code": null,
"e": 1067,
"s": 1058,
"text": "Syntax: "
},
{
"code": null,
"e": 1143,
"s": 1067,
"text": "try:\n # Some Code\nexcept:\n # Executed if error in the\n # try block"
},
{
"code": null,
"e": 1162,
"s": 1143,
"text": "How try() works? "
},
{
"code": null,
"e": 1241,
"s": 1162,
"text": "First, the try clause is executed i.e. the code between try and except clause."
},
{
"code": null,
"e": 1333,
"s": 1241,
"text": "If there is no exception, then only the try clause will run, except the clause is finished."
},
{
"code": null,
"e": 1417,
"s": 1333,
"text": "If any exception occurs, the try clause will be skipped and except clause will run."
},
{
"code": null,
"e": 1606,
"s": 1417,
"text": "If any exception occurs, but the except clause within the code doesn’t handle it, it is passed on to the outer try statements. If the exception is left unhandled, then the execution stops."
},
{
"code": null,
"e": 1659,
"s": 1606,
"text": "A try statement can have more than one except clause"
},
{
"code": null,
"e": 1711,
"s": 1659,
"text": "Code 1: No exception, so the try clause will run. "
},
{
"code": null,
"e": 1719,
"s": 1711,
"text": "Python3"
},
{
"code": "# Python code to illustrate# working of try()def divide(x, y): try: # Floor Division : Gives only Fractional Part as Answer result = x // y print(\"Yeah ! Your answer is :\", result) except ZeroDivisionError: print(\"Sorry ! You are dividing by zero \") # Look at parameters and note the working of Programdivide(3, 2)",
"e": 2068,
"s": 1719,
"text": null
},
{
"code": null,
"e": 2079,
"s": 2068,
"text": "Output : "
},
{
"code": null,
"e": 2110,
"s": 2079,
"text": "('Yeah ! Your answer is :', 1)"
},
{
"code": null,
"e": 2174,
"s": 2110,
"text": "Code 1: There is an exception so only except clause will run. "
},
{
"code": null,
"e": 2182,
"s": 2174,
"text": "Python3"
},
{
"code": "# Python code to illustrate# working of try()def divide(x, y): try: # Floor Division : Gives only Fractional Part as Answer result = x // y print(\"Yeah ! Your answer is :\", result) except ZeroDivisionError: print(\"Sorry ! You are dividing by zero \") # Look at parameters and note the working of Programdivide(3, 0)",
"e": 2531,
"s": 2182,
"text": null
},
{
"code": null,
"e": 2542,
"s": 2531,
"text": "Output : "
},
{
"code": null,
"e": 2575,
"s": 2542,
"text": "Sorry ! You are dividing by zero"
},
{
"code": null,
"e": 2781,
"s": 2577,
"text": "In python, you can also use the else clause on the try-except block which must be present after all the except clauses. The code enters the else block only if the try clause does not raise an exception. "
},
{
"code": null,
"e": 2789,
"s": 2781,
"text": "Syntax:"
},
{
"code": null,
"e": 2901,
"s": 2789,
"text": "try:\n # Some Code\nexcept:\n # Executed if error in the\n # try block\nelse:\n # execute if no exception"
},
{
"code": null,
"e": 2907,
"s": 2901,
"text": "Code:"
},
{
"code": null,
"e": 2915,
"s": 2907,
"text": "Python3"
},
{
"code": "# Program to depict else clause with try-except # Function which returns a/bdef AbyB(a , b): try: c = ((a+b) // (a-b)) except ZeroDivisionError: print (\"a/b result in 0\") else: print (c) # Driver program to test above functionAbyB(2.0, 3.0)AbyB(3.0, 3.0)",
"e": 3202,
"s": 2915,
"text": null
},
{
"code": null,
"e": 3210,
"s": 3202,
"text": "Output:"
},
{
"code": null,
"e": 3231,
"s": 3210,
"text": "-5.0\na/b result in 0"
},
{
"code": null,
"e": 3451,
"s": 3233,
"text": "Python provides a keyword finally, which is always executed after the try and except blocks. The final block always executes after normal termination of try block or after try block terminates due to some exceptions. "
},
{
"code": null,
"e": 3459,
"s": 3451,
"text": "Syntax:"
},
{
"code": null,
"e": 3619,
"s": 3459,
"text": "try:\n # Some Code\nexcept:\n # Executed if error in the\n # try block\nelse:\n # execute if no exception\nfinally:\n # Some code .....(always executed)"
},
{
"code": null,
"e": 3625,
"s": 3619,
"text": "Code:"
},
{
"code": null,
"e": 3633,
"s": 3625,
"text": "Python3"
},
{
"code": "# Python program to demonstrate finally # No exception Exception raised in try blocktry: k = 5//0 # raises divide by zero exception. print(k) # handles zerodivision exception except ZeroDivisionError: print(\"Can't divide by zero\") finally: # this block is always executed # regardless of exception generation. print('This is always executed') ",
"e": 4015,
"s": 3633,
"text": null
},
{
"code": null,
"e": 4023,
"s": 4015,
"text": "Output:"
},
{
"code": null,
"e": 4068,
"s": 4023,
"text": "Can't divide by zero\nThis is always executed"
},
{
"code": null,
"e": 4088,
"s": 4068,
"text": "Related Articles: "
},
{
"code": null,
"e": 4105,
"s": 4088,
"text": "Output Questions"
},
{
"code": null,
"e": 4134,
"s": 4105,
"text": "Exception Handling in Python"
},
{
"code": null,
"e": 4158,
"s": 4134,
"text": "User-Defined Exceptions"
},
{
"code": null,
"e": 4583,
"s": 4158,
"text": "This article is contributed by Mohit Gupta_OMG . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 4599,
"s": 4583,
"text": "nikhilaggarwal3"
},
{
"code": null,
"e": 4616,
"s": 4599,
"text": "punamsingh628700"
},
{
"code": null,
"e": 4632,
"s": 4616,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 4639,
"s": 4632,
"text": "Python"
},
{
"code": null,
"e": 4658,
"s": 4639,
"text": "School Programming"
}
] |
Python OpenCV | cv2.arrowedLine() method | 23 Nov, 2021
OpenCV-Python is a library of Python bindings designed to solve computer vision problems. cv2.arrowedLine() method is used to draw arrow segment pointing from the start point to the end point.
Syntax: cv2.arrowedLine(image, start_point, end_point, color, thickness, line_type, shift, tipLength)Parameters: image: It is the image on which line is to be drawn. start_point: It is the starting coordinates of line. The coordinates are represented as tuples of two values i.e. (X coordinate value, Y coordinate value). end_point: It is the ending coordinates of line. The coordinates are represented as tuples of two values i.e. (X coordinate value, Y coordinate value). color: It is the color of line to be drawn. For BGR, we pass a tuple. eg: (255, 0, 0) for blue color. thickness: It is the thickness of the line in px. line_type: It denotes the type of the line for drawing. shift: It denotes number of fractional bits in the point coordinates. tipLength: It denotes the length of the arrow tip in relation to the arrow length. Return Value: It returns an image.
Image used for all the below examples:
Example #1:
Python3
# Python program to explain cv2.arrowedLine() method # importing cv2import cv2 # pathpath = r'C:\Users\Atomix\Desktop\geeksforgeeks\geeks.png' # Reading an image in default modeimage = cv2.imread(path) # Window name in which image is displayedwindow_name = 'Image' # Start coordinate, here (0, 0)# represents the top left corner of imagestart_point = (0, 0) # End coordinateend_point = (200, 200) # Green color in BGRcolor = (0, 255, 0) # Line thickness of 9 pxthickness = 9 # Using cv2.arrowedLine() method# Draw a diagonal green arrow line# with thickness of 9 pximage = cv2.arrowedLine(image, start_point, end_point, color, thickness) # Displaying the imagecv2.imshow(window_name, image)
Output:
Example #2:
Python3
# Python program to explain cv2.arrowedLine() method # importing cv2import cv2 # pathpath = r'C:\Users\Atomix\Desktop\geeksforgeeks\geeks.png' # Reading an image in default modeimage = cv2.imread(path) # Window name in which image is displayedwindow_name = 'Image' # Start coordinate, here (225, 0)# represents the top right corner of imagestart_point = (225, 0) # End coordinateend_point = (0, 90) # Red color in BGRcolor = (0, 0, 255) # Line thickness of 9 pxthickness = 9 # Using cv2.arrowedLine() method# Draw a red arrow line# with thickness of 9 px and tipLength = 0.5image = cv2.arrowedLine(image, start_point, end_point, color, thickness, tipLength = 0.5) # Displaying the imagecv2.imshow(window_name, image)
Output:
ritvikcodes23
Image-Processing
OpenCV
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 Nov, 2021"
},
{
"code": null,
"e": 222,
"s": 28,
"text": "OpenCV-Python is a library of Python bindings designed to solve computer vision problems. cv2.arrowedLine() method is used to draw arrow segment pointing from the start point to the end point. "
},
{
"code": null,
"e": 1094,
"s": 222,
"text": "Syntax: cv2.arrowedLine(image, start_point, end_point, color, thickness, line_type, shift, tipLength)Parameters: image: It is the image on which line is to be drawn. start_point: It is the starting coordinates of line. The coordinates are represented as tuples of two values i.e. (X coordinate value, Y coordinate value). end_point: It is the ending coordinates of line. The coordinates are represented as tuples of two values i.e. (X coordinate value, Y coordinate value). color: It is the color of line to be drawn. For BGR, we pass a tuple. eg: (255, 0, 0) for blue color. thickness: It is the thickness of the line in px. line_type: It denotes the type of the line for drawing. shift: It denotes number of fractional bits in the point coordinates. tipLength: It denotes the length of the arrow tip in relation to the arrow length. Return Value: It returns an image. "
},
{
"code": null,
"e": 1135,
"s": 1094,
"text": "Image used for all the below examples: "
},
{
"code": null,
"e": 1149,
"s": 1135,
"text": "Example #1: "
},
{
"code": null,
"e": 1157,
"s": 1149,
"text": "Python3"
},
{
"code": "# Python program to explain cv2.arrowedLine() method # importing cv2import cv2 # pathpath = r'C:\\Users\\Atomix\\Desktop\\geeksforgeeks\\geeks.png' # Reading an image in default modeimage = cv2.imread(path) # Window name in which image is displayedwindow_name = 'Image' # Start coordinate, here (0, 0)# represents the top left corner of imagestart_point = (0, 0) # End coordinateend_point = (200, 200) # Green color in BGRcolor = (0, 255, 0) # Line thickness of 9 pxthickness = 9 # Using cv2.arrowedLine() method# Draw a diagonal green arrow line# with thickness of 9 pximage = cv2.arrowedLine(image, start_point, end_point, color, thickness) # Displaying the imagecv2.imshow(window_name, image)",
"e": 1884,
"s": 1157,
"text": null
},
{
"code": null,
"e": 1894,
"s": 1884,
"text": "Output: "
},
{
"code": null,
"e": 1908,
"s": 1894,
"text": "Example #2: "
},
{
"code": null,
"e": 1916,
"s": 1908,
"text": "Python3"
},
{
"code": "# Python program to explain cv2.arrowedLine() method # importing cv2import cv2 # pathpath = r'C:\\Users\\Atomix\\Desktop\\geeksforgeeks\\geeks.png' # Reading an image in default modeimage = cv2.imread(path) # Window name in which image is displayedwindow_name = 'Image' # Start coordinate, here (225, 0)# represents the top right corner of imagestart_point = (225, 0) # End coordinateend_point = (0, 90) # Red color in BGRcolor = (0, 0, 255) # Line thickness of 9 pxthickness = 9 # Using cv2.arrowedLine() method# Draw a red arrow line# with thickness of 9 px and tipLength = 0.5image = cv2.arrowedLine(image, start_point, end_point, color, thickness, tipLength = 0.5) # Displaying the imagecv2.imshow(window_name, image)",
"e": 2652,
"s": 1916,
"text": null
},
{
"code": null,
"e": 2662,
"s": 2652,
"text": "Output: "
},
{
"code": null,
"e": 2678,
"s": 2664,
"text": "ritvikcodes23"
},
{
"code": null,
"e": 2695,
"s": 2678,
"text": "Image-Processing"
},
{
"code": null,
"e": 2702,
"s": 2695,
"text": "OpenCV"
},
{
"code": null,
"e": 2709,
"s": 2702,
"text": "Python"
}
] |
JavaScript Date valueOf() Method | 17 Jan, 2022
Below is the example of Date valueOf() method.
Example:javascriptjavascript<script> // Here a date has been assigned // while creating Date object var dateobj = new Date('October 15, 1996 05:35:32'); // Getting the number of milliseconds between // 1 January 1970 00:00:00 // UTC and the given date as the content of // the above Date() constructor. var B = dateobj.valueOf(); // Printing the calculated number // of milliseconds. document.write(B);</script>
javascript
<script> // Here a date has been assigned // while creating Date object var dateobj = new Date('October 15, 1996 05:35:32'); // Getting the number of milliseconds between // 1 January 1970 00:00:00 // UTC and the given date as the content of // the above Date() constructor. var B = dateobj.valueOf(); // Printing the calculated number // of milliseconds. document.write(B);</script>
Output:845337932000
845337932000
The date.valueOf() method is used to get the number of milliseconds between 1 January 1970 00:00:00 UTC and the given date.Syntax:
dateObj.valueOf()
Parameters: This method does not accept any parameter. It is just used along with a Date object created using Date() constructor.
Return Values: It returns the number of milliseconds between 1 January 1970 00:00:00 UTC and the given date as the contents of the Date() constructor.
Note: The DateObj is a valid Date object created using Date() constructor whose contents are used to get the number of milliseconds between 1 January 1970 00:00:00 UTC and the given date as the contents of the Date() constructor.
More codes for the above method are as follows:
Program 1: If nothing as a parameter is passed while creating date object but still valueOf() method returns the number of milliseconds between 1 January 1970 00:00:00 UTC and the current date.
javascript
<script> // Here nothing has been assigned // while creating Date object var dateobj = new Date(); // Getting the number of milliseconds between // 1 January 1970 00:00:00 // UTC and the current date. var B = dateobj.valueOf(); // Printing the calculated number // of milliseconds. document.write(B);</script>
1524387231290
Program 2: Date of a month ranging between 1 to 31. If the date is taken as 35 which is out of the date range, it returns NaN i.e, not a number.
javascript
<script> // Here a date has been assigned // while creating Date object var dateobj = new Date('October 35, 1996 05:35:32'); // Getting the number of milliseconds between // 1 January 1970 00:00:00 // UTC and the given date. var B = dateobj.valueOf(); // Printing the calculated number // of milliseconds. document.write(B);</script>
NaN
Some Important Points:
Months, Dates, hours, minutes, seconds, milliseconds should all be in their respective range.Otherwise valueOf() method returns NaN i.e, not a number.
Range of Months, Dates, hours, minutes, seconds, milliseconds are 0 to 11, 1 to 31, 0 to 23, 0 to 59, 0 to 59, 0 to 999 respectively.
Supported Browsers: The browsers supported by JavaScript Date valueOf() Method are listed below:
Google Chrome 1 and above
Edge 12 and above
Firefox 1 and above
Internet Explorer 4 and above
Opera 3 and above
Safari 1 and above
ysachin2314
surindertarika1234
javascript-date
JavaScript-Methods
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": "\n17 Jan, 2022"
},
{
"code": null,
"e": 75,
"s": 28,
"text": "Below is the example of Date valueOf() method."
},
{
"code": null,
"e": 518,
"s": 75,
"text": "Example:javascriptjavascript<script> // Here a date has been assigned // while creating Date object var dateobj = new Date('October 15, 1996 05:35:32'); // Getting the number of milliseconds between // 1 January 1970 00:00:00 // UTC and the given date as the content of // the above Date() constructor. var B = dateobj.valueOf(); // Printing the calculated number // of milliseconds. document.write(B);</script>"
},
{
"code": null,
"e": 529,
"s": 518,
"text": "javascript"
},
{
"code": "<script> // Here a date has been assigned // while creating Date object var dateobj = new Date('October 15, 1996 05:35:32'); // Getting the number of milliseconds between // 1 January 1970 00:00:00 // UTC and the given date as the content of // the above Date() constructor. var B = dateobj.valueOf(); // Printing the calculated number // of milliseconds. document.write(B);</script>",
"e": 944,
"s": 529,
"text": null
},
{
"code": null,
"e": 964,
"s": 944,
"text": "Output:845337932000"
},
{
"code": null,
"e": 977,
"s": 964,
"text": "845337932000"
},
{
"code": null,
"e": 1108,
"s": 977,
"text": "The date.valueOf() method is used to get the number of milliseconds between 1 January 1970 00:00:00 UTC and the given date.Syntax:"
},
{
"code": null,
"e": 1126,
"s": 1108,
"text": "dateObj.valueOf()"
},
{
"code": null,
"e": 1256,
"s": 1126,
"text": "Parameters: This method does not accept any parameter. It is just used along with a Date object created using Date() constructor."
},
{
"code": null,
"e": 1407,
"s": 1256,
"text": "Return Values: It returns the number of milliseconds between 1 January 1970 00:00:00 UTC and the given date as the contents of the Date() constructor."
},
{
"code": null,
"e": 1637,
"s": 1407,
"text": "Note: The DateObj is a valid Date object created using Date() constructor whose contents are used to get the number of milliseconds between 1 January 1970 00:00:00 UTC and the given date as the contents of the Date() constructor."
},
{
"code": null,
"e": 1685,
"s": 1637,
"text": "More codes for the above method are as follows:"
},
{
"code": null,
"e": 1879,
"s": 1685,
"text": "Program 1: If nothing as a parameter is passed while creating date object but still valueOf() method returns the number of milliseconds between 1 January 1970 00:00:00 UTC and the current date."
},
{
"code": null,
"e": 1890,
"s": 1879,
"text": "javascript"
},
{
"code": "<script> // Here nothing has been assigned // while creating Date object var dateobj = new Date(); // Getting the number of milliseconds between // 1 January 1970 00:00:00 // UTC and the current date. var B = dateobj.valueOf(); // Printing the calculated number // of milliseconds. document.write(B);</script>",
"e": 2226,
"s": 1890,
"text": null
},
{
"code": null,
"e": 2240,
"s": 2226,
"text": "1524387231290"
},
{
"code": null,
"e": 2385,
"s": 2240,
"text": "Program 2: Date of a month ranging between 1 to 31. If the date is taken as 35 which is out of the date range, it returns NaN i.e, not a number."
},
{
"code": null,
"e": 2396,
"s": 2385,
"text": "javascript"
},
{
"code": "<script> // Here a date has been assigned // while creating Date object var dateobj = new Date('October 35, 1996 05:35:32'); // Getting the number of milliseconds between // 1 January 1970 00:00:00 // UTC and the given date. var B = dateobj.valueOf(); // Printing the calculated number // of milliseconds. document.write(B);</script>",
"e": 2758,
"s": 2396,
"text": null
},
{
"code": null,
"e": 2762,
"s": 2758,
"text": "NaN"
},
{
"code": null,
"e": 2785,
"s": 2762,
"text": "Some Important Points:"
},
{
"code": null,
"e": 2936,
"s": 2785,
"text": "Months, Dates, hours, minutes, seconds, milliseconds should all be in their respective range.Otherwise valueOf() method returns NaN i.e, not a number."
},
{
"code": null,
"e": 3070,
"s": 2936,
"text": "Range of Months, Dates, hours, minutes, seconds, milliseconds are 0 to 11, 1 to 31, 0 to 23, 0 to 59, 0 to 59, 0 to 999 respectively."
},
{
"code": null,
"e": 3167,
"s": 3070,
"text": "Supported Browsers: The browsers supported by JavaScript Date valueOf() Method are listed below:"
},
{
"code": null,
"e": 3193,
"s": 3167,
"text": "Google Chrome 1 and above"
},
{
"code": null,
"e": 3211,
"s": 3193,
"text": "Edge 12 and above"
},
{
"code": null,
"e": 3231,
"s": 3211,
"text": "Firefox 1 and above"
},
{
"code": null,
"e": 3261,
"s": 3231,
"text": "Internet Explorer 4 and above"
},
{
"code": null,
"e": 3279,
"s": 3261,
"text": "Opera 3 and above"
},
{
"code": null,
"e": 3298,
"s": 3279,
"text": "Safari 1 and above"
},
{
"code": null,
"e": 3310,
"s": 3298,
"text": "ysachin2314"
},
{
"code": null,
"e": 3329,
"s": 3310,
"text": "surindertarika1234"
},
{
"code": null,
"e": 3345,
"s": 3329,
"text": "javascript-date"
},
{
"code": null,
"e": 3364,
"s": 3345,
"text": "JavaScript-Methods"
},
{
"code": null,
"e": 3375,
"s": 3364,
"text": "JavaScript"
},
{
"code": null,
"e": 3392,
"s": 3375,
"text": "Web Technologies"
}
] |
Program to print Fibonacci Triangle | 19 May, 2021
Given the value of n(n < 10), i.e, number of lines, print the Fibonacci triangle.
Examples:
Input : n = 5
Output :
1
1 2
3 5 8
13 21 34 55
89 144 233 377 610
Input : n = 7
Output :
1
1 2
3 5 8
13 21 34 55
89 144 233 377 610
987 1597 2584 4181 6765 10946
17711 28657 46368 75025 121393 196418 317811
The Fibonacci numbers are the numbers in the following integer sequence.1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ........In mathematical terms, the sequence Fn of Fibonacci numbers is defined by the recurrence relation
Fn = Fn-1 + Fn-2
with seed values F1 = 1 and F2 = 1.
Below is the implementation of the above pattern :
C++
Java
Python3
C#
PHP
Javascript
// C++ Implementation for// Fibonacci triangle#include <bits/stdc++.h>using namespace std; // function to fill Fibonacci Numbers// in f[]void fib(int f[], int N){ // 1st and 2nd number of the // series are 1 and 1 f[1] = 1; f[2] = 1; for (int i = 3; i <= N; i++) // Add the previous 2 numbers // in the series and store it f[i] = f[i - 1] + f[i - 2];} void fiboTriangle(int n){ // Fill Fibonacci numbers in f[] using // fib(). We need N = n*(n+1)/2 Fibonacci // numbers to make a triangle of height // n int N = n * (n + 1) / 2; int f[N + 1]; fib(f, N); // To store next Fibonacci Number to print int fiboNum = 1; // for loop to keep track of // number of lines for (int i = 1; i <= n; i++) { // For loop to keep track of // numbers in each line for (int j = 1; j <= i; j++) cout << f[fiboNum++] << " "; cout << endl; }} // Driver codeint main(){ int n = 5; fiboTriangle(n); return 0;}
// Java Implementation for// Fibonacci triangleimport java.io.*; class GFG { // function to fill Fibonacci Numbers // in f[] static void fib(int f[], int N) { // 1st and 2nd number of the // series are 1 and 1 f[1] = 1; f[2] = 1; for (int i = 3; i <= N; i++) // Add the previous 2 numbers // in the series and store it f[i] = f[i - 1] + f[i - 2]; } static void fiboTriangle(int n) { // Fill Fibonacci numbers in f[] using // fib(). We need N = n*(n+1)/2 Fibonacci // numbers to make a triangle of height // n int N = n * (n + 1) / 2; int f[] = new int[N + 1]; fib(f, N); // To store next Fibonacci // Number to print int fiboNum = 1; // for loop to keep track of // number of lines for (int i = 1; i <= n; i++) { // For loop to keep track of // numbers in each line for (int j = 1; j <= i; j++) System.out.print(f[fiboNum++] + " "); System.out.println(); } } // Driver code public static void main(String args[]) { int n = 5; fiboTriangle(n); }} /*This code is contributed by Nikita Tiwari.*/
# Python 3 Implementation for# Fibonacci triangle # function to fill Fibonacci# Numbers in f[]def fib(f, N): # 1st and 2nd number of # the series are 1 and 1 f[1] = 1 f[2] = 1 for i in range(3, N + 1): # Add the previous 2 numbers # in the series and store it f[i] = f[i - 1] + f[i - 2] def fiboTriangle(n): # Fill Fibonacci numbers in # f[] using fib(). We need # N = n*(n + 1)/2 Fibonacci # numbers to make a triangle # of height n N = n * (n + 1) // 2 f = [0] * (N + 1) fib(f, N) # To store next Fibonacci # Number to print fiboNum = 1 # for loop to keep track of # number of lines for i in range(1, n + 1): # For loop to keep track of # numbers in each line for j in range(1, i + 1): print(f[fiboNum], " ", end="") fiboNum = fiboNum + 1 print() # Driver coden = 5fiboTriangle(n) # This code is contributed by Nikita Tiwari.
// C# Implementation for// Fibonacci triangleusing System; class GFG { // function to fill Fibonacci Numbers // in f[] static void fib(int[] f, int N) { // 1st and 2nd number of the // series are 1 and 1 f[1] = 1; f[2] = 1; for (int i = 3; i <= N; i++) // Add the previous 2 numbers // in the series and store it f[i] = f[i - 1] + f[i - 2]; } static void fiboTriangle(int n) { // Fill Fibonacci numbers in f[] using // fib(). We need N = n*(n+1)/2 Fibonacci // numbers to make a triangle of height // n int N = n * (n + 1) / 2; int[] f = new int[N + 1]; fib(f, N); // To store next Fibonacci // Number to print int fiboNum = 1; // for loop to keep track of // number of lines for (int i = 1; i <= n; i++) { // For loop to keep track of // numbers in each line for (int j = 1; j <= i; j++) Console.Write(f[fiboNum++] + " "); Console.WriteLine(); } } // Driver code public static void Main() { int n = 5; fiboTriangle(n); }} /*This code is contributed by vt_m.*/
<?php// PHP Implementation for// Fibonacci triangle // function to fill// Fibonacci Numbers// in f[]function fib(&$f, $N){ // 1st and 2nd number // of the series are // 1 and 1 $f[1] = 1; $f[2] = 1; for ($i = 3; $i <= $N; $i++) // Add the previous // 2 numbers in the // series and store it $f[$i] = $f[$i - 1] + $f[$i - 2];} function fiboTriangle($n){ // Fill Fibonacci numbers // in f[] using fib(). We // need N = n*(n+1)/2 // Fibonacci numbers to make // a triangle of height n $N = $n * ($n + 1) / 2; $f = array(); fib($f, $N); // To store next // Fibonacci Number // to print $fiboNum = 1; // for loop to keep track // of number of lines for ($i = 1; $i <= $n; $i++) { // For loop to keep track // of numbers in each line for ($j = 1;$j <= $i; $j++) echo ($f[$fiboNum++] . " "); echo("\n"); }} // Driver code$n = 5;fiboTriangle($n); // This code is contributed by// Manish Shaw(manishshaw1)?>
<script> // JavaScript implementation for// Fibonacci triangle // Function to fill Fibonacci Numbers// in f[]function fib(f, N){ // 1st and 2nd number of the // series are 1 and 1 f[1] = 1; f[2] = 1; for(var i = 3; i <= N; i++) // Add the previous 2 numbers // in the series and store it f[i] = f[i - 1] + f[i - 2];} function fiboTriangle(n){ // Fill Fibonacci numbers in f[] using // fib(). We need N = n*(n+1)/2 Fibonacci // numbers to make a triangle of height // n var N = (n * (n + 1)) / 2; var f = [...Array(N + 1)]; fib(f, N); // To store next Fibonacci Number to print var fiboNum = 1; // for loop to keep track of // number of lines for(var i = 1; i <= n; i++) { // For loop to keep track of // numbers in each line for(var j = 1; j <= i; j++) document.write(f[fiboNum++] + " "); document.write("<br>"); }} // Driver codevar n = 5; fiboTriangle(n); // This code is contributed by rdtank </script>
Output:
1
1 2
3 5 8
13 21 34 55
89 144 233 377 610
manishshaw1
rdtank
gourangakataky4
Fibonacci
Mathematical
Mathematical
Fibonacci
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n19 May, 2021"
},
{
"code": null,
"e": 136,
"s": 54,
"text": "Given the value of n(n < 10), i.e, number of lines, print the Fibonacci triangle."
},
{
"code": null,
"e": 147,
"s": 136,
"text": "Examples: "
},
{
"code": null,
"e": 368,
"s": 147,
"text": "Input : n = 5 \nOutput :\n1 \n1 2 \n3 5 8 \n13 21 34 55 \n89 144 233 377 610 \n\nInput : n = 7\nOutput :\n1 \n1 2 \n3 5 8 \n13 21 34 55 \n89 144 233 377 610 \n987 1597 2584 4181 6765 10946 \n17711 28657 46368 75025 121393 196418 317811 "
},
{
"code": null,
"e": 590,
"s": 368,
"text": "The Fibonacci numbers are the numbers in the following integer sequence.1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ........In mathematical terms, the sequence Fn of Fibonacci numbers is defined by the recurrence relation "
},
{
"code": null,
"e": 611,
"s": 590,
"text": " Fn = Fn-1 + Fn-2"
},
{
"code": null,
"e": 647,
"s": 611,
"text": "with seed values F1 = 1 and F2 = 1."
},
{
"code": null,
"e": 700,
"s": 647,
"text": "Below is the implementation of the above pattern : "
},
{
"code": null,
"e": 704,
"s": 700,
"text": "C++"
},
{
"code": null,
"e": 709,
"s": 704,
"text": "Java"
},
{
"code": null,
"e": 717,
"s": 709,
"text": "Python3"
},
{
"code": null,
"e": 720,
"s": 717,
"text": "C#"
},
{
"code": null,
"e": 724,
"s": 720,
"text": "PHP"
},
{
"code": null,
"e": 735,
"s": 724,
"text": "Javascript"
},
{
"code": "// C++ Implementation for// Fibonacci triangle#include <bits/stdc++.h>using namespace std; // function to fill Fibonacci Numbers// in f[]void fib(int f[], int N){ // 1st and 2nd number of the // series are 1 and 1 f[1] = 1; f[2] = 1; for (int i = 3; i <= N; i++) // Add the previous 2 numbers // in the series and store it f[i] = f[i - 1] + f[i - 2];} void fiboTriangle(int n){ // Fill Fibonacci numbers in f[] using // fib(). We need N = n*(n+1)/2 Fibonacci // numbers to make a triangle of height // n int N = n * (n + 1) / 2; int f[N + 1]; fib(f, N); // To store next Fibonacci Number to print int fiboNum = 1; // for loop to keep track of // number of lines for (int i = 1; i <= n; i++) { // For loop to keep track of // numbers in each line for (int j = 1; j <= i; j++) cout << f[fiboNum++] << \" \"; cout << endl; }} // Driver codeint main(){ int n = 5; fiboTriangle(n); return 0;}",
"e": 1749,
"s": 735,
"text": null
},
{
"code": "// Java Implementation for// Fibonacci triangleimport java.io.*; class GFG { // function to fill Fibonacci Numbers // in f[] static void fib(int f[], int N) { // 1st and 2nd number of the // series are 1 and 1 f[1] = 1; f[2] = 1; for (int i = 3; i <= N; i++) // Add the previous 2 numbers // in the series and store it f[i] = f[i - 1] + f[i - 2]; } static void fiboTriangle(int n) { // Fill Fibonacci numbers in f[] using // fib(). We need N = n*(n+1)/2 Fibonacci // numbers to make a triangle of height // n int N = n * (n + 1) / 2; int f[] = new int[N + 1]; fib(f, N); // To store next Fibonacci // Number to print int fiboNum = 1; // for loop to keep track of // number of lines for (int i = 1; i <= n; i++) { // For loop to keep track of // numbers in each line for (int j = 1; j <= i; j++) System.out.print(f[fiboNum++] + \" \"); System.out.println(); } } // Driver code public static void main(String args[]) { int n = 5; fiboTriangle(n); }} /*This code is contributed by Nikita Tiwari.*/",
"e": 3025,
"s": 1749,
"text": null
},
{
"code": "# Python 3 Implementation for# Fibonacci triangle # function to fill Fibonacci# Numbers in f[]def fib(f, N): # 1st and 2nd number of # the series are 1 and 1 f[1] = 1 f[2] = 1 for i in range(3, N + 1): # Add the previous 2 numbers # in the series and store it f[i] = f[i - 1] + f[i - 2] def fiboTriangle(n): # Fill Fibonacci numbers in # f[] using fib(). We need # N = n*(n + 1)/2 Fibonacci # numbers to make a triangle # of height n N = n * (n + 1) // 2 f = [0] * (N + 1) fib(f, N) # To store next Fibonacci # Number to print fiboNum = 1 # for loop to keep track of # number of lines for i in range(1, n + 1): # For loop to keep track of # numbers in each line for j in range(1, i + 1): print(f[fiboNum], \" \", end=\"\") fiboNum = fiboNum + 1 print() # Driver coden = 5fiboTriangle(n) # This code is contributed by Nikita Tiwari.",
"e": 3993,
"s": 3025,
"text": null
},
{
"code": "// C# Implementation for// Fibonacci triangleusing System; class GFG { // function to fill Fibonacci Numbers // in f[] static void fib(int[] f, int N) { // 1st and 2nd number of the // series are 1 and 1 f[1] = 1; f[2] = 1; for (int i = 3; i <= N; i++) // Add the previous 2 numbers // in the series and store it f[i] = f[i - 1] + f[i - 2]; } static void fiboTriangle(int n) { // Fill Fibonacci numbers in f[] using // fib(). We need N = n*(n+1)/2 Fibonacci // numbers to make a triangle of height // n int N = n * (n + 1) / 2; int[] f = new int[N + 1]; fib(f, N); // To store next Fibonacci // Number to print int fiboNum = 1; // for loop to keep track of // number of lines for (int i = 1; i <= n; i++) { // For loop to keep track of // numbers in each line for (int j = 1; j <= i; j++) Console.Write(f[fiboNum++] + \" \"); Console.WriteLine(); } } // Driver code public static void Main() { int n = 5; fiboTriangle(n); }} /*This code is contributed by vt_m.*/",
"e": 5237,
"s": 3993,
"text": null
},
{
"code": "<?php// PHP Implementation for// Fibonacci triangle // function to fill// Fibonacci Numbers// in f[]function fib(&$f, $N){ // 1st and 2nd number // of the series are // 1 and 1 $f[1] = 1; $f[2] = 1; for ($i = 3; $i <= $N; $i++) // Add the previous // 2 numbers in the // series and store it $f[$i] = $f[$i - 1] + $f[$i - 2];} function fiboTriangle($n){ // Fill Fibonacci numbers // in f[] using fib(). We // need N = n*(n+1)/2 // Fibonacci numbers to make // a triangle of height n $N = $n * ($n + 1) / 2; $f = array(); fib($f, $N); // To store next // Fibonacci Number // to print $fiboNum = 1; // for loop to keep track // of number of lines for ($i = 1; $i <= $n; $i++) { // For loop to keep track // of numbers in each line for ($j = 1;$j <= $i; $j++) echo ($f[$fiboNum++] . \" \"); echo(\"\\n\"); }} // Driver code$n = 5;fiboTriangle($n); // This code is contributed by// Manish Shaw(manishshaw1)?>",
"e": 6325,
"s": 5237,
"text": null
},
{
"code": "<script> // JavaScript implementation for// Fibonacci triangle // Function to fill Fibonacci Numbers// in f[]function fib(f, N){ // 1st and 2nd number of the // series are 1 and 1 f[1] = 1; f[2] = 1; for(var i = 3; i <= N; i++) // Add the previous 2 numbers // in the series and store it f[i] = f[i - 1] + f[i - 2];} function fiboTriangle(n){ // Fill Fibonacci numbers in f[] using // fib(). We need N = n*(n+1)/2 Fibonacci // numbers to make a triangle of height // n var N = (n * (n + 1)) / 2; var f = [...Array(N + 1)]; fib(f, N); // To store next Fibonacci Number to print var fiboNum = 1; // for loop to keep track of // number of lines for(var i = 1; i <= n; i++) { // For loop to keep track of // numbers in each line for(var j = 1; j <= i; j++) document.write(f[fiboNum++] + \" \"); document.write(\"<br>\"); }} // Driver codevar n = 5; fiboTriangle(n); // This code is contributed by rdtank </script>",
"e": 7383,
"s": 6325,
"text": null
},
{
"code": null,
"e": 7392,
"s": 7383,
"text": "Output: "
},
{
"code": null,
"e": 7440,
"s": 7392,
"text": "1 \n1 2 \n3 5 8 \n13 21 34 55 \n89 144 233 377 610 "
},
{
"code": null,
"e": 7454,
"s": 7442,
"text": "manishshaw1"
},
{
"code": null,
"e": 7461,
"s": 7454,
"text": "rdtank"
},
{
"code": null,
"e": 7477,
"s": 7461,
"text": "gourangakataky4"
},
{
"code": null,
"e": 7487,
"s": 7477,
"text": "Fibonacci"
},
{
"code": null,
"e": 7500,
"s": 7487,
"text": "Mathematical"
},
{
"code": null,
"e": 7513,
"s": 7500,
"text": "Mathematical"
},
{
"code": null,
"e": 7523,
"s": 7513,
"text": "Fibonacci"
}
] |
Hazelcast - Setup | Hazelcast requires Java 1.6 or above. Hazelcast can also be used with .NET, C++, or other JVM based languages like Scala and Clojure. However, for this tutorial, we are going to use Java 8.
Before we move on, following is the project setup that we will use for this tutorial.
hazelcast/
├── com.example.demo/
│ ├── SingleInstanceHazelcastExample.java
│ ├── MultiInstanceHazelcastExample.java
│ ├── Server.java
│ └── ....
├── pom.xml
├── target/
├── hazelcast.xml
├── hazelcast-multicast.xml
├── ...
For now, we can just create the package, i.e., com.example.demo inside the hazelcast directory. Then, just cd to that directory. We will look at other files in the upcoming sections.
Installing Hazelcast simply involves adding a JAR file to your build file. POM file or build.gradle based on whether you are using Maven or Gradle respectively.
If you are using Gradle, adding the following to build.gradle file would be enough −
dependencies {
compile "com.hazelcast:hazelcast:3.12.12”
}
We will use the following POM for our tutorial −
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>1.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Hazelcast</description>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>com.hazelcast</groupId>
<artifactId>hazelcast</artifactId>
<version>3.12.12</version>
</dependency>
</dependencies>
<!-- Below build plugin is not needed for Hazelcast, it is being used only to created a shaded JAR so that -->
<!-- using the output i.e. the JAR becomes simple for testing snippets in the tutorial-->
<build>
<plugins>
<plugin>
<!-- Create a shaded JAR and specify the entry point class-->
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.2.4</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2153,
"s": 1963,
"text": "Hazelcast requires Java 1.6 or above. Hazelcast can also be used with .NET, C++, or other JVM based languages like Scala and Clojure. However, for this tutorial, we are going to use Java 8."
},
{
"code": null,
"e": 2239,
"s": 2153,
"text": "Before we move on, following is the project setup that we will use for this tutorial."
},
{
"code": null,
"e": 2463,
"s": 2239,
"text": "hazelcast/\n├── com.example.demo/\n│ ├── SingleInstanceHazelcastExample.java\n│ ├── MultiInstanceHazelcastExample.java\n│ ├── Server.java\n│ └── ....\n├── pom.xml\n├── target/\n├── hazelcast.xml\n├── hazelcast-multicast.xml\n├── ...\n"
},
{
"code": null,
"e": 2646,
"s": 2463,
"text": "For now, we can just create the package, i.e., com.example.demo inside the hazelcast directory. Then, just cd to that directory. We will look at other files in the upcoming sections."
},
{
"code": null,
"e": 2807,
"s": 2646,
"text": "Installing Hazelcast simply involves adding a JAR file to your build file. POM file or build.gradle based on whether you are using Maven or Gradle respectively."
},
{
"code": null,
"e": 2892,
"s": 2807,
"text": "If you are using Gradle, adding the following to build.gradle file would be enough −"
},
{
"code": null,
"e": 2954,
"s": 2892,
"text": "dependencies {\n compile \"com.hazelcast:hazelcast:3.12.12”\n}"
},
{
"code": null,
"e": 3003,
"s": 2954,
"text": "We will use the following POM for our tutorial −"
},
{
"code": null,
"e": 4598,
"s": 3003,
"text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\"\n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n <modelVersion>1.0.0</modelVersion>\n <groupId>com.example</groupId>\n <artifactId>demo</artifactId>\n <version>0.0.1-SNAPSHOT</version>\n <name>demo</name>\n <description>Demo project for Hazelcast</description>\n\n <properties>\n <maven.compiler.source>1.8</maven.compiler.source>\n <maven.compiler.target>1.8</maven.compiler.target>\n </properties>\n\n <dependencies>\n <dependency>\n <groupId>com.hazelcast</groupId>\n <artifactId>hazelcast</artifactId>\n <version>3.12.12</version>\n </dependency>\n </dependencies>\n\n <!-- Below build plugin is not needed for Hazelcast, it is being used only to created a shaded JAR so that -->\n <!-- using the output i.e. the JAR becomes simple for testing snippets in the tutorial-->\n <build>\n <plugins>\n <plugin>\n <!-- Create a shaded JAR and specify the entry point class-->\n <groupId>org.apache.maven.plugins</groupId>\n <artifactId>maven-shade-plugin</artifactId>\n <version>3.2.4</version>\n <executions>\n <execution>\n <phase>package</phase>\n <goals>\n <goal>shade</goal>\n </goals>\n </execution>\n </executions>\n </plugin>\n </plugins>\n </build>\n</project>"
},
{
"code": null,
"e": 4605,
"s": 4598,
"text": " Print"
},
{
"code": null,
"e": 4616,
"s": 4605,
"text": " Add Notes"
}
] |
Python - Convert a set into dictionary | Python provides lot of flexibility to handle different types of data structures. There may be a need when you have to convert one Data Structure to another for a better use or better analysis of the data. In this article we will see how to convert a Python set to a Python dictionary.
The dict() can be used to take input parameters and convert them to a dictionary. We also use the zip function to group the keys and values together which finally become the key value pair in the dictionary.
Live Demo
list_keys = {1,2,3,4}
list_values = {'Mon','Tue','Wed','Thu'}
new_dict = dict(zip(list_keys, list_values))
print(new_dict)
print(type(new_dict))
Running the above code gives us the following result −
{1: 'Mon', 2: 'Tue', 3: 'Thu', 4: 'Wed'}
<class 'dict'>
When we need a dictionary with different keys but the value of each key is same, we can use this method as shown below.
Live Demo
list_keys = {1,2,3,4}
new_dict = dict.fromkeys(list_keys,'Mon')
print(new_dict)
print(type(new_dict))
Running the above code gives us the following result −
{1: 'Mon', 2: 'Mon', 3: 'Mon', 4: 'Mon'}
<class 'dict'>
We use a similar method as the previous approach except that in this case we have dictionary comprehension.
Live Demo
list_keys = {1,2,3,4}
new_dict = {element:'Tue' for element in list_keys}
print(new_dict)
print(type(new_dict))
Running the above code gives us the following result −
{1: 'Tue', 2: 'Tue', 3: 'Tue', 4: 'Tue'}
<class 'dict'> | [
{
"code": null,
"e": 1347,
"s": 1062,
"text": "Python provides lot of flexibility to handle different types of data structures. There may be a need when you have to convert one Data Structure to another for a better use or better analysis of the data. In this article we will see how to convert a Python set to a Python dictionary."
},
{
"code": null,
"e": 1555,
"s": 1347,
"text": "The dict() can be used to take input parameters and convert them to a dictionary. We also use the zip function to group the keys and values together which finally become the key value pair in the dictionary."
},
{
"code": null,
"e": 1566,
"s": 1555,
"text": " Live Demo"
},
{
"code": null,
"e": 1711,
"s": 1566,
"text": "list_keys = {1,2,3,4}\nlist_values = {'Mon','Tue','Wed','Thu'}\nnew_dict = dict(zip(list_keys, list_values))\nprint(new_dict)\nprint(type(new_dict))"
},
{
"code": null,
"e": 1766,
"s": 1711,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 1822,
"s": 1766,
"text": "{1: 'Mon', 2: 'Tue', 3: 'Thu', 4: 'Wed'}\n<class 'dict'>"
},
{
"code": null,
"e": 1942,
"s": 1822,
"text": "When we need a dictionary with different keys but the value of each key is same, we can use this method as shown below."
},
{
"code": null,
"e": 1953,
"s": 1942,
"text": " Live Demo"
},
{
"code": null,
"e": 2055,
"s": 1953,
"text": "list_keys = {1,2,3,4}\nnew_dict = dict.fromkeys(list_keys,'Mon')\nprint(new_dict)\nprint(type(new_dict))"
},
{
"code": null,
"e": 2110,
"s": 2055,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 2166,
"s": 2110,
"text": "{1: 'Mon', 2: 'Mon', 3: 'Mon', 4: 'Mon'}\n<class 'dict'>"
},
{
"code": null,
"e": 2274,
"s": 2166,
"text": "We use a similar method as the previous approach except that in this case we have dictionary comprehension."
},
{
"code": null,
"e": 2285,
"s": 2274,
"text": " Live Demo"
},
{
"code": null,
"e": 2397,
"s": 2285,
"text": "list_keys = {1,2,3,4}\nnew_dict = {element:'Tue' for element in list_keys}\nprint(new_dict)\nprint(type(new_dict))"
},
{
"code": null,
"e": 2452,
"s": 2397,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 2508,
"s": 2452,
"text": "{1: 'Tue', 2: 'Tue', 3: 'Tue', 4: 'Tue'}\n<class 'dict'>"
}
] |
Count of Ordered Pairs (X, Y) satisfying the Equation 1/X + 1/Y = 1/N - GeeksforGeeks | 19 Dec, 2021
Given a positive integer N, the task is to find the number of ordered pairs (X, Y) where both X and Y are positive integers, such that they satisfy the equation 1/X + 1/Y = 1/N.
Examples:
Input: N = 5 Output: 3 Explanation: Only 3 pairs {(30,6), (10,10), (6,30)} satisfy the given equation.
Input: N = 360 Output: 105
Approach: Follow the steps to solve the problem:
Solve for X using the given equation.
1/X + 1/Y = 1/N => 1/X = 1/N – 1/Y => 1/X = (Y – N) / NY => X = NY / (Y – N)
X = [ NY / (Y – N) ] * (1)
=> X = [ NY / (Y – N) ] * [1 – N/Y + N/Y]
=> X = [ NY / (Y – N) ] * [(Y- N)/Y + N/Y]
=> X = N + N2 / (Y – N)
Therefore, it can be observed that, to have a positive integer X, the remainder when N2 is divided by (Y – N) needs to be 0.
It can be observed that the minimum value of Y can be N + 1 (so that denominator Y – N > 0) and the maximum value of Y can be N2 + N so that N2/(Y – N) remains a positive integer ≥ 1.
Then iterate over the maximum and minimum possible values of Y, and for each value of Y for which N2 % (Y – N) == 0, increment count.
Finally, return count as the number of ordered pairs.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ Program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find number of ordered// positive integer pairs (x,y) such// that they satisfy the equationvoid solve(int n){ // Initialize answer variable int ans = 0; // Iterate over all possible values of y for (int y = n + 1; y <= n * n + n; y++) { // For valid x and y, // (n*n)%(y - n) has to be 0 if ((n * n) % (y - n) == 0) { // Increment count of ordered pairs ans += 1; } } // Print the answer cout << ans;} // Driver Codeint main(){ int n = 5; // Function call solve(n); return 0;}
// Java program for the above approachclass GFG{ // Function to find number of ordered// positive integer pairs (x,y) such// that they satisfy the equationstatic void solve(int n){ // Initialize answer variable int ans = 0; // Iterate over all possible values of y for(int y = n + 1; y <= n * n + n; y++) { // For valid x and y, // (n*n)%(y - n) has to be 0 if ((n * n) % (y - n) == 0) { // Increment count of ordered pairs ans += 1; } } // Print the answer System.out.print(ans);} // Driver Codepublic static void main(String[] args){ int n = 5; // Function call solve(n);}} // This code is contributed by Amit Katiyar
# Python3 program for the above approach # Function to find number of ordered# positive integer pairs (x,y) such# that they satisfy the equationdef solve(n): # Initialize answer variable ans = 0 # Iterate over all possible values of y y = n + 1 while(y <= n * n + n): # For valid x and y, # (n*n)%(y - n) has to be 0 if ((n * n) % (y - n) == 0): # Increment count of ordered pairs ans += 1 y += 1 # Print the answer print(ans) # Driver Coden = 5 # Function callsolve(n) # This code is contributed by Shivam Singh
// C# program for the above approachusing System; class GFG{ // Function to find number of ordered// positive integer pairs (x,y) such// that they satisfy the equationstatic void solve(int n){ // Initialize answer variable int ans = 0; // Iterate over all possible values of y for(int y = n + 1; y <= n * n + n; y++) { // For valid x and y, // (n*n)%(y - n) has to be 0 if ((n * n) % (y - n) == 0) { // Increment count of ordered pairs ans += 1; } } // Print the answer Console.Write(ans);} // Driver Codepublic static void Main(String[] args){ int n = 5; // Function call solve(n);}} // This code is contributed by Amit Katiyar
<script>// javascript program for the above approach // Function to find number of ordered // positive integer pairs (x,y) such // that they satisfy the equation function solve(n) { // Initialize answer variable var ans = 0; // Iterate over all possible values of y for (y = n + 1; y <= n * n + n; y++) { // For valid x and y, // (n*n)%(y - n) has to be 0 if ((n * n) % (y - n) == 0) { // Increment count of ordered pairs ans += 1; } } // Print the answer document.write(ans); } // Driver Code var n = 5; // Function call solve(n); // This code contributed by umadevi9616</script>
Output:
3
Time Complexity: O(logN)Auxiliary Space: O(1)
SHIVAMSINGH67
amit143katiyar
umadevi9616
yathaarthsuri
simranarora5sos
counter
Numbers
Mathematical
Puzzles
School Programming
Searching
Searching
Mathematical
Numbers
Puzzles
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Modulo Operator (%) in C/C++ with Examples
Merge two sorted arrays
Prime Numbers
Program to find sum of elements in a given array
Program for factorial of a number
SDE SHEET - A Complete Guide for SDE Preparation
Puzzle 1 | (How to Measure 45 minutes using two identical wires?)
Puzzle 2 | (Find ages of daughters)
Algorithm to solve Rubik's Cube
Puzzle 3 | (Calculate total distance travelled by bee) | [
{
"code": null,
"e": 25380,
"s": 25352,
"text": "\n19 Dec, 2021"
},
{
"code": null,
"e": 25558,
"s": 25380,
"text": "Given a positive integer N, the task is to find the number of ordered pairs (X, Y) where both X and Y are positive integers, such that they satisfy the equation 1/X + 1/Y = 1/N."
},
{
"code": null,
"e": 25568,
"s": 25558,
"text": "Examples:"
},
{
"code": null,
"e": 25672,
"s": 25568,
"text": "Input: N = 5 Output: 3 Explanation: Only 3 pairs {(30,6), (10,10), (6,30)} satisfy the given equation. "
},
{
"code": null,
"e": 25701,
"s": 25672,
"text": "Input: N = 360 Output: 105 "
},
{
"code": null,
"e": 25752,
"s": 25701,
"text": "Approach: Follow the steps to solve the problem: "
},
{
"code": null,
"e": 25792,
"s": 25752,
"text": "Solve for X using the given equation. "
},
{
"code": null,
"e": 25870,
"s": 25792,
"text": "1/X + 1/Y = 1/N => 1/X = 1/N – 1/Y => 1/X = (Y – N) / NY => X = NY / (Y – N) "
},
{
"code": null,
"e": 25897,
"s": 25870,
"text": "X = [ NY / (Y – N) ] * (1)"
},
{
"code": null,
"e": 25939,
"s": 25897,
"text": "=> X = [ NY / (Y – N) ] * [1 – N/Y + N/Y]"
},
{
"code": null,
"e": 25982,
"s": 25939,
"text": "=> X = [ NY / (Y – N) ] * [(Y- N)/Y + N/Y]"
},
{
"code": null,
"e": 26006,
"s": 25982,
"text": "=> X = N + N2 / (Y – N)"
},
{
"code": null,
"e": 26131,
"s": 26006,
"text": "Therefore, it can be observed that, to have a positive integer X, the remainder when N2 is divided by (Y – N) needs to be 0."
},
{
"code": null,
"e": 26315,
"s": 26131,
"text": "It can be observed that the minimum value of Y can be N + 1 (so that denominator Y – N > 0) and the maximum value of Y can be N2 + N so that N2/(Y – N) remains a positive integer ≥ 1."
},
{
"code": null,
"e": 26449,
"s": 26315,
"text": "Then iterate over the maximum and minimum possible values of Y, and for each value of Y for which N2 % (Y – N) == 0, increment count."
},
{
"code": null,
"e": 26503,
"s": 26449,
"text": "Finally, return count as the number of ordered pairs."
},
{
"code": null,
"e": 26554,
"s": 26503,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 26558,
"s": 26554,
"text": "C++"
},
{
"code": null,
"e": 26563,
"s": 26558,
"text": "Java"
},
{
"code": null,
"e": 26571,
"s": 26563,
"text": "Python3"
},
{
"code": null,
"e": 26574,
"s": 26571,
"text": "C#"
},
{
"code": null,
"e": 26585,
"s": 26574,
"text": "Javascript"
},
{
"code": "// C++ Program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find number of ordered// positive integer pairs (x,y) such// that they satisfy the equationvoid solve(int n){ // Initialize answer variable int ans = 0; // Iterate over all possible values of y for (int y = n + 1; y <= n * n + n; y++) { // For valid x and y, // (n*n)%(y - n) has to be 0 if ((n * n) % (y - n) == 0) { // Increment count of ordered pairs ans += 1; } } // Print the answer cout << ans;} // Driver Codeint main(){ int n = 5; // Function call solve(n); return 0;}",
"e": 27243,
"s": 26585,
"text": null
},
{
"code": "// Java program for the above approachclass GFG{ // Function to find number of ordered// positive integer pairs (x,y) such// that they satisfy the equationstatic void solve(int n){ // Initialize answer variable int ans = 0; // Iterate over all possible values of y for(int y = n + 1; y <= n * n + n; y++) { // For valid x and y, // (n*n)%(y - n) has to be 0 if ((n * n) % (y - n) == 0) { // Increment count of ordered pairs ans += 1; } } // Print the answer System.out.print(ans);} // Driver Codepublic static void main(String[] args){ int n = 5; // Function call solve(n);}} // This code is contributed by Amit Katiyar",
"e": 27987,
"s": 27243,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to find number of ordered# positive integer pairs (x,y) such# that they satisfy the equationdef solve(n): # Initialize answer variable ans = 0 # Iterate over all possible values of y y = n + 1 while(y <= n * n + n): # For valid x and y, # (n*n)%(y - n) has to be 0 if ((n * n) % (y - n) == 0): # Increment count of ordered pairs ans += 1 y += 1 # Print the answer print(ans) # Driver Coden = 5 # Function callsolve(n) # This code is contributed by Shivam Singh",
"e": 28589,
"s": 27987,
"text": null
},
{
"code": "// C# program for the above approachusing System; class GFG{ // Function to find number of ordered// positive integer pairs (x,y) such// that they satisfy the equationstatic void solve(int n){ // Initialize answer variable int ans = 0; // Iterate over all possible values of y for(int y = n + 1; y <= n * n + n; y++) { // For valid x and y, // (n*n)%(y - n) has to be 0 if ((n * n) % (y - n) == 0) { // Increment count of ordered pairs ans += 1; } } // Print the answer Console.Write(ans);} // Driver Codepublic static void Main(String[] args){ int n = 5; // Function call solve(n);}} // This code is contributed by Amit Katiyar",
"e": 29342,
"s": 28589,
"text": null
},
{
"code": "<script>// javascript program for the above approach // Function to find number of ordered // positive integer pairs (x,y) such // that they satisfy the equation function solve(n) { // Initialize answer variable var ans = 0; // Iterate over all possible values of y for (y = n + 1; y <= n * n + n; y++) { // For valid x and y, // (n*n)%(y - n) has to be 0 if ((n * n) % (y - n) == 0) { // Increment count of ordered pairs ans += 1; } } // Print the answer document.write(ans); } // Driver Code var n = 5; // Function call solve(n); // This code contributed by umadevi9616</script>",
"e": 30096,
"s": 29342,
"text": null
},
{
"code": null,
"e": 30106,
"s": 30096,
"text": "Output: "
},
{
"code": null,
"e": 30108,
"s": 30106,
"text": "3"
},
{
"code": null,
"e": 30154,
"s": 30108,
"text": "Time Complexity: O(logN)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 30168,
"s": 30154,
"text": "SHIVAMSINGH67"
},
{
"code": null,
"e": 30183,
"s": 30168,
"text": "amit143katiyar"
},
{
"code": null,
"e": 30195,
"s": 30183,
"text": "umadevi9616"
},
{
"code": null,
"e": 30209,
"s": 30195,
"text": "yathaarthsuri"
},
{
"code": null,
"e": 30225,
"s": 30209,
"text": "simranarora5sos"
},
{
"code": null,
"e": 30233,
"s": 30225,
"text": "counter"
},
{
"code": null,
"e": 30241,
"s": 30233,
"text": "Numbers"
},
{
"code": null,
"e": 30254,
"s": 30241,
"text": "Mathematical"
},
{
"code": null,
"e": 30262,
"s": 30254,
"text": "Puzzles"
},
{
"code": null,
"e": 30281,
"s": 30262,
"text": "School Programming"
},
{
"code": null,
"e": 30291,
"s": 30281,
"text": "Searching"
},
{
"code": null,
"e": 30301,
"s": 30291,
"text": "Searching"
},
{
"code": null,
"e": 30314,
"s": 30301,
"text": "Mathematical"
},
{
"code": null,
"e": 30322,
"s": 30314,
"text": "Numbers"
},
{
"code": null,
"e": 30330,
"s": 30322,
"text": "Puzzles"
},
{
"code": null,
"e": 30428,
"s": 30330,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30471,
"s": 30428,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 30495,
"s": 30471,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 30509,
"s": 30495,
"text": "Prime Numbers"
},
{
"code": null,
"e": 30558,
"s": 30509,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 30592,
"s": 30558,
"text": "Program for factorial of a number"
},
{
"code": null,
"e": 30641,
"s": 30592,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 30707,
"s": 30641,
"text": "Puzzle 1 | (How to Measure 45 minutes using two identical wires?)"
},
{
"code": null,
"e": 30743,
"s": 30707,
"text": "Puzzle 2 | (Find ages of daughters)"
},
{
"code": null,
"e": 30775,
"s": 30743,
"text": "Algorithm to solve Rubik's Cube"
}
] |
How to programmatically scroll to a specific position in listView in Android? | This example demonstrates how do I programmatically scroll to a specific position in android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/rl"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp"
tools:context=".MainActivity">
<Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ListView Scroll To Position 22" />
<ListView
android:id="@+id/listView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/btn" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.java
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ListView listView = findViewById(R.id.listView);
Button btn = findViewById(R.id.btn);
String[] footballPlayers = new String[] {
"Cristiano Ronaldo",
"Lionel Messi",
"Neymar Jnr",
"Eden Hazard",
"Isco",
"Gareth Bale",
"Sergio Buesquets",
"Zlatan Ibrahimovic",
"GG Buffon",
"Iker Casillas",
"Rafael Varane",
"Zinedine Zidane",
"Menphis Depay",
"Gerard Pique",
"Victor Valdes",
"David De Gea",
"Mo Salah",
"Ronaldinio",
"Marco Rues",
"Asencio",
"Luis Figo",
"Sergio Ramos",
"Maldini",
"Marcelo",
"Karim Benzema",
"Sir Alex Firguson"
};
final List<String> footballPlayers = new ArrayList<>(Arrays.asList(footballPlayers));
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, footballPlayers);
listView.setAdapter(arrayAdapter);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
listView.smoothScrollToPosition(22);
}
});
}
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
Click here to download the project code. | [
{
"code": null,
"e": 1156,
"s": 1062,
"text": "This example demonstrates how do I programmatically scroll to a specific position in android."
},
{
"code": null,
"e": 1285,
"s": 1156,
"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": 1350,
"s": 1285,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2048,
"s": 1350,
"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 android:id=\"@+id/rl\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:padding=\"10dp\"\n tools:context=\".MainActivity\">\n <Button\n android:id=\"@+id/btn\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"ListView Scroll To Position 22\" />\n <ListView\n android:id=\"@+id/listView\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_below=\"@id/btn\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 2105,
"s": 2048,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 3813,
"s": 2105,
"text": "import android.os.Bundle;\nimport android.app.Activity;\nimport android.view.View;\nimport android.widget.ArrayAdapter;\nimport android.widget.Button;\nimport android.widget.ListView;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\npublic class MainActivity extends Activity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n final ListView listView = findViewById(R.id.listView);\n Button btn = findViewById(R.id.btn);\n String[] footballPlayers = new String[] {\n \"Cristiano Ronaldo\",\n \"Lionel Messi\",\n \"Neymar Jnr\",\n \"Eden Hazard\",\n \"Isco\",\n \"Gareth Bale\",\n \"Sergio Buesquets\",\n \"Zlatan Ibrahimovic\",\n \"GG Buffon\",\n \"Iker Casillas\",\n \"Rafael Varane\",\n \"Zinedine Zidane\",\n \"Menphis Depay\",\n \"Gerard Pique\",\n \"Victor Valdes\",\n \"David De Gea\",\n \"Mo Salah\",\n \"Ronaldinio\",\n \"Marco Rues\",\n \"Asencio\",\n \"Luis Figo\",\n \"Sergio Ramos\",\n \"Maldini\",\n \"Marcelo\",\n \"Karim Benzema\",\n \"Sir Alex Firguson\"\n };\n final List<String> footballPlayers = new ArrayList<>(Arrays.asList(footballPlayers));\n final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, footballPlayers);\n listView.setAdapter(arrayAdapter);\n btn.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n listView.smoothScrollToPosition(22);\n }\n });\n }\n}"
},
{
"code": null,
"e": 3868,
"s": 3813,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 4538,
"s": 3868,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 4885,
"s": 4538,
"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": 4926,
"s": 4885,
"text": "Click here to download the project code."
}
] |
Numpy | Data Type Objects - GeeksforGeeks | 15 Nov, 2018
Every ndarray has an associated data type (dtype) object. This data type object (dtype) informs us about the layout of the array. This means it gives us information about :
Type of the data (integer, float, Python object etc.)
Size of the data (number of bytes)
Byte order of the data (little-endian or big-endian)
If the data type is a sub-array, what is its shape and data type.
The values of an ndarray are stored in a buffer which can be thought of as a contiguous block of memory bytes. So how these bytes will be interpreted is given by the dtype object.
Constructing a data type (dtype) object : Data type object is an instance of numpy.dtype class and it can be created using numpy.dtype.
Parameters:
obj: Object to be converted to a data type object.align : [bool, optional] Add padding to the fields to match what a C compiler would output for a similar C-struct.copy : [bool, optional] Make a new copy of the data-type object. If False, the result may just be a reference to a built-in data-type object.
Output:
int16
Output:
Byte order is: >
Size is: 4
Name of data type is: int32
The type specifier (i4 in above case) can take different forms:
b1, i1, i2, i4, i8, u1, u2, u4, u8, f2, f4, f8, c8, c16, a (representing bytes, ints, unsigned ints, floats, complex and fixed length strings of specified byte lengths)
int8,...,uint8,...,float16, float32, float64, complex64, complex128 (this time with bit sizes)
Note : dtype is different from type.
Output:
type is:
dtype is: int32
Data type Objects with Structured Arrays : Data type objects are useful for creating structured arrays. A structured array is the one which contains different types of data. Structured arrays can be accessed with the help of fields.
A field is like specifying a name to the object. In case of structured arrays, the dtype object will also be structured.
Output:
('<f8', (2,))
Output:
('John', [ 6., 7.])
Grades of John are: [ 6. 7.]
Names are: ['Sarah' 'John']
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Comments
Old Comments
Python Program for Breadth First Search or BFS for a Graph
Best Time to Buy and Sell Stock
Must Do Coding Questions for Product Based Companies
Axios in React: A Guide for Beginners
C++ Program For Inserting A Node In A Linked List
How to create a Blog app using ReactJS ?
Implementation of Bit Stuffing and Bit Destuffing
How to set background images in ReactJS ?
Tailwind CSS vs Bootstrap
Image Sharpening Using Laplacian Filter and High Boost Filtering in MATLAB | [
{
"code": null,
"e": 41448,
"s": 41420,
"text": "\n15 Nov, 2018"
},
{
"code": null,
"e": 41621,
"s": 41448,
"text": "Every ndarray has an associated data type (dtype) object. This data type object (dtype) informs us about the layout of the array. This means it gives us information about :"
},
{
"code": null,
"e": 41675,
"s": 41621,
"text": "Type of the data (integer, float, Python object etc.)"
},
{
"code": null,
"e": 41710,
"s": 41675,
"text": "Size of the data (number of bytes)"
},
{
"code": null,
"e": 41763,
"s": 41710,
"text": "Byte order of the data (little-endian or big-endian)"
},
{
"code": null,
"e": 41829,
"s": 41763,
"text": "If the data type is a sub-array, what is its shape and data type."
},
{
"code": null,
"e": 42011,
"s": 41829,
"text": "The values of an ndarray are stored in a buffer which can be thought of as a contiguous block of memory bytes. So how these bytes will be interpreted is given by the dtype object. "
},
{
"code": null,
"e": 42147,
"s": 42011,
"text": "Constructing a data type (dtype) object : Data type object is an instance of numpy.dtype class and it can be created using numpy.dtype."
},
{
"code": null,
"e": 42159,
"s": 42147,
"text": "Parameters:"
},
{
"code": null,
"e": 42465,
"s": 42159,
"text": "obj: Object to be converted to a data type object.align : [bool, optional] Add padding to the fields to match what a C compiler would output for a similar C-struct.copy : [bool, optional] Make a new copy of the data-type object. If False, the result may just be a reference to a built-in data-type object."
},
{
"code": null,
"e": 42473,
"s": 42465,
"text": "Output:"
},
{
"code": null,
"e": 42479,
"s": 42473,
"text": "int16"
},
{
"code": null,
"e": 42487,
"s": 42479,
"text": "Output:"
},
{
"code": null,
"e": 42544,
"s": 42487,
"text": "Byte order is: >\nSize is: 4\nName of data type is: int32\n"
},
{
"code": null,
"e": 42608,
"s": 42544,
"text": "The type specifier (i4 in above case) can take different forms:"
},
{
"code": null,
"e": 42777,
"s": 42608,
"text": "b1, i1, i2, i4, i8, u1, u2, u4, u8, f2, f4, f8, c8, c16, a (representing bytes, ints, unsigned ints, floats, complex and fixed length strings of specified byte lengths)"
},
{
"code": null,
"e": 42872,
"s": 42777,
"text": "int8,...,uint8,...,float16, float32, float64, complex64, complex128 (this time with bit sizes)"
},
{
"code": null,
"e": 42910,
"s": 42872,
"text": "Note : dtype is different from type. "
},
{
"code": null,
"e": 42918,
"s": 42910,
"text": "Output:"
},
{
"code": null,
"e": 42949,
"s": 42918,
"text": "type is: \ndtype is: int32\n"
},
{
"code": null,
"e": 43183,
"s": 42949,
"text": " Data type Objects with Structured Arrays : Data type objects are useful for creating structured arrays. A structured array is the one which contains different types of data. Structured arrays can be accessed with the help of fields."
},
{
"code": null,
"e": 43305,
"s": 43183,
"text": "A field is like specifying a name to the object. In case of structured arrays, the dtype object will also be structured. "
},
{
"code": null,
"e": 43313,
"s": 43305,
"text": "Output:"
},
{
"code": null,
"e": 43327,
"s": 43313,
"text": "('<f8', (2,))"
},
{
"code": null,
"e": 43335,
"s": 43327,
"text": "Output:"
},
{
"code": null,
"e": 43417,
"s": 43335,
"text": "('John', [ 6., 7.])\nGrades of John are: [ 6. 7.]\nNames are: ['Sarah' 'John']\n"
},
{
"code": null,
"e": 43515,
"s": 43417,
"text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here."
},
{
"code": null,
"e": 43524,
"s": 43515,
"text": "Comments"
},
{
"code": null,
"e": 43537,
"s": 43524,
"text": "Old Comments"
},
{
"code": null,
"e": 43596,
"s": 43537,
"text": "Python Program for Breadth First Search or BFS for a Graph"
},
{
"code": null,
"e": 43628,
"s": 43596,
"text": "Best Time to Buy and Sell Stock"
},
{
"code": null,
"e": 43681,
"s": 43628,
"text": "Must Do Coding Questions for Product Based Companies"
},
{
"code": null,
"e": 43719,
"s": 43681,
"text": "Axios in React: A Guide for Beginners"
},
{
"code": null,
"e": 43769,
"s": 43719,
"text": "C++ Program For Inserting A Node In A Linked List"
},
{
"code": null,
"e": 43810,
"s": 43769,
"text": "How to create a Blog app using ReactJS ?"
},
{
"code": null,
"e": 43860,
"s": 43810,
"text": "Implementation of Bit Stuffing and Bit Destuffing"
},
{
"code": null,
"e": 43902,
"s": 43860,
"text": "How to set background images in ReactJS ?"
},
{
"code": null,
"e": 43928,
"s": 43902,
"text": "Tailwind CSS vs Bootstrap"
}
] |
Gentle Start to Natural Language Processing using Python | by Rahil Shaikh | Towards Data Science | Gentle Start to Natural Language Processing using Python
What is NLP ?
Natural language processing (NLP) is about developing applications and services that are able to understand human languages. Some Practical examples of NLP are speech recognition for eg: google voice search, understanding what the content is about or sentiment analysis etc.
Benefits of NLP
As all of you know, there are millions of gigabytes every day are generated by blogs, social websites, and web pages.
There are many companies gathering all of these data for understanding users and their passions and give these reports to the companies to adjust their plans.
Suppose a person loves traveling and is regularly searching for a holiday destination, the searches made by the user is used to provide him with relative advertisements by online hotel and flight booking apps.
You know what, search engines are not the only implementation of natural language processing (NLP) and there are a lot of awesome implementations out there.
These are some of the successful implementations of Natural Language Processing (NLP):
Search engines like Google, Yahoo, etc. Google search engine understands that you are a tech guy so it shows you results related to you.
Social websites feed like the Facebook news feed. The news feed algorithm understands your interests using natural language processing and shows you related Ads and posts more likely than other posts.
Speech engines like Apple Siri.
Spam filters like Google spam filters. It’s not just about the usual spam filtering, now spam filters understand what’s inside the email content and see if it’s a spam or not.
How do I Start with NLP using Python?
Natural language toolkit (NLTK) is the most popular library for natural language processing (NLP) which was written in Python and has a big community behind it.
NLTK also is very easy to learn, actually, it’s the easiest natural language processing (NLP) library that you’ll use.
In this NLP Tutorial, we will use Python NLTK library.
Before I start installing NLTK, I assume that you know some Python basics to get started.
If you are using Windows or Linux or Mac, you can install NLTK using pip:
You can use NLTK on Python 2.7, 3.4, and 3.5 at the time of writing this post.
Alternatively, you can install it from source from this tar.
To check if NLTK has installed correctly, you can open python terminal and type the following:
If everything goes fine, that means you’ve successfully installed NLTK library.
Once you’ve installed NLTK, you should install the NLTK packages by running the following code:
import nltknltk.download()
This will show the NLTK downloader to choose what packages need to be installed.
You can install all packages since they have small sizes, so no problem. Now let’s start the show.
First, we will grab a webpage and analyze the text to see what the page is about.
urllib module will help us to crawl the webpage
import urllib.requestresponse = urllib.request.urlopen('https://en.wikipedia.org/wiki/SpaceX')html = response.read()print(html)
It’s pretty clear from the link that page is about SpaceX now let us see whether our code is able to correctly identify the page’s context.
We will use Beautiful Soup which is a Python library for pulling data out of HTML and XML files. We will use beautiful soup to clean our webpage text of HTML tags.
from bs4 import BeautifulSoupsoup = BeautifulSoup(html,'html5lib')text = soup.get_text(strip = True)print(text)
Now we have clean text from the crawled web page, let’s convert the text into tokens.
tokens = [t for t in text.split()]print(tokens)
your output text is now converted into tokens
nltk offers a function FreqDist() which will do the job for us. Also, we will remove stop words (a, at, the, for etc) from our web page as we don't need them to hamper our word frequency count. We will plot the graph for most frequently occurring words in the webpage in order to get the clear picture of the context of the web page
from nltk.corpus import stopwordssr= stopwords.words('english')clean_tokens = tokens[:]for token in tokens: if token in stopwords.words('english'): clean_tokens.remove(token)freq = nltk.FreqDist(clean_tokens)for key,val in freq.items(): print(str(key) + ':' + str(val))freq.plot(20, cumulative=False)
Great!!! the code has correctly identified that the web page speaks about SpaceX.
It was so simple and interesting right !!! you can similarly identify the news articles, blogs etc.
I have done my best to make the article simple and interesting for you, hope you found it useful and interesting too.
You have successfully taken your first step towards NLP, there is an ocean to explore for you...
If you liked this post give it a Clap, it inspires me to write and share more with you guys :) | [
{
"code": null,
"e": 229,
"s": 172,
"text": "Gentle Start to Natural Language Processing using Python"
},
{
"code": null,
"e": 243,
"s": 229,
"text": "What is NLP ?"
},
{
"code": null,
"e": 518,
"s": 243,
"text": "Natural language processing (NLP) is about developing applications and services that are able to understand human languages. Some Practical examples of NLP are speech recognition for eg: google voice search, understanding what the content is about or sentiment analysis etc."
},
{
"code": null,
"e": 534,
"s": 518,
"text": "Benefits of NLP"
},
{
"code": null,
"e": 652,
"s": 534,
"text": "As all of you know, there are millions of gigabytes every day are generated by blogs, social websites, and web pages."
},
{
"code": null,
"e": 811,
"s": 652,
"text": "There are many companies gathering all of these data for understanding users and their passions and give these reports to the companies to adjust their plans."
},
{
"code": null,
"e": 1021,
"s": 811,
"text": "Suppose a person loves traveling and is regularly searching for a holiday destination, the searches made by the user is used to provide him with relative advertisements by online hotel and flight booking apps."
},
{
"code": null,
"e": 1178,
"s": 1021,
"text": "You know what, search engines are not the only implementation of natural language processing (NLP) and there are a lot of awesome implementations out there."
},
{
"code": null,
"e": 1265,
"s": 1178,
"text": "These are some of the successful implementations of Natural Language Processing (NLP):"
},
{
"code": null,
"e": 1402,
"s": 1265,
"text": "Search engines like Google, Yahoo, etc. Google search engine understands that you are a tech guy so it shows you results related to you."
},
{
"code": null,
"e": 1603,
"s": 1402,
"text": "Social websites feed like the Facebook news feed. The news feed algorithm understands your interests using natural language processing and shows you related Ads and posts more likely than other posts."
},
{
"code": null,
"e": 1635,
"s": 1603,
"text": "Speech engines like Apple Siri."
},
{
"code": null,
"e": 1811,
"s": 1635,
"text": "Spam filters like Google spam filters. It’s not just about the usual spam filtering, now spam filters understand what’s inside the email content and see if it’s a spam or not."
},
{
"code": null,
"e": 1849,
"s": 1811,
"text": "How do I Start with NLP using Python?"
},
{
"code": null,
"e": 2010,
"s": 1849,
"text": "Natural language toolkit (NLTK) is the most popular library for natural language processing (NLP) which was written in Python and has a big community behind it."
},
{
"code": null,
"e": 2129,
"s": 2010,
"text": "NLTK also is very easy to learn, actually, it’s the easiest natural language processing (NLP) library that you’ll use."
},
{
"code": null,
"e": 2184,
"s": 2129,
"text": "In this NLP Tutorial, we will use Python NLTK library."
},
{
"code": null,
"e": 2274,
"s": 2184,
"text": "Before I start installing NLTK, I assume that you know some Python basics to get started."
},
{
"code": null,
"e": 2348,
"s": 2274,
"text": "If you are using Windows or Linux or Mac, you can install NLTK using pip:"
},
{
"code": null,
"e": 2427,
"s": 2348,
"text": "You can use NLTK on Python 2.7, 3.4, and 3.5 at the time of writing this post."
},
{
"code": null,
"e": 2488,
"s": 2427,
"text": "Alternatively, you can install it from source from this tar."
},
{
"code": null,
"e": 2583,
"s": 2488,
"text": "To check if NLTK has installed correctly, you can open python terminal and type the following:"
},
{
"code": null,
"e": 2663,
"s": 2583,
"text": "If everything goes fine, that means you’ve successfully installed NLTK library."
},
{
"code": null,
"e": 2759,
"s": 2663,
"text": "Once you’ve installed NLTK, you should install the NLTK packages by running the following code:"
},
{
"code": null,
"e": 2786,
"s": 2759,
"text": "import nltknltk.download()"
},
{
"code": null,
"e": 2867,
"s": 2786,
"text": "This will show the NLTK downloader to choose what packages need to be installed."
},
{
"code": null,
"e": 2966,
"s": 2867,
"text": "You can install all packages since they have small sizes, so no problem. Now let’s start the show."
},
{
"code": null,
"e": 3048,
"s": 2966,
"text": "First, we will grab a webpage and analyze the text to see what the page is about."
},
{
"code": null,
"e": 3096,
"s": 3048,
"text": "urllib module will help us to crawl the webpage"
},
{
"code": null,
"e": 3225,
"s": 3096,
"text": "import urllib.requestresponse = urllib.request.urlopen('https://en.wikipedia.org/wiki/SpaceX')html = response.read()print(html)"
},
{
"code": null,
"e": 3365,
"s": 3225,
"text": "It’s pretty clear from the link that page is about SpaceX now let us see whether our code is able to correctly identify the page’s context."
},
{
"code": null,
"e": 3529,
"s": 3365,
"text": "We will use Beautiful Soup which is a Python library for pulling data out of HTML and XML files. We will use beautiful soup to clean our webpage text of HTML tags."
},
{
"code": null,
"e": 3641,
"s": 3529,
"text": "from bs4 import BeautifulSoupsoup = BeautifulSoup(html,'html5lib')text = soup.get_text(strip = True)print(text)"
},
{
"code": null,
"e": 3727,
"s": 3641,
"text": "Now we have clean text from the crawled web page, let’s convert the text into tokens."
},
{
"code": null,
"e": 3775,
"s": 3727,
"text": "tokens = [t for t in text.split()]print(tokens)"
},
{
"code": null,
"e": 3821,
"s": 3775,
"text": "your output text is now converted into tokens"
},
{
"code": null,
"e": 4154,
"s": 3821,
"text": "nltk offers a function FreqDist() which will do the job for us. Also, we will remove stop words (a, at, the, for etc) from our web page as we don't need them to hamper our word frequency count. We will plot the graph for most frequently occurring words in the webpage in order to get the clear picture of the context of the web page"
},
{
"code": null,
"e": 4476,
"s": 4154,
"text": "from nltk.corpus import stopwordssr= stopwords.words('english')clean_tokens = tokens[:]for token in tokens: if token in stopwords.words('english'): clean_tokens.remove(token)freq = nltk.FreqDist(clean_tokens)for key,val in freq.items(): print(str(key) + ':' + str(val))freq.plot(20, cumulative=False)"
},
{
"code": null,
"e": 4558,
"s": 4476,
"text": "Great!!! the code has correctly identified that the web page speaks about SpaceX."
},
{
"code": null,
"e": 4658,
"s": 4558,
"text": "It was so simple and interesting right !!! you can similarly identify the news articles, blogs etc."
},
{
"code": null,
"e": 4776,
"s": 4658,
"text": "I have done my best to make the article simple and interesting for you, hope you found it useful and interesting too."
},
{
"code": null,
"e": 4873,
"s": 4776,
"text": "You have successfully taken your first step towards NLP, there is an ocean to explore for you..."
}
] |
Faster Video Processing in Python using Parallel Computing | by Sabina Pokhrel | Towards Data Science | If you want to process a number of video files, it might take a from minutes to hours, depending on the size of the video, frame count, and frame dimensions.
How can we speed up video processing?
Parallel processing is the answer!
If you are processing images in batches, you can utilize the power of parallel processing and speed-up the task.
In this post, we will look at how to use python for prallel processing of videos.
We will read video from the disk, perform face detection, and write the video with output of face detection (bounding boxes) back to the disk.
Lets get started.
We will need the following packages:
OpenCV: is a computer vision library that is commonly used. In this post, we will use OpenCV to read and write video files.
To install OpenCV on your device, you can use either pip command or apt-get command.
pip3 install opencv-python
or
sudo apt-get install -y python3-opencv
FFmpeg: is a cross-platform solution to record, convert and stream audio and video. In this post, we will use FFmpeg to join multiple video files.
To install ffmpeg, use the following apt-get command:
sudo apt-get install -y ffmpeg
Let’s import the required python libraries.
Details on libraries used:
cv2: OpenCV library to read from and write to video files.
time: to get current time for calculating code execution time.
subprocess: to start new processes, connect to their input/output/error pipes, and obtain their return codes.
multiprocessing: to parallelize the execution of a function across multiple input values, distributing the input data across processes
xailient: library for face detection
We will first define a method to process video using single process. This is the way how we would normally read a video file, process each frame and write the output frames back to the disk.
Let’s create another function that calls the video processor, takes note of start and end time, and calculates the time taken to execute the pipeline and the frames processed per second.
Now, lets define another function for processing video that utilizes mutiprocessing.
The was the above function works is that, the video processing job, that is normally done using one process, is now divided equally amongst the total number of processors available on the executing device.
If there are 4 processes, and total number of frames in the video to be processed is 1000, then each process gets 250 frames to process, which are executed in parallel. This means that each process will create a separate output file, and so when the video processing is completed, there are 4 different output videos.
To combine these output videos, we will use ffmpeg.
Create a pipeline to run the multiprocessing of video and calculate time to execute and frames processed per second.
I ran this experiment on Lenovo Yoga 920 with Ubuntu18.04 operating system. The number of logical processors available on this device are 8.
From this experiment, we can observe 2x more frames being processed per second when using all cores to process the video.
Found this post helpful? Leave your thoughts as comments below.
Originally published in www.xailient.com/blog.
About the author
Sabina Pokhrel works at Xailient, a computer-vision start-up that has built the world’s fastest Edge-optimized object detector. | [
{
"code": null,
"e": 329,
"s": 171,
"text": "If you want to process a number of video files, it might take a from minutes to hours, depending on the size of the video, frame count, and frame dimensions."
},
{
"code": null,
"e": 367,
"s": 329,
"text": "How can we speed up video processing?"
},
{
"code": null,
"e": 402,
"s": 367,
"text": "Parallel processing is the answer!"
},
{
"code": null,
"e": 515,
"s": 402,
"text": "If you are processing images in batches, you can utilize the power of parallel processing and speed-up the task."
},
{
"code": null,
"e": 597,
"s": 515,
"text": "In this post, we will look at how to use python for prallel processing of videos."
},
{
"code": null,
"e": 740,
"s": 597,
"text": "We will read video from the disk, perform face detection, and write the video with output of face detection (bounding boxes) back to the disk."
},
{
"code": null,
"e": 758,
"s": 740,
"text": "Lets get started."
},
{
"code": null,
"e": 795,
"s": 758,
"text": "We will need the following packages:"
},
{
"code": null,
"e": 919,
"s": 795,
"text": "OpenCV: is a computer vision library that is commonly used. In this post, we will use OpenCV to read and write video files."
},
{
"code": null,
"e": 1004,
"s": 919,
"text": "To install OpenCV on your device, you can use either pip command or apt-get command."
},
{
"code": null,
"e": 1031,
"s": 1004,
"text": "pip3 install opencv-python"
},
{
"code": null,
"e": 1034,
"s": 1031,
"text": "or"
},
{
"code": null,
"e": 1073,
"s": 1034,
"text": "sudo apt-get install -y python3-opencv"
},
{
"code": null,
"e": 1220,
"s": 1073,
"text": "FFmpeg: is a cross-platform solution to record, convert and stream audio and video. In this post, we will use FFmpeg to join multiple video files."
},
{
"code": null,
"e": 1274,
"s": 1220,
"text": "To install ffmpeg, use the following apt-get command:"
},
{
"code": null,
"e": 1305,
"s": 1274,
"text": "sudo apt-get install -y ffmpeg"
},
{
"code": null,
"e": 1349,
"s": 1305,
"text": "Let’s import the required python libraries."
},
{
"code": null,
"e": 1376,
"s": 1349,
"text": "Details on libraries used:"
},
{
"code": null,
"e": 1435,
"s": 1376,
"text": "cv2: OpenCV library to read from and write to video files."
},
{
"code": null,
"e": 1498,
"s": 1435,
"text": "time: to get current time for calculating code execution time."
},
{
"code": null,
"e": 1608,
"s": 1498,
"text": "subprocess: to start new processes, connect to their input/output/error pipes, and obtain their return codes."
},
{
"code": null,
"e": 1743,
"s": 1608,
"text": "multiprocessing: to parallelize the execution of a function across multiple input values, distributing the input data across processes"
},
{
"code": null,
"e": 1780,
"s": 1743,
"text": "xailient: library for face detection"
},
{
"code": null,
"e": 1971,
"s": 1780,
"text": "We will first define a method to process video using single process. This is the way how we would normally read a video file, process each frame and write the output frames back to the disk."
},
{
"code": null,
"e": 2158,
"s": 1971,
"text": "Let’s create another function that calls the video processor, takes note of start and end time, and calculates the time taken to execute the pipeline and the frames processed per second."
},
{
"code": null,
"e": 2243,
"s": 2158,
"text": "Now, lets define another function for processing video that utilizes mutiprocessing."
},
{
"code": null,
"e": 2449,
"s": 2243,
"text": "The was the above function works is that, the video processing job, that is normally done using one process, is now divided equally amongst the total number of processors available on the executing device."
},
{
"code": null,
"e": 2767,
"s": 2449,
"text": "If there are 4 processes, and total number of frames in the video to be processed is 1000, then each process gets 250 frames to process, which are executed in parallel. This means that each process will create a separate output file, and so when the video processing is completed, there are 4 different output videos."
},
{
"code": null,
"e": 2819,
"s": 2767,
"text": "To combine these output videos, we will use ffmpeg."
},
{
"code": null,
"e": 2936,
"s": 2819,
"text": "Create a pipeline to run the multiprocessing of video and calculate time to execute and frames processed per second."
},
{
"code": null,
"e": 3077,
"s": 2936,
"text": "I ran this experiment on Lenovo Yoga 920 with Ubuntu18.04 operating system. The number of logical processors available on this device are 8."
},
{
"code": null,
"e": 3199,
"s": 3077,
"text": "From this experiment, we can observe 2x more frames being processed per second when using all cores to process the video."
},
{
"code": null,
"e": 3263,
"s": 3199,
"text": "Found this post helpful? Leave your thoughts as comments below."
},
{
"code": null,
"e": 3310,
"s": 3263,
"text": "Originally published in www.xailient.com/blog."
},
{
"code": null,
"e": 3327,
"s": 3310,
"text": "About the author"
}
] |
Drop MySQL Database | You would need special privileges to create or to delete a MySQL database. So, assuming you have access to the root user, you can create any database using the mysql mysqladmin binary.
Be careful while deleting any database because you will lose your all the data available in your database.
Here is an example to delete a database(TUTORIALS) created in the previous chapter −
[root@host]# mysqladmin -u root -p drop TUTORIALS
Enter password:******
This will give you a warning and it will confirm if you really want to delete this database or not.
Dropping the database is potentially a very bad thing to do.
Any data stored in the database will be destroyed.
Do you really want to drop the 'TUTORIALS' database [y/N] y
Database "TUTORIALS" dropped
PHP uses mysqli query() or mysql_query() function to drop a MySQL database. This function takes two parameters and returns TRUE on success or FALSE on failure.
$mysqli->query($sql,$resultmode)
$sql
Required - SQL query to drop a MySQL database.
$resultmode
Optional - Either the constant MYSQLI_USE_RESULT or MYSQLI_STORE_RESULT depending on the desired behavior. By default, MYSQLI_STORE_RESULT is used.
Try the following example to drop a database −
Copy and paste the following example as mysql_example.php −
<html>
<head><title>Dropping MySQL Database</title></head>
<body>
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'root@123';
$mysqli = new mysqli($dbhost, $dbuser, $dbpass);
if($mysqli->connect_errno ) {
printf("Connect failed: %s<br />", $mysqli->connect_error);
exit();
}
printf('Connected successfully.<br />');
if ($mysqli->query("Drop DATABASE TUTORIALS")) {
printf("Database TUTORIALS dropped successfully.<br />");
}
if ($mysqli->errno) {
printf("Could not drop database: %s<br />", $mysqli->error);
}
$mysqli->close();
?>
</body>
</html>
Access the mysql_example.php deployed on apache web server and verify the output.
Connected successfully.
Database TUTORIALS dropped successfully.
31 Lectures
6 hours
Eduonix Learning Solutions
84 Lectures
5.5 hours
Frahaan Hussain
6 Lectures
3.5 hours
DATAhill Solutions Srinivas Reddy
60 Lectures
10 hours
Vijay Kumar Parvatha Reddy
10 Lectures
1 hours
Harshit Srivastava
25 Lectures
4 hours
Trevoir Williams
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2518,
"s": 2333,
"text": "You would need special privileges to create or to delete a MySQL database. So, assuming you have access to the root user, you can create any database using the mysql mysqladmin binary."
},
{
"code": null,
"e": 2625,
"s": 2518,
"text": "Be careful while deleting any database because you will lose your all the data available in your database."
},
{
"code": null,
"e": 2710,
"s": 2625,
"text": "Here is an example to delete a database(TUTORIALS) created in the previous chapter −"
},
{
"code": null,
"e": 2783,
"s": 2710,
"text": "[root@host]# mysqladmin -u root -p drop TUTORIALS\nEnter password:******\n"
},
{
"code": null,
"e": 2883,
"s": 2783,
"text": "This will give you a warning and it will confirm if you really want to delete this database or not."
},
{
"code": null,
"e": 3086,
"s": 2883,
"text": "Dropping the database is potentially a very bad thing to do.\nAny data stored in the database will be destroyed.\n\nDo you really want to drop the 'TUTORIALS' database [y/N] y\nDatabase \"TUTORIALS\" dropped\n"
},
{
"code": null,
"e": 3246,
"s": 3086,
"text": "PHP uses mysqli query() or mysql_query() function to drop a MySQL database. This function takes two parameters and returns TRUE on success or FALSE on failure."
},
{
"code": null,
"e": 3280,
"s": 3246,
"text": "$mysqli->query($sql,$resultmode)\n"
},
{
"code": null,
"e": 3285,
"s": 3280,
"text": "$sql"
},
{
"code": null,
"e": 3332,
"s": 3285,
"text": "Required - SQL query to drop a MySQL database."
},
{
"code": null,
"e": 3344,
"s": 3332,
"text": "$resultmode"
},
{
"code": null,
"e": 3492,
"s": 3344,
"text": "Optional - Either the constant MYSQLI_USE_RESULT or MYSQLI_STORE_RESULT depending on the desired behavior. By default, MYSQLI_STORE_RESULT is used."
},
{
"code": null,
"e": 3539,
"s": 3492,
"text": "Try the following example to drop a database −"
},
{
"code": null,
"e": 3599,
"s": 3539,
"text": "Copy and paste the following example as mysql_example.php −"
},
{
"code": null,
"e": 4343,
"s": 3599,
"text": "<html>\n <head><title>Dropping MySQL Database</title></head>\n <body>\n <?php\n $dbhost = 'localhost';\n $dbuser = 'root';\n $dbpass = 'root@123';\n $mysqli = new mysqli($dbhost, $dbuser, $dbpass);\n \n if($mysqli->connect_errno ) {\n printf(\"Connect failed: %s<br />\", $mysqli->connect_error);\n exit();\n }\n printf('Connected successfully.<br />');\n\n if ($mysqli->query(\"Drop DATABASE TUTORIALS\")) {\n printf(\"Database TUTORIALS dropped successfully.<br />\");\n }\n if ($mysqli->errno) {\n printf(\"Could not drop database: %s<br />\", $mysqli->error);\n }\n $mysqli->close();\n ?>\n </body>\n</html>"
},
{
"code": null,
"e": 4425,
"s": 4343,
"text": "Access the mysql_example.php deployed on apache web server and verify the output."
},
{
"code": null,
"e": 4491,
"s": 4425,
"text": "Connected successfully.\nDatabase TUTORIALS dropped successfully.\n"
},
{
"code": null,
"e": 4524,
"s": 4491,
"text": "\n 31 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 4552,
"s": 4524,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 4587,
"s": 4552,
"text": "\n 84 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 4604,
"s": 4587,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 4638,
"s": 4604,
"text": "\n 6 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 4673,
"s": 4638,
"text": " DATAhill Solutions Srinivas Reddy"
},
{
"code": null,
"e": 4707,
"s": 4673,
"text": "\n 60 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 4735,
"s": 4707,
"text": " Vijay Kumar Parvatha Reddy"
},
{
"code": null,
"e": 4768,
"s": 4735,
"text": "\n 10 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 4788,
"s": 4768,
"text": " Harshit Srivastava"
},
{
"code": null,
"e": 4821,
"s": 4788,
"text": "\n 25 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 4839,
"s": 4821,
"text": " Trevoir Williams"
},
{
"code": null,
"e": 4846,
"s": 4839,
"text": " Print"
},
{
"code": null,
"e": 4857,
"s": 4846,
"text": " Add Notes"
}
] |
C Program for replacing one digit with other | Given a number n, we have to replace a digit x from that number with another given number m. we have to look for the number whether the number is present in the given number or not, if it is present in the given number then replace that particular number x with another number m.
Like we are given with a number “123” and m as 5 and the number to be replaced i.e. x as “2”, so the result should be “153”.
Input: n = 983, digit = 9, replace = 6
Output: 683
Explanation: digit 9 is the first digit in 983 and we have to replace the digit 9 with 6 so the result will be 683.
Input: n = 123, digit = 5, replace = 4
Output: 123
Explanation: There is not digit 5 in the given number n so the result will be same as the number n.
The approach used below is as follows −
We will look up for the number by starting from the unit place
When we found the digit which we want to replace then add result to the (replace * d) where d should be equal to 1.
If we don’t found the number just simply keep the number as it is.
In function int digitreplace(int n, int digit, int replace)
Step 1-> Declare and initialize res=0 and d=1, rem
Step 2-> Loop While(n)
Set rem as n%10
If rem == digit then,
Set res as res + replace * d
Else
Set res as res + rem * d
d *= 10;
n /= 10;
End Loop
Step 3-> Print res
End function
In function int main(int argc, char const *argv[])
Step 1-> Declare and initialize n = 983, digit = 9, replace = 7
Step 2-> Call Function digitreplace(n, digit, replace);
Stop
Live Demo
#include <stdio.h>
int digitreplace(int n, int digit, int replace) {
int res=0, d=1;
int rem;
while(n) {
//finding the remainder from the back
rem = n%10;
//Checking whether the remainder equal to the
//digit we want to replace. If yes then replace.
if(rem == digit)
res = res + replace * d;
//Else dont replace just store the same in res.
else
res = res + rem * d;
d *= 10;
n /= 10;
}
printf("%d\n", res);
return 0;
}
//main function
int main(int argc, char const *argv[]) {
int n = 983;
int digit = 9;
int replace = 7;
digitreplace(n, digit, replace);
return 0;
}
If run the above code it will generate the following output −
783 | [
{
"code": null,
"e": 1342,
"s": 1062,
"text": "Given a number n, we have to replace a digit x from that number with another given number m. we have to look for the number whether the number is present in the given number or not, if it is present in the given number then replace that particular number x with another number m."
},
{
"code": null,
"e": 1467,
"s": 1342,
"text": "Like we are given with a number “123” and m as 5 and the number to be replaced i.e. x as “2”, so the result should be “153”."
},
{
"code": null,
"e": 1785,
"s": 1467,
"text": "Input: n = 983, digit = 9, replace = 6\nOutput: 683\nExplanation: digit 9 is the first digit in 983 and we have to replace the digit 9 with 6 so the result will be 683.\nInput: n = 123, digit = 5, replace = 4\nOutput: 123\nExplanation: There is not digit 5 in the given number n so the result will be same as the number n."
},
{
"code": null,
"e": 1825,
"s": 1785,
"text": "The approach used below is as follows −"
},
{
"code": null,
"e": 1888,
"s": 1825,
"text": "We will look up for the number by starting from the unit place"
},
{
"code": null,
"e": 2004,
"s": 1888,
"text": "When we found the digit which we want to replace then add result to the (replace * d) where d should be equal to 1."
},
{
"code": null,
"e": 2071,
"s": 2004,
"text": "If we don’t found the number just simply keep the number as it is."
},
{
"code": null,
"e": 2618,
"s": 2071,
"text": "In function int digitreplace(int n, int digit, int replace)\n Step 1-> Declare and initialize res=0 and d=1, rem\n Step 2-> Loop While(n)\n Set rem as n%10\n If rem == digit then,\n Set res as res + replace * d\n Else\n Set res as res + rem * d\n d *= 10;\n n /= 10;\n End Loop\n Step 3-> Print res\n End function\nIn function int main(int argc, char const *argv[])\n Step 1-> Declare and initialize n = 983, digit = 9, replace = 7\n Step 2-> Call Function digitreplace(n, digit, replace);\nStop"
},
{
"code": null,
"e": 2629,
"s": 2618,
"text": " Live Demo"
},
{
"code": null,
"e": 3309,
"s": 2629,
"text": "#include <stdio.h>\nint digitreplace(int n, int digit, int replace) {\n int res=0, d=1;\n int rem;\n while(n) {\n //finding the remainder from the back\n rem = n%10;\n //Checking whether the remainder equal to the\n //digit we want to replace. If yes then replace.\n if(rem == digit)\n res = res + replace * d;\n //Else dont replace just store the same in res.\n else\n res = res + rem * d;\n d *= 10;\n n /= 10;\n }\n printf(\"%d\\n\", res);\n return 0;\n}\n//main function\nint main(int argc, char const *argv[]) {\n int n = 983;\n int digit = 9;\n int replace = 7;\n digitreplace(n, digit, replace);\n return 0;\n}"
},
{
"code": null,
"e": 3371,
"s": 3309,
"text": "If run the above code it will generate the following output −"
},
{
"code": null,
"e": 3375,
"s": 3371,
"text": "783"
}
] |
Top K Frequent Elements in Python | Suppose we have a non-empty array of integer numbers. we have to return the kth most frequent elements. So if the elements are [1,1,1,1,2,2,3,3,3] and k = 2, then the result will be
Formally the function should −
Return true if there exists i, j, k
such that arr[i] < arr[j] < arr[k] given 0 ≤ i < j < k ≤ n-1 else return false.
To solve this, we will follow these steps −
num_freq = an empty map, freq_list := an empty map
for each element i in numsif i is not in num_freq, then num_freq[i] := 1, otherwise increase num_freq[i] by 1
if i is not in num_freq, then num_freq[i] := 1, otherwise increase num_freq[i] by 1
for each key-value pair in num_freq mapif value is not present in freq_list, then freq_list[value] := a list with [key], otherwise insert key into freq_list[value] array
if value is not present in freq_list, then freq_list[value] := a list with [key], otherwise insert key into freq_list[value] array
res := empty list
for i := length of numbers down to 0if i in freq_list, then add elements of freq_list[i] into resif length of res >= k, then break
if i in freq_list, then add elements of freq_list[i] into res
if length of res >= k, then break
return result
Let us see the following implementation to get better understanding −
Live Demo
class Solution(object):
def topKFrequent(self, nums, k):
number_frequency = {}
frequency_list ={}
for i in nums:
if i not in number_frequency:
number_frequency[i] = 1
else:
number_frequency[i] += 1
for key,value in number_frequency.items():
if value not in frequency_list:
frequency_list[value] = [key]
else:
frequency_list[value].append(key)
result = []
for i in range(len(nums),0,-1):
if i in frequency_list:
result.extend(frequency_list[i])
if len(result) >=k:
break
return result
ob1 = Solution()
print(ob1.topKFrequent([1,1,1,1,2,2,3,3,3], 2))
[1,1,1,1,2,2,3,3,3]
2
[1, 3] | [
{
"code": null,
"e": 1244,
"s": 1062,
"text": "Suppose we have a non-empty array of integer numbers. we have to return the kth most frequent elements. So if the elements are [1,1,1,1,2,2,3,3,3] and k = 2, then the result will be"
},
{
"code": null,
"e": 1275,
"s": 1244,
"text": "Formally the function should −"
},
{
"code": null,
"e": 1311,
"s": 1275,
"text": "Return true if there exists i, j, k"
},
{
"code": null,
"e": 1391,
"s": 1311,
"text": "such that arr[i] < arr[j] < arr[k] given 0 ≤ i < j < k ≤ n-1 else return false."
},
{
"code": null,
"e": 1435,
"s": 1391,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1486,
"s": 1435,
"text": "num_freq = an empty map, freq_list := an empty map"
},
{
"code": null,
"e": 1596,
"s": 1486,
"text": "for each element i in numsif i is not in num_freq, then num_freq[i] := 1, otherwise increase num_freq[i] by 1"
},
{
"code": null,
"e": 1680,
"s": 1596,
"text": "if i is not in num_freq, then num_freq[i] := 1, otherwise increase num_freq[i] by 1"
},
{
"code": null,
"e": 1850,
"s": 1680,
"text": "for each key-value pair in num_freq mapif value is not present in freq_list, then freq_list[value] := a list with [key], otherwise insert key into freq_list[value] array"
},
{
"code": null,
"e": 1981,
"s": 1850,
"text": "if value is not present in freq_list, then freq_list[value] := a list with [key], otherwise insert key into freq_list[value] array"
},
{
"code": null,
"e": 1999,
"s": 1981,
"text": "res := empty list"
},
{
"code": null,
"e": 2130,
"s": 1999,
"text": "for i := length of numbers down to 0if i in freq_list, then add elements of freq_list[i] into resif length of res >= k, then break"
},
{
"code": null,
"e": 2192,
"s": 2130,
"text": "if i in freq_list, then add elements of freq_list[i] into res"
},
{
"code": null,
"e": 2226,
"s": 2192,
"text": "if length of res >= k, then break"
},
{
"code": null,
"e": 2240,
"s": 2226,
"text": "return result"
},
{
"code": null,
"e": 2310,
"s": 2240,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 2321,
"s": 2310,
"text": " Live Demo"
},
{
"code": null,
"e": 3041,
"s": 2321,
"text": "class Solution(object):\n def topKFrequent(self, nums, k):\n number_frequency = {}\n frequency_list ={}\n for i in nums:\n if i not in number_frequency:\n number_frequency[i] = 1\n else:\n number_frequency[i] += 1\n for key,value in number_frequency.items():\n if value not in frequency_list:\n frequency_list[value] = [key]\n else:\n frequency_list[value].append(key)\n result = []\n for i in range(len(nums),0,-1):\n if i in frequency_list:\n result.extend(frequency_list[i])\n if len(result) >=k:\n break\n return result\nob1 = Solution()\nprint(ob1.topKFrequent([1,1,1,1,2,2,3,3,3], 2))"
},
{
"code": null,
"e": 3063,
"s": 3041,
"text": "[1,1,1,1,2,2,3,3,3]\n2"
},
{
"code": null,
"e": 3070,
"s": 3063,
"text": "[1, 3]"
}
] |
Android - Alert Dialog | A Dialog is small window that prompts the user to a decision or enter additional information.
Some times in your application, if you wanted to ask the user about taking a decision between yes or no in response of any particular action taken by the user, by remaining in the same activity and without changing the screen, you can use Alert Dialog.
In order to make an alert dialog, you need to make an object of AlertDialogBuilder which an inner class of AlertDialog. Its syntax is given below
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
Now you have to set the positive (yes) or negative (no) button using the object of the AlertDialogBuilder class. Its syntax is
alertDialogBuilder.setPositiveButton(CharSequence text,
DialogInterface.OnClickListener listener)
alertDialogBuilder.setNegativeButton(CharSequence text,
DialogInterface.OnClickListener listener)
Apart from this , you can use other functions provided by the builder class to customize the alert dialog. These are listed below
setIcon(Drawable icon)
This method set the icon of the alert dialog box.
setCancelable(boolean cancel able)
This method sets the property that the dialog can be cancelled or not
setMessage(CharSequence message)
This method sets the message to be displayed in the alert dialog
setMultiChoiceItems(CharSequence[] items, boolean[] checkedItems, DialogInterface.OnMultiChoiceClickListener listener)
This method sets list of items to be displayed in the dialog as the content. The selected option will be notified by the listener
setOnCancelListener(DialogInterface.OnCancelListener onCancelListener)
This method Sets the callback that will be called if the dialog is cancelled.
setTitle(CharSequence title)
This method set the title to be appear in the dialog
After creating and setting the dialog builder , you will create an alert dialog by calling the create() method of the builder class. Its syntax is
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
This will create the alert dialog and will show it on the screen.
Before enter into an example we should need to know dialog fragment.Dialog fragment is a fragment which can show fragment in dialog box
public class DialogFragment extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setPositiveButton(R.string.fire, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
toast.makeText(this,"enter a text here",Toast.LENTH_SHORT).show();
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
});
// Create the AlertDialog object and return it
return builder.create();
}
}
}
It has used to show list of items in a dialog box.For suppose, user need to select a list of items or else need to click a item from multiple list of items.At this situation we can use list dialog.
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(Pick a Color)
.setItems(R.array.colors_array, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// The 'which' argument contains the index position
// of the selected item
}
});
return builder.create();
}
It has used to add single choice list to Dialog box.We can check or uncheck as per user choice.
public Dialog onCreateDialog(Bundle savedInstanceState) {
mSelectedItems = new ArrayList();
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("This is list choice dialog box");
.setMultiChoiceItems(R.array.toppings, null,
new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
if (isChecked) {
// If the user checked the item, add it to the selected items
mSelectedItems.add(which);
}
else if (mSelectedItems.contains(which)) {
// Else, if the item is already in the array, remove it
mSelectedItems.remove(Integer.valueOf(which));
}
}
})
// Set the action buttons
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
// User clicked OK, so save the mSelectedItems results somewhere
// or return them to the component that opened the dialog
...
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
...
}
});
return builder.create();
}
The following example demonstrates the use of AlertDialog in android.
To experiment with this example , you need to run this on an emulator or an actual device.
Here is the modified code of src/MainActivity.java
package com.example.sairamkrishna.myapplication;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void open(View view){
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setMessage("Are you sure,
You wanted to make decision");
alertDialogBuilder.setPositiveButton("yes",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
Toast.makeText(MainActivity.this,"You clicked yes
button",Toast.LENGTH_LONG).show();
}
});
alertDialogBuilder.setNegativeButton("No",new DialogInterface.OnClickListener() {
Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
}
Here is the modified code of res/layout/activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Alert Dialog"
android:id="@+id/textView"
android:textSize="35dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorialspoint"
android:id="@+id/textView2"
android:textColor="#ff3eff0f"
android:textSize="35dp"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:src="@drawable/abc"
android:layout_below="@+id/textView2"
android:layout_alignRight="@+id/textView2"
android:layout_alignEnd="@+id/textView2"
android:layout_alignLeft="@+id/textView"
android:layout_alignStart="@+id/textView" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Alert dialog"
android:id="@+id/button"
android:layout_below="@+id/imageView"
android:layout_alignRight="@+id/textView2"
android:layout_alignEnd="@+id/textView2"
android:layout_marginTop="42dp"
android:onClick="open"
android:layout_alignLeft="@+id/imageView"
android:layout_alignStart="@+id/imageView" />
</RelativeLayout>
Here is ofStrings.xml
<resources>
<string name="app_name">My Application</string>
</resources>
Here is the default code of AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sairamkrishna.myapplication" >
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.sairamkrishna.myapplication.MainActivity"
android:label="@string/app_name" >
<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. Before starting your application, ]Android studio will display following window to select an option where you want to run your Android application.
Select your an option and then click on it. For suppose, if you have clicked on yes button, then result would as follows
if you click on no button it will call finish() and it will close your application.
46 Lectures
7.5 hours
Aditya Dua
32 Lectures
3.5 hours
Sharad Kumar
9 Lectures
1 hours
Abhilash Nelson
14 Lectures
1.5 hours
Abhilash Nelson
15 Lectures
1.5 hours
Abhilash Nelson
10 Lectures
1 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 3701,
"s": 3607,
"text": "A Dialog is small window that prompts the user to a decision or enter additional information."
},
{
"code": null,
"e": 3954,
"s": 3701,
"text": "Some times in your application, if you wanted to ask the user about taking a decision between yes or no in response of any particular action taken by the user, by remaining in the same activity and without changing the screen, you can use Alert Dialog."
},
{
"code": null,
"e": 4100,
"s": 3954,
"text": "In order to make an alert dialog, you need to make an object of AlertDialogBuilder which an inner class of AlertDialog. Its syntax is given below"
},
{
"code": null,
"e": 4172,
"s": 4100,
"text": "AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);"
},
{
"code": null,
"e": 4299,
"s": 4172,
"text": "Now you have to set the positive (yes) or negative (no) button using the object of the AlertDialogBuilder class. Its syntax is"
},
{
"code": null,
"e": 4503,
"s": 4299,
"text": "alertDialogBuilder.setPositiveButton(CharSequence text, \n DialogInterface.OnClickListener listener)\nalertDialogBuilder.setNegativeButton(CharSequence text, \n DialogInterface.OnClickListener listener)"
},
{
"code": null,
"e": 4633,
"s": 4503,
"text": "Apart from this , you can use other functions provided by the builder class to customize the alert dialog. These are listed below"
},
{
"code": null,
"e": 4656,
"s": 4633,
"text": "setIcon(Drawable icon)"
},
{
"code": null,
"e": 4706,
"s": 4656,
"text": "This method set the icon of the alert dialog box."
},
{
"code": null,
"e": 4741,
"s": 4706,
"text": "setCancelable(boolean cancel able)"
},
{
"code": null,
"e": 4811,
"s": 4741,
"text": "This method sets the property that the dialog can be cancelled or not"
},
{
"code": null,
"e": 4844,
"s": 4811,
"text": "setMessage(CharSequence message)"
},
{
"code": null,
"e": 4909,
"s": 4844,
"text": "This method sets the message to be displayed in the alert dialog"
},
{
"code": null,
"e": 5028,
"s": 4909,
"text": "setMultiChoiceItems(CharSequence[] items, boolean[] checkedItems, DialogInterface.OnMultiChoiceClickListener listener)"
},
{
"code": null,
"e": 5158,
"s": 5028,
"text": "This method sets list of items to be displayed in the dialog as the content. The selected option will be notified by the listener"
},
{
"code": null,
"e": 5229,
"s": 5158,
"text": "setOnCancelListener(DialogInterface.OnCancelListener onCancelListener)"
},
{
"code": null,
"e": 5307,
"s": 5229,
"text": "This method Sets the callback that will be called if the dialog is cancelled."
},
{
"code": null,
"e": 5336,
"s": 5307,
"text": "setTitle(CharSequence title)"
},
{
"code": null,
"e": 5389,
"s": 5336,
"text": "This method set the title to be appear in the dialog"
},
{
"code": null,
"e": 5536,
"s": 5389,
"text": "After creating and setting the dialog builder , you will create an alert dialog by calling the create() method of the builder class. Its syntax is"
},
{
"code": null,
"e": 5611,
"s": 5536,
"text": "AlertDialog alertDialog = alertDialogBuilder.create();\nalertDialog.show();"
},
{
"code": null,
"e": 5677,
"s": 5611,
"text": "This will create the alert dialog and will show it on the screen."
},
{
"code": null,
"e": 5813,
"s": 5677,
"text": "Before enter into an example we should need to know dialog fragment.Dialog fragment is a fragment which can show fragment in dialog box"
},
{
"code": null,
"e": 6616,
"s": 5813,
"text": "public class DialogFragment extends DialogFragment {\n @Override\n public Dialog onCreateDialog(Bundle savedInstanceState) {\n // Use the Builder class for convenient dialog construction\n AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());\n builder.setPositiveButton(R.string.fire, new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int id) {\n toast.makeText(this,\"enter a text here\",Toast.LENTH_SHORT).show();\n }\n })\n .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int id) {\n finish();\n });\n // Create the AlertDialog object and return it\n return builder.create();\n }\n }\n}"
},
{
"code": null,
"e": 6815,
"s": 6616,
"text": "It has used to show list of items in a dialog box.For suppose, user need to select a list of items or else need to click a item from multiple list of items.At this situation we can use list dialog."
},
{
"code": null,
"e": 7261,
"s": 6815,
"text": "public Dialog onCreateDialog(Bundle savedInstanceState) {\n AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());\n builder.setTitle(Pick a Color)\n \n .setItems(R.array.colors_array, new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int which) {\n // The 'which' argument contains the index position\n // of the selected item\n }\n });\n return builder.create();\n}"
},
{
"code": null,
"e": 7357,
"s": 7261,
"text": "It has used to add single choice list to Dialog box.We can check or uncheck as per user choice."
},
{
"code": null,
"e": 8731,
"s": 7357,
"text": "public Dialog onCreateDialog(Bundle savedInstanceState) {\n mSelectedItems = new ArrayList();\n AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());\n \n builder.setTitle(\"This is list choice dialog box\");\n .setMultiChoiceItems(R.array.toppings, null,\n new DialogInterface.OnMultiChoiceClickListener() {\n @Override\n public void onClick(DialogInterface dialog, int which, boolean isChecked) {\n \n if (isChecked) {\n // If the user checked the item, add it to the selected items\n mSelectedItems.add(which);\n }\n \n else if (mSelectedItems.contains(which)) {\n // Else, if the item is already in the array, remove it \n mSelectedItems.remove(Integer.valueOf(which));\n }\n }\n })\n \n // Set the action buttons\n .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {\n @Override\n public void onClick(DialogInterface dialog, int id) {\n // User clicked OK, so save the mSelectedItems results somewhere\n // or return them to the component that opened the dialog\n ...\n }\n })\n \n .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {\n @Override\n public void onClick(DialogInterface dialog, int id) {\n ...\n }\n });\n return builder.create();\n}"
},
{
"code": null,
"e": 8801,
"s": 8731,
"text": "The following example demonstrates the use of AlertDialog in android."
},
{
"code": null,
"e": 8892,
"s": 8801,
"text": "To experiment with this example , you need to run this on an emulator or an actual device."
},
{
"code": null,
"e": 8943,
"s": 8892,
"text": "Here is the modified code of src/MainActivity.java"
},
{
"code": null,
"e": 10241,
"s": 8943,
"text": "package com.example.sairamkrishna.myapplication;\n\nimport android.app.AlertDialog;\nimport android.content.DialogInterface;\nimport android.support.v7.app.ActionBarActivity;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.Toast;\n\npublic class MainActivity extends ActionBarActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n }\n\n public void open(View view){\n AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);\n alertDialogBuilder.setMessage(\"Are you sure,\n You wanted to make decision\");\n alertDialogBuilder.setPositiveButton(\"yes\", \n new DialogInterface.OnClickListener() {\n @Override\n public void onClick(DialogInterface arg0, int arg1) {\n Toast.makeText(MainActivity.this,\"You clicked yes \n button\",Toast.LENGTH_LONG).show();\n }\n });\n\n alertDialogBuilder.setNegativeButton(\"No\",new DialogInterface.OnClickListener() {\n Override\n public void onClick(DialogInterface dialog, int which) {\n finish();\n }\n });\n\n AlertDialog alertDialog = alertDialogBuilder.create();\n alertDialog.show();\n }\n}"
},
{
"code": null,
"e": 10299,
"s": 10241,
"text": "Here is the modified code of res/layout/activity_main.xml"
},
{
"code": null,
"e": 12340,
"s": 10299,
"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\" android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\" \n android:paddingLeft=\"@dimen/activity_horizontal_margin\"\n android:paddingRight=\"@dimen/activity_horizontal_margin\"\n android:paddingTop=\"@dimen/activity_vertical_margin\"\n android:paddingBottom=\"@dimen/activity_vertical_margin\" \n tools:context=\".MainActivity\">\n \n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Alert Dialog\"\n android:id=\"@+id/textView\"\n android:textSize=\"35dp\"\n android:layout_alignParentTop=\"true\"\n android:layout_centerHorizontal=\"true\" />\n \n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Tutorialspoint\"\n android:id=\"@+id/textView2\"\n android:textColor=\"#ff3eff0f\"\n android:textSize=\"35dp\"\n android:layout_below=\"@+id/textView\"\n android:layout_centerHorizontal=\"true\" />\n \n <ImageView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:id=\"@+id/imageView\"\n android:src=\"@drawable/abc\"\n android:layout_below=\"@+id/textView2\"\n android:layout_alignRight=\"@+id/textView2\"\n android:layout_alignEnd=\"@+id/textView2\"\n android:layout_alignLeft=\"@+id/textView\"\n android:layout_alignStart=\"@+id/textView\" />\n <Button\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Alert dialog\"\n android:id=\"@+id/button\"\n android:layout_below=\"@+id/imageView\"\n android:layout_alignRight=\"@+id/textView2\"\n android:layout_alignEnd=\"@+id/textView2\"\n android:layout_marginTop=\"42dp\"\n android:onClick=\"open\"\n android:layout_alignLeft=\"@+id/imageView\"\n android:layout_alignStart=\"@+id/imageView\" />\n \n</RelativeLayout>"
},
{
"code": null,
"e": 12363,
"s": 12340,
"text": "Here is ofStrings.xml"
},
{
"code": null,
"e": 12440,
"s": 12363,
"text": "<resources>\n <string name=\"app_name\">My Application</string>\n</resources>"
},
{
"code": null,
"e": 12488,
"s": 12440,
"text": "Here is the default code of AndroidManifest.xml"
},
{
"code": null,
"e": 13231,
"s": 12488,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"com.example.sairamkrishna.myapplication\" >\n\n <application\n android:allowBackup=\"true\"\n android:icon=\"@drawable/ic_launcher\"\n android:label=\"@string/app_name\"\n android:theme=\"@style/AppTheme\" >\n \n <activity\n android:name=\"com.example.sairamkrishna.myapplication.MainActivity\"\n android:label=\"@string/app_name\" >\n \n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n \n </activity>\n \n </application>\n</manifest>"
},
{
"code": null,
"e": 13613,
"s": 13231,
"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. Before starting your application, ]Android studio will display following window to select an option where you want to run your Android application."
},
{
"code": null,
"e": 13735,
"s": 13613,
"text": "Select your an option and then click on it. For suppose, if you have clicked on yes button, then result would as follows"
},
{
"code": null,
"e": 13819,
"s": 13735,
"text": "if you click on no button it will call finish() and it will close your application."
},
{
"code": null,
"e": 13854,
"s": 13819,
"text": "\n 46 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 13866,
"s": 13854,
"text": " Aditya Dua"
},
{
"code": null,
"e": 13901,
"s": 13866,
"text": "\n 32 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 13915,
"s": 13901,
"text": " Sharad Kumar"
},
{
"code": null,
"e": 13947,
"s": 13915,
"text": "\n 9 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 13964,
"s": 13947,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 13999,
"s": 13964,
"text": "\n 14 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 14016,
"s": 13999,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 14051,
"s": 14016,
"text": "\n 15 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 14068,
"s": 14051,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 14101,
"s": 14068,
"text": "\n 10 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 14118,
"s": 14101,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 14125,
"s": 14118,
"text": " Print"
},
{
"code": null,
"e": 14136,
"s": 14125,
"text": " Add Notes"
}
] |
How to disable Bluetooth in android? | This example demonstrates How to disable Bluetooth in android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
xmlns:app = "http://schemas.android.com/apk/res-auto"
xmlns:tools = "http://schemas.android.com/tools"
android:layout_width = "match_parent"
android:gravity = "center"
android:layout_height = "match_parent"
tools:context = ".MainActivity">
<TextView
android:id = "@+id/text"
android:textSize = "30sp"
android:layout_width = "match_parent"
android:layout_height = "match_parent" />
</LinearLayout>
In the above code, we have taken text view to show Bluetooth status.
Step 3 − Add the following code to src/MainActivity.java
package com.example.myapplication;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.Network;
import android.os.Build;
import android.os.Bundle;
import android.os.health.SystemHealthManager;
import android.provider.Telephony;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.telephony.SmsManager;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView textView;
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.text);
textView.setText("disable");
final BluetoothManager manager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
textView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
manager.getAdapter().disable();
}
});
}
@Override
protected void onStop() {
super.onStop();
}
@Override
protected void onResume() {
super.onResume();
}
}
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": 1125,
"s": 1062,
"text": "This example demonstrates How to disable Bluetooth in android."
},
{
"code": null,
"e": 1254,
"s": 1125,
"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": 1319,
"s": 1254,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 1879,
"s": 1319,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<LinearLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:app = \"http://schemas.android.com/apk/res-auto\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:gravity = \"center\"\n android:layout_height = \"match_parent\"\n tools:context = \".MainActivity\">\n <TextView\n android:id = \"@+id/text\"\n android:textSize = \"30sp\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\" />\n</LinearLayout>"
},
{
"code": null,
"e": 1948,
"s": 1879,
"text": "In the above code, we have taken text view to show Bluetooth status."
},
{
"code": null,
"e": 2005,
"s": 1948,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 3326,
"s": 2005,
"text": "package com.example.myapplication;\nimport android.bluetooth.BluetoothManager;\nimport android.content.Context;\nimport android.net.ConnectivityManager;\nimport android.net.Network;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.os.health.SystemHealthManager;\nimport android.provider.Telephony;\nimport android.support.annotation.RequiresApi;\nimport android.support.v7.app.AppCompatActivity;\nimport android.telephony.SmsManager;\nimport android.view.View;\nimport android.view.WindowManager;\nimport android.widget.TextView;\npublic class MainActivity extends AppCompatActivity {\n TextView textView;\n @RequiresApi(api = Build.VERSION_CODES.N)\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n textView = findViewById(R.id.text);\n textView.setText(\"disable\");\n final BluetoothManager manager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);\n textView.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n manager.getAdapter().disable();\n }\n });\n }\n @Override\n protected void onStop() {\n super.onStop();\n }\n @Override\n protected void onResume() {\n super.onResume();\n }\n}"
},
{
"code": null,
"e": 3673,
"s": 3326,
"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": 3713,
"s": 3673,
"text": "Click here to download the project code"
}
] |
C/C++ Program to Count set bits in an integer? | Here we will see how we can check number of set bits in an integer number. The set bits are 1’s in the binary representation of a number. For an example the number 13 has three set bits 1101. So the count will be 3.
To solve this problem, we will shift the number to the right, and if the LSb is 1, then increase count. Until the number becomes 0, it will run.
begin
count := 0
while count is not 0, do
if LSb of n is set, then
count := count + 1
end if
n := n after shifting 1 bit to right
done
return count
end
Live Demo
#include<iostream>
using namespace std;
int count_set_bit(int n) {
int count = 0;
while(n != 0) {
if(n & 1 == 1) {
count++;
}
n = n >> 1; //right shift 1 bit
}
return count;
}
int main() {
int n;
cout << "Enter a number: ";
cin >> n;
cout << "Number of set bits: " << count_set_bit(n);
}
Enter a number: 29
Number of set bits: 4
This program will run in C and generates output, but when we want to compile in C++, it will return an error during compile time. It will say there are too many arguments are passed. | [
{
"code": null,
"e": 1278,
"s": 1062,
"text": "Here we will see how we can check number of set bits in an integer number. The set bits are 1’s in the binary representation of a number. For an example the number 13 has three set bits 1101. So the count will be 3."
},
{
"code": null,
"e": 1423,
"s": 1278,
"text": "To solve this problem, we will shift the number to the right, and if the LSb is 1, then increase count. Until the number becomes 0, it will run."
},
{
"code": null,
"e": 1617,
"s": 1423,
"text": "begin\n count := 0\n while count is not 0, do\n if LSb of n is set, then\n count := count + 1\n end if\n n := n after shifting 1 bit to right\n done\n return count\nend"
},
{
"code": null,
"e": 1628,
"s": 1617,
"text": " Live Demo"
},
{
"code": null,
"e": 1967,
"s": 1628,
"text": "#include<iostream>\nusing namespace std;\nint count_set_bit(int n) {\n int count = 0;\n while(n != 0) {\n if(n & 1 == 1) {\n count++;\n }\n n = n >> 1; //right shift 1 bit\n }\n return count;\n}\nint main() {\n int n;\n cout << \"Enter a number: \";\n cin >> n;\n cout << \"Number of set bits: \" << count_set_bit(n);\n}"
},
{
"code": null,
"e": 2008,
"s": 1967,
"text": "Enter a number: 29\nNumber of set bits: 4"
},
{
"code": null,
"e": 2191,
"s": 2008,
"text": "This program will run in C and generates output, but when we want to compile in C++, it will return an error during compile time. It will say there are too many arguments are passed."
}
] |
Subsets and Splits