title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Powerful One-Liner Python codes - GeeksforGeeks
17 Feb, 2021 Python is a widely-used general-purpose, high-level programming language. Python programs generally are smaller than other programming languages like Java. Programmers have to type relatively less and indentation requirements of the language makes them readable all the time. However, Python programs can be made more concise using some one-liner codes. These can save time by having less code to type. Refer to the below articles to know more about Python. Python basics One-Liner #1: To input space separated integers in a list: Suppose you want to take space separated input from the console and you want to convert it into List. To do this map() function can be used that takes int() method and input().split() methods as parameter. Here the int() method is used for conversion of input to int type and input().split() methods are used to take input from the console and split the input by spaces. Below is the implementation. lis = list(map(int, input().split())) Note: To know more about Python map() function click here. One-Liner #2: To input a 2-D matrix(When the entries are given row-wise): The most naive method that comes in mind while taking a input for 2-D matrix is given below. # Input for row and columnR = int(input()) C = int(input()) matrix = [] # for loop for row entries for i in range(R): a =[] # for loop for column entries for j in range(C): a.append(int(input())) matrix.append(a) The above code can be written in one-line that is way more concise and saves time especially for competitive programmers. # Input for row and columnR = int(input())C = int(input()) # Using list comprehension for inputmatrix = [[int(input()) for x in range (C)] for y in range(R)] One-Liner #3: We know this fact, but sometimes we tend to ignore it while translating from other languages. It is swapping of two numbers. The most naive way of doing this is: temp = aa = bb = temp However, Python provides one-liner for this also. The Pythonic way is: # to swap two numbers a and ba, b = b, a One-Liner #4 Lambda Functions(Anonymous Functions) – Lambda functions are python one liner functions and are often used when an expression is to be evaluated. For example, let’s suppose we want to create a function that returns the square of the number passed as argument. The normal way of doing this is: def sqr(x): return x * x print(sqr(5)) Output: 25 Lambda function replaces a function wherever a single expression is to be evaluated. sqr = lambda x: x * xprint(sqr(5)) Output: 25 One-Liner #5 List comprehensions – This is a concise way to create lists. Instead of doing it the usual way, we can make use of list comprehensions. For example, we want to create a list of even numbers till 11. The normal way of doing this is: evenNumbers =[]for x in range(11): if x % 2 == 0: evenNumbers.append(x) print(evenNumbers) Output: [0, 2, 4, 6, 8, 10] The pythonic way: evenNumbers =[x for x in range(11) if x % 2 == 0]print(evenNumbers) Output: [0, 2, 4, 6, 8, 10] One-Liner #6: This trick may help while using if-else or while loop. Instead of doing this – if m == 1 or m == 2 or m == 3: pass We can code it as: if m in [1, 2, 3]: pass One-Liner #7: There are various ways to reverse a list in python.Pythonic ways to reverse a list: Using the slicing technique- This technique creates the copy of the list while reversing. It takes up more memory. lis = [1, 2, 3]reversed_list = lis[::-1] print(reversed_list) Output: [3, 2, 1] Using the reverse function- It reverse the contents of the list object in-place. lis = [1, 2, 3]lis.reverse() print(lis) Output: [3, 2, 1] One-Liner #8: You can take this as a challenge. Making one-liner python patterns. For example, Make the following code concise to one line. for i in range(0, 5): for j in range(0, i + 1): # printing stars print("* ", end ="") # ending line after each row print("\r") Output: * * * * * * * * * * * * * * * Concise all this in one line is fun. n = 5 # one liner code for half pyramid patternprint('\n'.join('* ' * i for i in range(1, n + 1))) Output: * * * * * * * * * * * * * * * One-Liner #9 Finding the factorial. The normal way of finding a factorial is iterating till that number and multiplying the number in each iteration. n = 5fact = 1 for i in range(1, n + 1): fact = fact * i print (fact) Output: 120 We can use math.factorial(x)– It returns the factorial of x. But it raises Value error if number is negative or non-integral. import math n = 5print(math.factorial(n)) Output: 120 One more way to do find the factorial concisely is by using reduce() and lambda function. import functools n = 5print(functools.reduce(lambda x, y: x * y, range(1, n + 1))) Output: 120 One-Liner #10: Finding all subsets of a set in one line.Usual way takes a lot of hard work and can be seen here. It can be be done in a much simpler way using itertools.combinations() from itertools import combinations # list of all subsets of # length r (r = 2 in this example) print(list(combinations([1, 2, 3, 4], 2))) [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)] One-Liner #11: Read file in python and input it to a list. file = open('gfg.txt', 'r') lis =[] for each in file: # removing '\n' from the end of the string a = each[:-1] lis.append(a) file.close() One liner code is: lis = [line.strip() for line in open('gfg.txt', 'r')] python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Python | Get unique values from a list Python | os.path.join() method Defaultdict in Python Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25563, "s": 25535, "text": "\n17 Feb, 2021" }, { "code": null, "e": 25966, "s": 25563, "text": "Python is a widely-used general-purpose, high-level programming language. Python programs generally are smaller than other programming languages like Java. Programmers have to type relatively less and indentation requirements of the language makes them readable all the time. However, Python programs can be made more concise using some one-liner codes. These can save time by having less code to type." }, { "code": null, "e": 26021, "s": 25966, "text": "Refer to the below articles to know more about Python." }, { "code": null, "e": 26035, "s": 26021, "text": "Python basics" }, { "code": null, "e": 26094, "s": 26035, "text": "One-Liner #1: To input space separated integers in a list:" }, { "code": null, "e": 26494, "s": 26094, "text": "Suppose you want to take space separated input from the console and you want to convert it into List. To do this map() function can be used that takes int() method and input().split() methods as parameter. Here the int() method is used for conversion of input to int type and input().split() methods are used to take input from the console and split the input by spaces. Below is the implementation." }, { "code": "lis = list(map(int, input().split()))", "e": 26532, "s": 26494, "text": null }, { "code": null, "e": 26591, "s": 26532, "text": "Note: To know more about Python map() function click here." }, { "code": null, "e": 26665, "s": 26591, "text": "One-Liner #2: To input a 2-D matrix(When the entries are given row-wise):" }, { "code": null, "e": 26758, "s": 26665, "text": "The most naive method that comes in mind while taking a input for 2-D matrix is given below." }, { "code": "# Input for row and columnR = int(input()) C = int(input()) matrix = [] # for loop for row entries for i in range(R): a =[] # for loop for column entries for j in range(C): a.append(int(input())) matrix.append(a) ", "e": 27011, "s": 26758, "text": null }, { "code": null, "e": 27133, "s": 27011, "text": "The above code can be written in one-line that is way more concise and saves time especially for competitive programmers." }, { "code": "# Input for row and columnR = int(input())C = int(input()) # Using list comprehension for inputmatrix = [[int(input()) for x in range (C)] for y in range(R)] ", "e": 27293, "s": 27133, "text": null }, { "code": null, "e": 27469, "s": 27293, "text": "One-Liner #3: We know this fact, but sometimes we tend to ignore it while translating from other languages. It is swapping of two numbers. The most naive way of doing this is:" }, { "code": "temp = aa = bb = temp", "e": 27491, "s": 27469, "text": null }, { "code": null, "e": 27562, "s": 27491, "text": "However, Python provides one-liner for this also. The Pythonic way is:" }, { "code": "# to swap two numbers a and ba, b = b, a", "e": 27603, "s": 27562, "text": null }, { "code": null, "e": 27762, "s": 27603, "text": "One-Liner #4 Lambda Functions(Anonymous Functions) – Lambda functions are python one liner functions and are often used when an expression is to be evaluated." }, { "code": null, "e": 27909, "s": 27762, "text": "For example, let’s suppose we want to create a function that returns the square of the number passed as argument. The normal way of doing this is:" }, { "code": "def sqr(x): return x * x print(sqr(5))", "e": 27952, "s": 27909, "text": null }, { "code": null, "e": 27960, "s": 27952, "text": "Output:" }, { "code": null, "e": 27964, "s": 27960, "text": "25\n" }, { "code": null, "e": 28049, "s": 27964, "text": "Lambda function replaces a function wherever a single expression is to be evaluated." }, { "code": "sqr = lambda x: x * xprint(sqr(5))", "e": 28084, "s": 28049, "text": null }, { "code": null, "e": 28092, "s": 28084, "text": "Output:" }, { "code": null, "e": 28096, "s": 28092, "text": "25\n" }, { "code": null, "e": 28245, "s": 28096, "text": "One-Liner #5 List comprehensions – This is a concise way to create lists. Instead of doing it the usual way, we can make use of list comprehensions." }, { "code": null, "e": 28341, "s": 28245, "text": "For example, we want to create a list of even numbers till 11. The normal way of doing this is:" }, { "code": "evenNumbers =[]for x in range(11): if x % 2 == 0: evenNumbers.append(x) print(evenNumbers)", "e": 28443, "s": 28341, "text": null }, { "code": null, "e": 28451, "s": 28443, "text": "Output:" }, { "code": null, "e": 28472, "s": 28451, "text": "[0, 2, 4, 6, 8, 10]\n" }, { "code": null, "e": 28490, "s": 28472, "text": "The pythonic way:" }, { "code": "evenNumbers =[x for x in range(11) if x % 2 == 0]print(evenNumbers)", "e": 28558, "s": 28490, "text": null }, { "code": null, "e": 28566, "s": 28558, "text": "Output:" }, { "code": null, "e": 28587, "s": 28566, "text": "[0, 2, 4, 6, 8, 10]\n" }, { "code": null, "e": 28680, "s": 28587, "text": "One-Liner #6: This trick may help while using if-else or while loop. Instead of doing this –" }, { "code": "if m == 1 or m == 2 or m == 3: pass", "e": 28719, "s": 28680, "text": null }, { "code": null, "e": 28738, "s": 28719, "text": "We can code it as:" }, { "code": "if m in [1, 2, 3]: pass", "e": 28765, "s": 28738, "text": null }, { "code": null, "e": 28863, "s": 28765, "text": "One-Liner #7: There are various ways to reverse a list in python.Pythonic ways to reverse a list:" }, { "code": null, "e": 28978, "s": 28863, "text": "Using the slicing technique- This technique creates the copy of the list while reversing. It takes up more memory." }, { "code": "lis = [1, 2, 3]reversed_list = lis[::-1] print(reversed_list)", "e": 29041, "s": 28978, "text": null }, { "code": null, "e": 29049, "s": 29041, "text": "Output:" }, { "code": null, "e": 29060, "s": 29049, "text": "[3, 2, 1]\n" }, { "code": null, "e": 29141, "s": 29060, "text": "Using the reverse function- It reverse the contents of the list object in-place." }, { "code": "lis = [1, 2, 3]lis.reverse() print(lis)", "e": 29182, "s": 29141, "text": null }, { "code": null, "e": 29190, "s": 29182, "text": "Output:" }, { "code": null, "e": 29201, "s": 29190, "text": "[3, 2, 1]\n" }, { "code": null, "e": 29283, "s": 29201, "text": "One-Liner #8: You can take this as a challenge. Making one-liner python patterns." }, { "code": null, "e": 29341, "s": 29283, "text": "For example, Make the following code concise to one line." }, { "code": "for i in range(0, 5): for j in range(0, i + 1): # printing stars print(\"* \", end =\"\") # ending line after each row print(\"\\r\")", "e": 29533, "s": 29341, "text": null }, { "code": null, "e": 29541, "s": 29533, "text": "Output:" }, { "code": null, "e": 29577, "s": 29541, "text": "* \n* * \n* * * \n* * * * \n* * * * * \n" }, { "code": null, "e": 29614, "s": 29577, "text": "Concise all this in one line is fun." }, { "code": "n = 5 # one liner code for half pyramid patternprint('\\n'.join('* ' * i for i in range(1, n + 1)))", "e": 29714, "s": 29614, "text": null }, { "code": null, "e": 29722, "s": 29714, "text": "Output:" }, { "code": null, "e": 29757, "s": 29722, "text": "* \n* * \n* * * \n* * * * \n* * * * *\n" }, { "code": null, "e": 29907, "s": 29757, "text": "One-Liner #9 Finding the factorial. The normal way of finding a factorial is iterating till that number and multiplying the number in each iteration." }, { "code": "n = 5fact = 1 for i in range(1, n + 1): fact = fact * i print (fact) ", "e": 29984, "s": 29907, "text": null }, { "code": null, "e": 29992, "s": 29984, "text": "Output:" }, { "code": null, "e": 29997, "s": 29992, "text": "120\n" }, { "code": null, "e": 30123, "s": 29997, "text": "We can use math.factorial(x)– It returns the factorial of x. But it raises Value error if number is negative or non-integral." }, { "code": "import math n = 5print(math.factorial(n))", "e": 30168, "s": 30123, "text": null }, { "code": null, "e": 30176, "s": 30168, "text": "Output:" }, { "code": null, "e": 30181, "s": 30176, "text": "120\n" }, { "code": null, "e": 30271, "s": 30181, "text": "One more way to do find the factorial concisely is by using reduce() and lambda function." }, { "code": "import functools n = 5print(functools.reduce(lambda x, y: x * y, range(1, n + 1)))", "e": 30357, "s": 30271, "text": null }, { "code": null, "e": 30365, "s": 30357, "text": "Output:" }, { "code": null, "e": 30370, "s": 30365, "text": "120\n" }, { "code": null, "e": 30554, "s": 30370, "text": "One-Liner #10: Finding all subsets of a set in one line.Usual way takes a lot of hard work and can be seen here. It can be be done in a much simpler way using itertools.combinations()" }, { "code": "from itertools import combinations # list of all subsets of # length r (r = 2 in this example) print(list(combinations([1, 2, 3, 4], 2)))", "e": 30695, "s": 30554, "text": null }, { "code": null, "e": 30745, "s": 30695, "text": "[(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]\n" }, { "code": null, "e": 30804, "s": 30745, "text": "One-Liner #11: Read file in python and input it to a list." }, { "code": "file = open('gfg.txt', 'r') lis =[] for each in file: # removing '\\n' from the end of the string a = each[:-1] lis.append(a) file.close()", "e": 30956, "s": 30804, "text": null }, { "code": null, "e": 30975, "s": 30956, "text": "One liner code is:" }, { "code": "lis = [line.strip() for line in open('gfg.txt', 'r')]", "e": 31029, "s": 30975, "text": null }, { "code": null, "e": 31044, "s": 31029, "text": "python-utility" }, { "code": null, "e": 31051, "s": 31044, "text": "Python" }, { "code": null, "e": 31149, "s": 31051, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31181, "s": 31149, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 31223, "s": 31181, "text": "Check if element exists in list in Python" }, { "code": null, "e": 31265, "s": 31223, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 31292, "s": 31265, "text": "Python Classes and Objects" }, { "code": null, "e": 31348, "s": 31292, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 31387, "s": 31348, "text": "Python | Get unique values from a list" }, { "code": null, "e": 31418, "s": 31387, "text": "Python | os.path.join() method" }, { "code": null, "e": 31440, "s": 31418, "text": "Defaultdict in Python" }, { "code": null, "e": 31469, "s": 31440, "text": "Create a directory in Python" } ]
ReactJS Blueprint Checkbox Component - GeeksforGeeks
08 Apr, 2022 BlueprintJS is a React-based UI toolkit for the web. This library is very optimized and popular for building interfaces that are complex data-dense for desktop applications. Checkbox Component provides a way for users to toggle between checked, unchecked, and indeterminate states. We can use the following approach in ReactJS to use the ReactJS Blueprint Checkbox Component. Checkbox Props: alignIndicator: It is used for the alignment of the indicator within the container. checked: It is used to indicate whether the control is checked or not. children: It is used to denote the JSX label for the control. className: It is used to denote a space-delimited list of class names to pass along to a child element. defaultChecked: It is used to indicate whether the control is initially checked (uncontrolled mode) or not. defaultIndeterminate: It is used to indicate whether this checkbox is initially indeterminate (uncontrolled mode) or not. disabled: It is used to indicate whether the control is non-interactive or not. indeterminate: It is used to indicate whether this checkbox is indeterminate, or partially checked. inline: It is used to indicate whether the control should appear as an inline element or not. inputRef: It is used to denote the ref handler that receives HTML <input> element backing this component. label: It is used to denote the text label for the control. labelElement: It is used to denote the JSX Element label for the control. large: It is used to indicate whether this control should use large styles or not. onChange: It is used to denote the event handler invoked when the input value is changed. tagName: It is used to denote the name of the HTML tag that wraps the checkbox. Creating React Application And Installing Module: Step 1: Create a React application using the following command: npx create-react-app foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command: cd foldername Step 3: After creating the ReactJS application, Install the required module using the following command: npm install @blueprintjs/core Project Structure: It will look like the following. Project Structure Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. Javascript import React from 'react'import '@blueprintjs/core/lib/css/blueprint.css';import { Checkbox } from "@blueprintjs/core"; function App() { return ( <div style={{ display: 'block', width: 500, padding: 30 }}> <h4>ReactJS Blueprint Checkbox Component</h4> Favourite Food: <Checkbox label="Fast Food" defaultIndeterminate={true} /> <Checkbox label="Junk Food" /> <Checkbox label="Sweet Food" /> <Checkbox label="Spicy Food" /> </div> );} export default App; Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: Reference: https://blueprintjs.com/docs/#core/components/checkbox Blueprint-Core Blueprint-Form Controls React-Blueprint JavaScript ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request JavaScript | Promises How to get character array from string in JavaScript? How to fetch data from an API in ReactJS ? How to redirect to another page in ReactJS ? How to pass data from child component to its parent in ReactJS ? How to pass data from one component to other component in ReactJS ? ReactJS Functional Components
[ { "code": null, "e": 26557, "s": 26529, "text": "\n08 Apr, 2022" }, { "code": null, "e": 26933, "s": 26557, "text": "BlueprintJS is a React-based UI toolkit for the web. This library is very optimized and popular for building interfaces that are complex data-dense for desktop applications. Checkbox Component provides a way for users to toggle between checked, unchecked, and indeterminate states. We can use the following approach in ReactJS to use the ReactJS Blueprint Checkbox Component." }, { "code": null, "e": 26949, "s": 26933, "text": "Checkbox Props:" }, { "code": null, "e": 27033, "s": 26949, "text": "alignIndicator: It is used for the alignment of the indicator within the container." }, { "code": null, "e": 27104, "s": 27033, "text": "checked: It is used to indicate whether the control is checked or not." }, { "code": null, "e": 27166, "s": 27104, "text": "children: It is used to denote the JSX label for the control." }, { "code": null, "e": 27270, "s": 27166, "text": "className: It is used to denote a space-delimited list of class names to pass along to a child element." }, { "code": null, "e": 27378, "s": 27270, "text": "defaultChecked: It is used to indicate whether the control is initially checked (uncontrolled mode) or not." }, { "code": null, "e": 27500, "s": 27378, "text": "defaultIndeterminate: It is used to indicate whether this checkbox is initially indeterminate (uncontrolled mode) or not." }, { "code": null, "e": 27580, "s": 27500, "text": "disabled: It is used to indicate whether the control is non-interactive or not." }, { "code": null, "e": 27680, "s": 27580, "text": "indeterminate: It is used to indicate whether this checkbox is indeterminate, or partially checked." }, { "code": null, "e": 27774, "s": 27680, "text": "inline: It is used to indicate whether the control should appear as an inline element or not." }, { "code": null, "e": 27880, "s": 27774, "text": "inputRef: It is used to denote the ref handler that receives HTML <input> element backing this component." }, { "code": null, "e": 27940, "s": 27880, "text": "label: It is used to denote the text label for the control." }, { "code": null, "e": 28014, "s": 27940, "text": "labelElement: It is used to denote the JSX Element label for the control." }, { "code": null, "e": 28097, "s": 28014, "text": "large: It is used to indicate whether this control should use large styles or not." }, { "code": null, "e": 28187, "s": 28097, "text": "onChange: It is used to denote the event handler invoked when the input value is changed." }, { "code": null, "e": 28267, "s": 28187, "text": "tagName: It is used to denote the name of the HTML tag that wraps the checkbox." }, { "code": null, "e": 28317, "s": 28267, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 28381, "s": 28317, "text": "Step 1: Create a React application using the following command:" }, { "code": null, "e": 28413, "s": 28381, "text": "npx create-react-app foldername" }, { "code": null, "e": 28515, "s": 28415, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:" }, { "code": null, "e": 28529, "s": 28515, "text": "cd foldername" }, { "code": null, "e": 28634, "s": 28529, "text": "Step 3: After creating the ReactJS application, Install the required module using the following command:" }, { "code": null, "e": 28664, "s": 28634, "text": "npm install @blueprintjs/core" }, { "code": null, "e": 28716, "s": 28664, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 28734, "s": 28716, "text": "Project Structure" }, { "code": null, "e": 28864, "s": 28734, "text": "Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code." }, { "code": null, "e": 28875, "s": 28864, "text": "Javascript" }, { "code": "import React from 'react'import '@blueprintjs/core/lib/css/blueprint.css';import { Checkbox } from \"@blueprintjs/core\"; function App() { return ( <div style={{ display: 'block', width: 500, padding: 30 }}> <h4>ReactJS Blueprint Checkbox Component</h4> Favourite Food: <Checkbox label=\"Fast Food\" defaultIndeterminate={true} /> <Checkbox label=\"Junk Food\" /> <Checkbox label=\"Sweet Food\" /> <Checkbox label=\"Spicy Food\" /> </div> );} export default App;", "e": 29436, "s": 28875, "text": null }, { "code": null, "e": 29549, "s": 29436, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 29559, "s": 29549, "text": "npm start" }, { "code": null, "e": 29658, "s": 29559, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 29724, "s": 29658, "text": "Reference: https://blueprintjs.com/docs/#core/components/checkbox" }, { "code": null, "e": 29739, "s": 29724, "text": "Blueprint-Core" }, { "code": null, "e": 29763, "s": 29739, "text": "Blueprint-Form Controls" }, { "code": null, "e": 29779, "s": 29763, "text": "React-Blueprint" }, { "code": null, "e": 29790, "s": 29779, "text": "JavaScript" }, { "code": null, "e": 29798, "s": 29790, "text": "ReactJS" }, { "code": null, "e": 29815, "s": 29798, "text": "Web Technologies" }, { "code": null, "e": 29913, "s": 29815, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29953, "s": 29913, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 30014, "s": 29953, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 30055, "s": 30014, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 30077, "s": 30055, "text": "JavaScript | Promises" }, { "code": null, "e": 30131, "s": 30077, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 30174, "s": 30131, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 30219, "s": 30174, "text": "How to redirect to another page in ReactJS ?" }, { "code": null, "e": 30284, "s": 30219, "text": "How to pass data from child component to its parent in ReactJS ?" }, { "code": null, "e": 30352, "s": 30284, "text": "How to pass data from one component to other component in ReactJS ?" } ]
Finding roots of a quadratic equation – JavaScript
We are required to write a JavaScript function that takes in three numbers (representing the coefficient of quadratic term, coefficient of linear term and the constant respectively in a quadratic quadratic). And we are required to find the roots, (if they are real roots) otherwise we have to return false. Let's write the code for this function Following is the code − const coefficients = [3, 12, 2]; const findRoots = co => { const [a, b, c] = co; const discriminant = (b * b) - 4 * a * c; if(discriminant < 0){ // the roots are non-real roots return false; }; const d = Math.sqrt(discriminant); const x1 = (d - b) / (2 * a); const x2 = ((d + b) * -1) / (2 * a); return [x1, x2]; }; console.log(findRoots(coefficients)); The output in the console − [ -0.17425814164944628, -3.825741858350554 ]
[ { "code": null, "e": 1270, "s": 1062, "text": "We are required to write a JavaScript function that takes in three numbers (representing the coefficient of quadratic term, coefficient of linear term and the constant respectively in a quadratic quadratic)." }, { "code": null, "e": 1408, "s": 1270, "text": "And we are required to find the roots, (if they are real roots) otherwise we have to return false. Let's write the code for this function" }, { "code": null, "e": 1432, "s": 1408, "text": "Following is the code −" }, { "code": null, "e": 1822, "s": 1432, "text": "const coefficients = [3, 12, 2];\nconst findRoots = co => {\n const [a, b, c] = co;\n const discriminant = (b * b) - 4 * a * c;\n if(discriminant < 0){\n // the roots are non-real roots\n return false;\n };\n const d = Math.sqrt(discriminant);\n const x1 = (d - b) / (2 * a);\n const x2 = ((d + b) * -1) / (2 * a);\n return [x1, x2];\n};\nconsole.log(findRoots(coefficients));" }, { "code": null, "e": 1850, "s": 1822, "text": "The output in the console −" }, { "code": null, "e": 1895, "s": 1850, "text": "[ -0.17425814164944628, -3.825741858350554 ]" } ]
Differential or Derivatives in MATLAB - GeeksforGeeks
23 Aug, 2021 Differentiation of a function y = f(x) tells us how the value of y changes with respect to change in x. It can also be termed as the slope of a function. Derivative of a function f(x) wrt to x is represented as MATLAB allows users to calculate the derivative of a function using diff() method. Different syntax of diff() method are: f’ = diff(f) f’ = diff(f, a) f’ = diff(f, b, 2) It returns the derivative of function f(x) wrt variable x. Example 1: Matlab % Create a symbolic expression in variable xsyms xf = cos(x);disp("f(x) :");disp(f); % Derivative of f(x)d = diff(f);disp("Derivative of f(x) :");disp(d); Output : Example 2: Evaluating the derivative of a function at a specified value using subs(y,x,k). subs(y,x,k), it gives the value of function y at x = k. Matlab % Create a symbolic expression in# variable xsyms xf = cos(x);disp("f(x) :");disp(f); % Derivative of f(x)d = diff(f);val = subs(d,x,pi/2); disp("Value of f'(x) at x = pi/2:");disp(val); Output : It returns the derivative of function f with respect to variable a. Matlab % Create a symbolic expression in variable xsyms x t;f = sin(x*t);disp("f(x) :");disp(f); % Derivative of f(x,t) wrt td = diff(f,t);disp("Derivative of f(x,t) wrt t:");disp(d); Output : It returns the double derivative of function f with respect to variable b. Example 1: Matlab % Create a symbolic expression in% variable x,nsyms x n;f = x^n;disp("f(x,n) :");disp(f); % Double Derivative of f(x,n) wrt xd = diff(f,x,2);disp("Double Derivative of f(x,n) wrt x:");disp(d); Output : In the same way, you can also calculate the k-order derivative of function f using diff(f,x,k). Example 2: Calculating the partial derivative } using Jacobian matrix and determinant. Matlab % Create a symbolic expression in variable% u and vsyms u v;f = u^2;g = sin(v)*(3*u);disp("f(u,v) :");disp(f);disp("g(u,v) :");disp(g); % Jacobian matrix of function f(u,v) and% g(u,v)J = jacobian([f; g], [u v]);disp("Jacobian matrix :");disp(J); % Determinant of Jacobian matrixd = det(J);disp("Determinant of Jacobian matrix:");disp(d); Output : ruhelaa48 MATLAB-Maths Picked MATLAB Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Remove Noise from Digital Image in Frequency Domain Using MATLAB? Boundary Extraction of image using MATLAB Laplacian of Gaussian Filter in MATLAB Forward and Inverse Fourier Transform of an Image in MATLAB How to Perform Contrast Enhancement of Color Image in MATLAB? How to Solve Histogram Equalization Numerical Problem in MATLAB? How to Normalize a Histogram in MATLAB? Turn an Array into a Column Vector in MATLAB Trigonometric Functions in MATLAB Laplace Transform in MATLAB
[ { "code": null, "e": 24566, "s": 24538, "text": "\n23 Aug, 2021" }, { "code": null, "e": 24720, "s": 24566, "text": "Differentiation of a function y = f(x) tells us how the value of y changes with respect to change in x. It can also be termed as the slope of a function." }, { "code": null, "e": 24778, "s": 24720, "text": "Derivative of a function f(x) wrt to x is represented as " }, { "code": null, "e": 24900, "s": 24778, "text": "MATLAB allows users to calculate the derivative of a function using diff() method. Different syntax of diff() method are:" }, { "code": null, "e": 24913, "s": 24900, "text": "f’ = diff(f)" }, { "code": null, "e": 24929, "s": 24913, "text": "f’ = diff(f, a)" }, { "code": null, "e": 24948, "s": 24929, "text": "f’ = diff(f, b, 2)" }, { "code": null, "e": 25007, "s": 24948, "text": "It returns the derivative of function f(x) wrt variable x." }, { "code": null, "e": 25018, "s": 25007, "text": "Example 1:" }, { "code": null, "e": 25025, "s": 25018, "text": "Matlab" }, { "code": "% Create a symbolic expression in variable xsyms xf = cos(x);disp(\"f(x) :\");disp(f); % Derivative of f(x)d = diff(f);disp(\"Derivative of f(x) :\");disp(d);", "e": 25180, "s": 25025, "text": null }, { "code": null, "e": 25189, "s": 25180, "text": "Output :" }, { "code": null, "e": 25280, "s": 25189, "text": "Example 2: Evaluating the derivative of a function at a specified value using subs(y,x,k)." }, { "code": null, "e": 25336, "s": 25280, "text": "subs(y,x,k), it gives the value of function y at x = k." }, { "code": null, "e": 25343, "s": 25336, "text": "Matlab" }, { "code": "% Create a symbolic expression in# variable xsyms xf = cos(x);disp(\"f(x) :\");disp(f); % Derivative of f(x)d = diff(f);val = subs(d,x,pi/2); disp(\"Value of f'(x) at x = pi/2:\");disp(val);", "e": 25530, "s": 25343, "text": null }, { "code": null, "e": 25539, "s": 25530, "text": "Output :" }, { "code": null, "e": 25607, "s": 25539, "text": "It returns the derivative of function f with respect to variable a." }, { "code": null, "e": 25614, "s": 25607, "text": "Matlab" }, { "code": "% Create a symbolic expression in variable xsyms x t;f = sin(x*t);disp(\"f(x) :\");disp(f); % Derivative of f(x,t) wrt td = diff(f,t);disp(\"Derivative of f(x,t) wrt t:\");disp(d);", "e": 25791, "s": 25614, "text": null }, { "code": null, "e": 25800, "s": 25791, "text": "Output :" }, { "code": null, "e": 25875, "s": 25800, "text": "It returns the double derivative of function f with respect to variable b." }, { "code": null, "e": 25886, "s": 25875, "text": "Example 1:" }, { "code": null, "e": 25893, "s": 25886, "text": "Matlab" }, { "code": "% Create a symbolic expression in% variable x,nsyms x n;f = x^n;disp(\"f(x,n) :\");disp(f); % Double Derivative of f(x,n) wrt xd = diff(f,x,2);disp(\"Double Derivative of f(x,n) wrt x:\");disp(d);", "e": 26086, "s": 25893, "text": null }, { "code": null, "e": 26095, "s": 26086, "text": "Output :" }, { "code": null, "e": 26191, "s": 26095, "text": "In the same way, you can also calculate the k-order derivative of function f using diff(f,x,k)." }, { "code": null, "e": 26203, "s": 26191, "text": "Example 2: " }, { "code": null, "e": 26279, "s": 26203, "text": "Calculating the partial derivative } using Jacobian matrix and determinant." }, { "code": null, "e": 26289, "s": 26282, "text": "Matlab" }, { "code": "% Create a symbolic expression in variable% u and vsyms u v;f = u^2;g = sin(v)*(3*u);disp(\"f(u,v) :\");disp(f);disp(\"g(u,v) :\");disp(g); % Jacobian matrix of function f(u,v) and% g(u,v)J = jacobian([f; g], [u v]);disp(\"Jacobian matrix :\");disp(J); % Determinant of Jacobian matrixd = det(J);disp(\"Determinant of Jacobian matrix:\");disp(d);", "e": 26628, "s": 26289, "text": null }, { "code": null, "e": 26641, "s": 26632, "text": "Output :" }, { "code": null, "e": 26655, "s": 26645, "text": "ruhelaa48" }, { "code": null, "e": 26668, "s": 26655, "text": "MATLAB-Maths" }, { "code": null, "e": 26675, "s": 26668, "text": "Picked" }, { "code": null, "e": 26682, "s": 26675, "text": "MATLAB" }, { "code": null, "e": 26780, "s": 26682, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26789, "s": 26780, "text": "Comments" }, { "code": null, "e": 26802, "s": 26789, "text": "Old Comments" }, { "code": null, "e": 26875, "s": 26802, "text": "How to Remove Noise from Digital Image in Frequency Domain Using MATLAB?" }, { "code": null, "e": 26917, "s": 26875, "text": "Boundary Extraction of image using MATLAB" }, { "code": null, "e": 26956, "s": 26917, "text": "Laplacian of Gaussian Filter in MATLAB" }, { "code": null, "e": 27016, "s": 26956, "text": "Forward and Inverse Fourier Transform of an Image in MATLAB" }, { "code": null, "e": 27078, "s": 27016, "text": "How to Perform Contrast Enhancement of Color Image in MATLAB?" }, { "code": null, "e": 27143, "s": 27078, "text": "How to Solve Histogram Equalization Numerical Problem in MATLAB?" }, { "code": null, "e": 27183, "s": 27143, "text": "How to Normalize a Histogram in MATLAB?" }, { "code": null, "e": 27228, "s": 27183, "text": "Turn an Array into a Column Vector in MATLAB" }, { "code": null, "e": 27262, "s": 27228, "text": "Trigonometric Functions in MATLAB" } ]
Kalman Filter(3) — Localisation in Continuous State Space | by Jeremy Zhang | Towards Data Science
In past sessions, we tried to do localisation in a grid world, where our robot has different probabilities locating in different cells. In a word, the state space is discrete. To generalise the problem setting to continuous state space, we will get to the core of kalman filter. Before we get to any details of kalman filter, please bear in mind of what we have learnt here, that there is going to be always 2 steps of kalman filter: Sensing(Measurement): based on what the robot is seeing, update the posterior distributionMoving(Prediction): estimate the new location after the robot makes a movement Sensing(Measurement): based on what the robot is seeing, update the posterior distribution Moving(Prediction): estimate the new location after the robot makes a movement The following has a structure of: The ideas of extending to continuous state spaceImplementing the sense(measurement) with gaussian distributionImplementing the move(prediction) with gaussian distributionCombine all togetherMulti-dimensional Kalman Filter The ideas of extending to continuous state space Implementing the sense(measurement) with gaussian distribution Implementing the move(prediction) with gaussian distribution Combine all together Multi-dimensional Kalman Filter In a discrete world, each state has a separate probability which adds up to 1, and the key to extend it to continuous state space is to find a continuous distribution, while here in kalman filter, the distribution is gaussian distribution. This is saying that our estimation of the robot position always conforms to a gaussian distribution regardless it is in step measurement or prediction. The 2 parameters of gaussian each represent: μ : the most likely estimation of robot’s locationσ : the uncertainty of our estimation caused by imprecision of detectors and predictions, etc. μ : the most likely estimation of robot’s location σ : the uncertainty of our estimation caused by imprecision of detectors and predictions, etc. And the task would be to find the final gaussian distribution with parameter μ and σ after a series of measurements and predictions. Let’s break it down into 2 parts. In measurement phase, we update our belief based on the robot’s sensor. Suppose X is the location and Z is the measurement(what the robot observes), the problem we are solving is: Our prior belief is p(X) , however our sensor sees it differently with a distribution of p(Z|X) , and now we are trying to calculate our posterior distribution p(X|Z) , that is given what we see( Z ), what is our best estimation now? Remember that here all distributions are gaussian, in order to get the posterior distribution we only need to apply the Bayes Rule, which is to multiply these 2 distributions: Above is the parameters of updated distribution. Notice that σ_new is smaller than both σ and γ ! This tells us that the uncertainty reduced after multiplication, which conforms to our knowledge that sensing is actually gaining information and reduce uncertainty. The implementation would be: Moving is addition which is straight forward. With initial distribution N(μ, σ), and move U with uncertainty γ^2, the distribution after movement is N(μ+U, σ^2+γ^2) , that is the mean is added with U and uncertainty is added with γ^2 . Notice that by making a movement which is uncertain, the variance(uncertainty) increases which is in contrast with measurement that reduces variance(uncertainty). Now combining measurement and prediction we got: In the example, we set the initial position mu = 0 and uncertainty sig = 10000 , meaning we are super uncertain with the robot’s initial position. After a few rounds of iteration, we got the result: We saw that by making the first measurement, the uncertainty instantly drops to 3.998 , which is smaller than both the initial variance and measurement variance. And finally we predict our robot landing in position 10.9999 with variance 4.0058 . The above example we have only one variable which is the position p . Now let’s consider a second variable velocity v , then our task will be to get the final estimation of x = (p, v) and uncertainty matrix P = cov(x) . In the prediction phase, suppose we have the relation: That given a speed and time t , we can get our next position and the velocity we assume remains the same. Then we got its matrix form: Here F is called state transition matrix, P is covariance matrix and μ is external motion vector(say there is acceleration or pedal throttle). Same goes with measurement, there is a measurement transition matrix H . In its simplest form, let’s assume that H = (1, 0) and, μ_0 = Hx = (1, 0)(p, v)^T = p This is saying that our measurement can only measure the position of the robot and we can not see the velocity. Now the problem turns into that we have two gaussian distributions, one is(the prior distribution): and the second is(the measurement distribution): Looks familiar with our previous examples, right? Now we need to combine these two distributions into posterior distribution. Here involves a series of deduction(one excellent explanation here), and I will put the result here: Now let’s combine them together and get our final kalman filter function: For complete implementation, please checkout here.
[ { "code": null, "e": 326, "s": 47, "text": "In past sessions, we tried to do localisation in a grid world, where our robot has different probabilities locating in different cells. In a word, the state space is discrete. To generalise the problem setting to continuous state space, we will get to the core of kalman filter." }, { "code": null, "e": 481, "s": 326, "text": "Before we get to any details of kalman filter, please bear in mind of what we have learnt here, that there is going to be always 2 steps of kalman filter:" }, { "code": null, "e": 650, "s": 481, "text": "Sensing(Measurement): based on what the robot is seeing, update the posterior distributionMoving(Prediction): estimate the new location after the robot makes a movement" }, { "code": null, "e": 741, "s": 650, "text": "Sensing(Measurement): based on what the robot is seeing, update the posterior distribution" }, { "code": null, "e": 820, "s": 741, "text": "Moving(Prediction): estimate the new location after the robot makes a movement" }, { "code": null, "e": 854, "s": 820, "text": "The following has a structure of:" }, { "code": null, "e": 1076, "s": 854, "text": "The ideas of extending to continuous state spaceImplementing the sense(measurement) with gaussian distributionImplementing the move(prediction) with gaussian distributionCombine all togetherMulti-dimensional Kalman Filter" }, { "code": null, "e": 1125, "s": 1076, "text": "The ideas of extending to continuous state space" }, { "code": null, "e": 1188, "s": 1125, "text": "Implementing the sense(measurement) with gaussian distribution" }, { "code": null, "e": 1249, "s": 1188, "text": "Implementing the move(prediction) with gaussian distribution" }, { "code": null, "e": 1270, "s": 1249, "text": "Combine all together" }, { "code": null, "e": 1302, "s": 1270, "text": "Multi-dimensional Kalman Filter" }, { "code": null, "e": 1542, "s": 1302, "text": "In a discrete world, each state has a separate probability which adds up to 1, and the key to extend it to continuous state space is to find a continuous distribution, while here in kalman filter, the distribution is gaussian distribution." }, { "code": null, "e": 1739, "s": 1542, "text": "This is saying that our estimation of the robot position always conforms to a gaussian distribution regardless it is in step measurement or prediction. The 2 parameters of gaussian each represent:" }, { "code": null, "e": 1884, "s": 1739, "text": "μ : the most likely estimation of robot’s locationσ : the uncertainty of our estimation caused by imprecision of detectors and predictions, etc." }, { "code": null, "e": 1935, "s": 1884, "text": "μ : the most likely estimation of robot’s location" }, { "code": null, "e": 2030, "s": 1935, "text": "σ : the uncertainty of our estimation caused by imprecision of detectors and predictions, etc." }, { "code": null, "e": 2197, "s": 2030, "text": "And the task would be to find the final gaussian distribution with parameter μ and σ after a series of measurements and predictions. Let’s break it down into 2 parts." }, { "code": null, "e": 2377, "s": 2197, "text": "In measurement phase, we update our belief based on the robot’s sensor. Suppose X is the location and Z is the measurement(what the robot observes), the problem we are solving is:" }, { "code": null, "e": 2611, "s": 2377, "text": "Our prior belief is p(X) , however our sensor sees it differently with a distribution of p(Z|X) , and now we are trying to calculate our posterior distribution p(X|Z) , that is given what we see( Z ), what is our best estimation now?" }, { "code": null, "e": 2787, "s": 2611, "text": "Remember that here all distributions are gaussian, in order to get the posterior distribution we only need to apply the Bayes Rule, which is to multiply these 2 distributions:" }, { "code": null, "e": 3080, "s": 2787, "text": "Above is the parameters of updated distribution. Notice that σ_new is smaller than both σ and γ ! This tells us that the uncertainty reduced after multiplication, which conforms to our knowledge that sensing is actually gaining information and reduce uncertainty. The implementation would be:" }, { "code": null, "e": 3316, "s": 3080, "text": "Moving is addition which is straight forward. With initial distribution N(μ, σ), and move U with uncertainty γ^2, the distribution after movement is N(μ+U, σ^2+γ^2) , that is the mean is added with U and uncertainty is added with γ^2 ." }, { "code": null, "e": 3479, "s": 3316, "text": "Notice that by making a movement which is uncertain, the variance(uncertainty) increases which is in contrast with measurement that reduces variance(uncertainty)." }, { "code": null, "e": 3528, "s": 3479, "text": "Now combining measurement and prediction we got:" }, { "code": null, "e": 3727, "s": 3528, "text": "In the example, we set the initial position mu = 0 and uncertainty sig = 10000 , meaning we are super uncertain with the robot’s initial position. After a few rounds of iteration, we got the result:" }, { "code": null, "e": 3973, "s": 3727, "text": "We saw that by making the first measurement, the uncertainty instantly drops to 3.998 , which is smaller than both the initial variance and measurement variance. And finally we predict our robot landing in position 10.9999 with variance 4.0058 ." }, { "code": null, "e": 4193, "s": 3973, "text": "The above example we have only one variable which is the position p . Now let’s consider a second variable velocity v , then our task will be to get the final estimation of x = (p, v) and uncertainty matrix P = cov(x) ." }, { "code": null, "e": 4248, "s": 4193, "text": "In the prediction phase, suppose we have the relation:" }, { "code": null, "e": 4383, "s": 4248, "text": "That given a speed and time t , we can get our next position and the velocity we assume remains the same. Then we got its matrix form:" }, { "code": null, "e": 4526, "s": 4383, "text": "Here F is called state transition matrix, P is covariance matrix and μ is external motion vector(say there is acceleration or pedal throttle)." }, { "code": null, "e": 4655, "s": 4526, "text": "Same goes with measurement, there is a measurement transition matrix H . In its simplest form, let’s assume that H = (1, 0) and," }, { "code": null, "e": 4686, "s": 4655, "text": " μ_0 = Hx = (1, 0)(p, v)^T = p" }, { "code": null, "e": 4898, "s": 4686, "text": "This is saying that our measurement can only measure the position of the robot and we can not see the velocity. Now the problem turns into that we have two gaussian distributions, one is(the prior distribution):" }, { "code": null, "e": 4947, "s": 4898, "text": "and the second is(the measurement distribution):" }, { "code": null, "e": 5174, "s": 4947, "text": "Looks familiar with our previous examples, right? Now we need to combine these two distributions into posterior distribution. Here involves a series of deduction(one excellent explanation here), and I will put the result here:" }, { "code": null, "e": 5248, "s": 5174, "text": "Now let’s combine them together and get our final kalman filter function:" } ]
Sum of the Tan(x) expansion upto N terms - GeeksforGeeks
14 Apr, 2021 Given two integers N and X. The task is to find the sum of tan(x) series up to N terms.The series : x + x3/3 + 2x5/15 + 17x7/315 + 62x9/2835........ Examples: Input : N = 6, X = 1 Output :The value from the expansion is 1.55137626113259Input : N = 4, X = 2 Output :The value from the expansion is 1.52063492063426 Approach : The expansion of tan(x) is shown here. Compute the each term using a simple loops and get the required answer. C++ Java Python3 C# Javascript // CPP program to find tan(x) expansion#include <bits/stdc++.h>using namespace std; // Function to find factorial of a numberint fac(int num){ if (num == 0) return 1; // To store factorial of a number int fact = 1; for (int i = 1; i <= num; i++) fact = fact * i; // Return the factorial of a number return fact;} // Function to find tan(x) upto n termsvoid Tanx_expansion(int terms, int x){ // To store value of the expansion double sum = 0; for (int i = 1; i <= terms; i += 1) { // This loops here calculate Bernoulli number // which is further used to get the coefficient // in the expansion of tan x double B = 0; int Bn = 2 * i; for (int k = 0; k <= Bn; k++) { double temp = 0; for (int r = 0; r <= k; r++) temp = temp + pow(-1, r) * fac(k) * pow(r, Bn) / (fac(r) * fac(k - r)); B = B + temp / ((double)(k + 1)); } sum = sum + pow(-4, i) * (1 - pow(4, i)) * B * pow(x, 2 * i - 1) / fac(2 * i); } // Print the value of expansion cout << setprecision(10) << sum;} // Driver codeint main(){ int n = 6, x = 1; // Function call Tanx_expansion(n, x); return 0;} // Java program to find tan(x) expansionclass GFG{ // Function to find factorial of a numberstatic int fac(int num){ if (num == 0) return 1; // To store factorial of a number int fact = 1; for (int i = 1; i <= num; i++) fact = fact * i; // Return the factorial of a number return fact;} // Function to find tan(x) upto n termsstatic void Tanx_expansion(int terms, int x){ // To store value of the expansion double sum = 0; for (int i = 1; i <= terms; i += 1) { // This loops here calculate Bernoulli number // which is further used to get the coefficient // in the expansion of tan x double B = 0; int Bn = 2 * i; for (int k = 0; k <= Bn; k++) { double temp = 0; for (int r = 0; r <= k; r++) temp = temp + Math.pow(-1, r) * fac(k) * Math.pow(r, Bn) / (fac(r) * fac(k - r)); B = B + temp / ((double)(k + 1)); } sum = sum + Math.pow(-4, i) * (1 - Math.pow(4, i)) * B * Math.pow(x, 2 * i - 1) / fac(2 * i); } // Print the value of expansion System.out.printf("%.9f", sum);} // Driver codepublic static void main(String[] args){ int n = 6, x = 1; // Function call Tanx_expansion(n, x);}} // This code is contributed by Rajput-Ji # Python3 program to find tan(x) expansion # Function to find factorial of a numberdef fac(num): if (num == 0): return 1; # To store factorial of a number fact = 1; for i in range(1, num + 1): fact = fact * i; # Return the factorial of a number return fact; # Function to find tan(x) upto n termsdef Tanx_expansion(terms, x): # To store value of the expansion sum = 0; for i in range(1, terms + 1): # This loops here calculate Bernoulli number # which is further used to get the coefficient # in the expansion of tan x B = 0; Bn = 2 * i; for k in range(Bn + 1): temp = 0; for r in range(0, k + 1): temp = temp + pow(-1, r) * fac(k) \ * pow(r, Bn) / (fac(r) * fac(k - r)); B = B + temp / ((k + 1)); sum = sum + pow(-4, i) * (1 - pow(4, i)) \ * B * pow(x, 2 * i - 1) / fac(2 * i); # Print the value of expansion print("%.9f" %(sum)); # Driver codeif __name__ == '__main__': n, x = 6, 1; # Function call Tanx_expansion(n, x); # This code is contributed by Rajput-Ji // C# program to find tan(x) expansionusing System; class GFG{ // Function to find factorial of a numberstatic int fac(int num){ if (num == 0) return 1; // To store factorial of a number int fact = 1; for (int i = 1; i <= num; i++) fact = fact * i; // Return the factorial of a number return fact;} // Function to find tan(x) upto n termsstatic void Tanx_expansion(int terms, int x){ // To store value of the expansion double sum = 0; for (int i = 1; i <= terms; i += 1) { // This loop here calculates // Bernoulli number which is // further used to get the coefficient // in the expansion of tan x double B = 0; int Bn = 2 * i; for (int k = 0; k <= Bn; k++) { double temp = 0; for (int r = 0; r <= k; r++) temp = temp + Math.Pow(-1, r) * fac(k) * Math.Pow(r, Bn) / (fac(r) * fac(k - r)); B = B + temp / ((double)(k + 1)); } sum = sum + Math.Pow(-4, i) * (1 - Math.Pow(4, i)) * B * Math.Pow(x, 2 * i - 1) / fac(2 * i); } // Print the value of expansion Console.Write("{0:F9}", sum);} // Driver codepublic static void Main(String[] args){ int n = 6, x = 1; // Function call Tanx_expansion(n, x);}} // This code is contributed by 29AjayKumar <script> // JavaScript program to find tan(x) expansion // Function to find factorial of a numberfunction fac(num){ if (num == 0) return 1; // To store factorial of a number let fact = 1; for (let i = 1; i <= num; i++) fact = fact * i; // Return the factorial of a number return fact;} // Function to find tan(x) upto n termsfunction Tanx_expansion(terms, x){ // To store value of the expansion let sum = 0; for (let i = 1; i <= terms; i += 1) { // This loops here calculate Bernoulli number // which is further used to get the coefficient // in the expansion of tan x let B = 0; let Bn = 2 * i; for (let k = 0; k <= Bn; k++) { let temp = 0; for (let r = 0; r <= k; r++) temp = temp + Math.pow(-1, r) * fac(k) * Math.pow(r, Bn) / (fac(r) * fac(k - r)); B = B + temp / (k + 1); } sum =sum + Math.pow(-4, i) * (1 - Math.pow(4, i)) * B * Math.pow(x, 2 * i - 1) / fac(2 * i); } // Print the value of expansion document.write(sum.toFixed(10));} // Driver code let n = 6, x = 1; // Function call Tanx_expansion(n, x); // This code is contributed by Surbhi Tyagi. </script> 1.551373344 Rajput-Ji 29AjayKumar surbhityagi15 series-sum Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program to print prime numbers from 1 to N. Modular multiplicative inverse Fizz Buzz Implementation Singular Value Decomposition (SVD) Check if a number is Palindrome Segment Tree | Set 1 (Sum of given range) How to check if a given point lies inside or outside a polygon? Program to multiply two matrices Count ways to reach the n'th stair Merge two sorted arrays with O(1) extra space
[ { "code": null, "e": 26072, "s": 26044, "text": "\n14 Apr, 2021" }, { "code": null, "e": 26174, "s": 26072, "text": "Given two integers N and X. The task is to find the sum of tan(x) series up to N terms.The series : " }, { "code": null, "e": 26223, "s": 26174, "text": "x + x3/3 + 2x5/15 + 17x7/315 + 62x9/2835........" }, { "code": null, "e": 26235, "s": 26223, "text": "Examples: " }, { "code": null, "e": 26390, "s": 26235, "text": "Input : N = 6, X = 1 Output :The value from the expansion is 1.55137626113259Input : N = 4, X = 2 Output :The value from the expansion is 1.52063492063426" }, { "code": null, "e": 26516, "s": 26392, "text": "Approach : The expansion of tan(x) is shown here. Compute the each term using a simple loops and get the required answer. " }, { "code": null, "e": 26520, "s": 26516, "text": "C++" }, { "code": null, "e": 26525, "s": 26520, "text": "Java" }, { "code": null, "e": 26533, "s": 26525, "text": "Python3" }, { "code": null, "e": 26536, "s": 26533, "text": "C#" }, { "code": null, "e": 26547, "s": 26536, "text": "Javascript" }, { "code": "// CPP program to find tan(x) expansion#include <bits/stdc++.h>using namespace std; // Function to find factorial of a numberint fac(int num){ if (num == 0) return 1; // To store factorial of a number int fact = 1; for (int i = 1; i <= num; i++) fact = fact * i; // Return the factorial of a number return fact;} // Function to find tan(x) upto n termsvoid Tanx_expansion(int terms, int x){ // To store value of the expansion double sum = 0; for (int i = 1; i <= terms; i += 1) { // This loops here calculate Bernoulli number // which is further used to get the coefficient // in the expansion of tan x double B = 0; int Bn = 2 * i; for (int k = 0; k <= Bn; k++) { double temp = 0; for (int r = 0; r <= k; r++) temp = temp + pow(-1, r) * fac(k) * pow(r, Bn) / (fac(r) * fac(k - r)); B = B + temp / ((double)(k + 1)); } sum = sum + pow(-4, i) * (1 - pow(4, i)) * B * pow(x, 2 * i - 1) / fac(2 * i); } // Print the value of expansion cout << setprecision(10) << sum;} // Driver codeint main(){ int n = 6, x = 1; // Function call Tanx_expansion(n, x); return 0;}", "e": 27846, "s": 26547, "text": null }, { "code": "// Java program to find tan(x) expansionclass GFG{ // Function to find factorial of a numberstatic int fac(int num){ if (num == 0) return 1; // To store factorial of a number int fact = 1; for (int i = 1; i <= num; i++) fact = fact * i; // Return the factorial of a number return fact;} // Function to find tan(x) upto n termsstatic void Tanx_expansion(int terms, int x){ // To store value of the expansion double sum = 0; for (int i = 1; i <= terms; i += 1) { // This loops here calculate Bernoulli number // which is further used to get the coefficient // in the expansion of tan x double B = 0; int Bn = 2 * i; for (int k = 0; k <= Bn; k++) { double temp = 0; for (int r = 0; r <= k; r++) temp = temp + Math.pow(-1, r) * fac(k) * Math.pow(r, Bn) / (fac(r) * fac(k - r)); B = B + temp / ((double)(k + 1)); } sum = sum + Math.pow(-4, i) * (1 - Math.pow(4, i)) * B * Math.pow(x, 2 * i - 1) / fac(2 * i); } // Print the value of expansion System.out.printf(\"%.9f\", sum);} // Driver codepublic static void main(String[] args){ int n = 6, x = 1; // Function call Tanx_expansion(n, x);}} // This code is contributed by Rajput-Ji", "e": 29269, "s": 27846, "text": null }, { "code": "# Python3 program to find tan(x) expansion # Function to find factorial of a numberdef fac(num): if (num == 0): return 1; # To store factorial of a number fact = 1; for i in range(1, num + 1): fact = fact * i; # Return the factorial of a number return fact; # Function to find tan(x) upto n termsdef Tanx_expansion(terms, x): # To store value of the expansion sum = 0; for i in range(1, terms + 1): # This loops here calculate Bernoulli number # which is further used to get the coefficient # in the expansion of tan x B = 0; Bn = 2 * i; for k in range(Bn + 1): temp = 0; for r in range(0, k + 1): temp = temp + pow(-1, r) * fac(k) \\ * pow(r, Bn) / (fac(r) * fac(k - r)); B = B + temp / ((k + 1)); sum = sum + pow(-4, i) * (1 - pow(4, i)) \\ * B * pow(x, 2 * i - 1) / fac(2 * i); # Print the value of expansion print(\"%.9f\" %(sum)); # Driver codeif __name__ == '__main__': n, x = 6, 1; # Function call Tanx_expansion(n, x); # This code is contributed by Rajput-Ji", "e": 30424, "s": 29269, "text": null }, { "code": "// C# program to find tan(x) expansionusing System; class GFG{ // Function to find factorial of a numberstatic int fac(int num){ if (num == 0) return 1; // To store factorial of a number int fact = 1; for (int i = 1; i <= num; i++) fact = fact * i; // Return the factorial of a number return fact;} // Function to find tan(x) upto n termsstatic void Tanx_expansion(int terms, int x){ // To store value of the expansion double sum = 0; for (int i = 1; i <= terms; i += 1) { // This loop here calculates // Bernoulli number which is // further used to get the coefficient // in the expansion of tan x double B = 0; int Bn = 2 * i; for (int k = 0; k <= Bn; k++) { double temp = 0; for (int r = 0; r <= k; r++) temp = temp + Math.Pow(-1, r) * fac(k) * Math.Pow(r, Bn) / (fac(r) * fac(k - r)); B = B + temp / ((double)(k + 1)); } sum = sum + Math.Pow(-4, i) * (1 - Math.Pow(4, i)) * B * Math.Pow(x, 2 * i - 1) / fac(2 * i); } // Print the value of expansion Console.Write(\"{0:F9}\", sum);} // Driver codepublic static void Main(String[] args){ int n = 6, x = 1; // Function call Tanx_expansion(n, x);}} // This code is contributed by 29AjayKumar", "e": 31873, "s": 30424, "text": null }, { "code": "<script> // JavaScript program to find tan(x) expansion // Function to find factorial of a numberfunction fac(num){ if (num == 0) return 1; // To store factorial of a number let fact = 1; for (let i = 1; i <= num; i++) fact = fact * i; // Return the factorial of a number return fact;} // Function to find tan(x) upto n termsfunction Tanx_expansion(terms, x){ // To store value of the expansion let sum = 0; for (let i = 1; i <= terms; i += 1) { // This loops here calculate Bernoulli number // which is further used to get the coefficient // in the expansion of tan x let B = 0; let Bn = 2 * i; for (let k = 0; k <= Bn; k++) { let temp = 0; for (let r = 0; r <= k; r++) temp = temp + Math.pow(-1, r) * fac(k) * Math.pow(r, Bn) / (fac(r) * fac(k - r)); B = B + temp / (k + 1); } sum =sum + Math.pow(-4, i) * (1 - Math.pow(4, i)) * B * Math.pow(x, 2 * i - 1) / fac(2 * i); } // Print the value of expansion document.write(sum.toFixed(10));} // Driver code let n = 6, x = 1; // Function call Tanx_expansion(n, x); // This code is contributed by Surbhi Tyagi. </script>", "e": 33172, "s": 31873, "text": null }, { "code": null, "e": 33184, "s": 33172, "text": "1.551373344" }, { "code": null, "e": 33196, "s": 33186, "text": "Rajput-Ji" }, { "code": null, "e": 33208, "s": 33196, "text": "29AjayKumar" }, { "code": null, "e": 33222, "s": 33208, "text": "surbhityagi15" }, { "code": null, "e": 33233, "s": 33222, "text": "series-sum" }, { "code": null, "e": 33246, "s": 33233, "text": "Mathematical" }, { "code": null, "e": 33259, "s": 33246, "text": "Mathematical" }, { "code": null, "e": 33357, "s": 33259, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33401, "s": 33357, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 33432, "s": 33401, "text": "Modular multiplicative inverse" }, { "code": null, "e": 33457, "s": 33432, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 33492, "s": 33457, "text": "Singular Value Decomposition (SVD)" }, { "code": null, "e": 33524, "s": 33492, "text": "Check if a number is Palindrome" }, { "code": null, "e": 33566, "s": 33524, "text": "Segment Tree | Set 1 (Sum of given range)" }, { "code": null, "e": 33630, "s": 33566, "text": "How to check if a given point lies inside or outside a polygon?" }, { "code": null, "e": 33663, "s": 33630, "text": "Program to multiply two matrices" }, { "code": null, "e": 33698, "s": 33663, "text": "Count ways to reach the n'th stair" } ]
Python - Itertools.accumulate() - GeeksforGeeks
31 Mar, 2020 Python itertools module is a collection of tools for handling iterators. According to the official documentation: “Module [that] implements a number of iterator building blocks inspired by constructs from APL, Haskell, and SML... Together, they form an ‘iterator algebra’ making it possible to construct specialized tools succinctly and efficiently in pure Python.” this basically means that the functions in itertools “operate” on iterators to produce more complex iterators. Simply put, iterators are data types that can be used in a for loop. The most common iterator in Python is the list. Let’s create a list of strings and named it colors. We can use a for loop to iterate the list like: colors = ['red', 'orange', 'yellow', 'green'] # Iterating Listfor each in colors: print(each) red orange yellow green There are many different kinds of iterables but for now, we will be using lists and sets. Requirements to work with itertools Must import the itertools module before using. We have to also import the operator module because we want to work with operators. import itertools import operator ## only needed if want to play with operators Itertools module is a collection of functions. We are going to explore one of these accumulate() function. Note: For more information, refer to Python Itertools This iterator takes two arguments, iterable target and the function which would be followed at each iteration of value in target. If no function is passed, addition takes place by default. If the input iterable is empty, the output iterable will also be empty. Syntaxitertools.accumulate(iterable[, func]) –> accumulate object This function makes an iterator that returns the results of a function. Parametersiterable & function Now its enough of the theory portion lets play with the code Code: 1 # import the itertool module # to work with itimport itertools # import operator to work # with operatorimport operator # creating a list GFGGFG = [1, 2, 3, 4, 5] # using the itertools.accumulate() result = itertools.accumulate(GFG, operator.mul) # printing each item from listfor each in result: print(each) 1 2 6 24 120 Explanation : The operator.mul takes two numbers and multiplies them. operator.mul(1, 2) 2 operator.mul(2, 3) 6 operator.mul(6, 4) 24 operator.mul(24, 5) 120 Now in the next example, we will use the max function as it takes a function as a parameter also. Code 2: # import the itertool module # to work with itimport itertools # import operator to work with# operatorimport operator # creating a list GFGGFG = [5, 3, 6, 2, 1, 9, 1] # using the itertools.accumulate() # Now here no need to import operator# as we are not using any operator# Try after removing it gives same resultresult = itertools.accumulate(GFG, max) # printing each item from listfor each in result: print(each) 5 5 6 6 6 9 9 Explanation: 5 max(5, 3) 5 max(5, 6) 6 max(6, 2) 6 max(6, 1) 6 max(6, 9) 9 max(9, 1) 9 Note: The passing function is optional as if you will not pass any function items will be summed i.e. added by default. itertools.accumulate(set.difference)This return accumulate of items of difference between sets. Code to explain # import the itertool module to# work with itimport itertools # creating a set GFG1 and GFG2GFG1 = { 5, 3, 6, 2, 1, 9 }GFG2 ={ 4, 2, 6, 0, 7 } # using the itertools.accumulate() # Now this will first give difference # and the give result by adding all # the element in result as by default# if no function passed it will add alwaysresult = itertools.accumulate(GFG2.difference(GFG1)) # printing each item from listfor each in result: print(each) 0 4 11 srisrinu Python-itertools Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Read a file line by line in Python Enumerate() in Python Iterate over a list in Python How to Install PIP on Windows ? Different ways to create Pandas Dataframe Python String | replace() Create a Pandas DataFrame from Lists Python program to convert a list to string Reading and Writing to text files in Python
[ { "code": null, "e": 24522, "s": 24494, "text": "\n31 Mar, 2020" }, { "code": null, "e": 24595, "s": 24522, "text": "Python itertools module is a collection of tools for handling iterators." }, { "code": null, "e": 24636, "s": 24595, "text": "According to the official documentation:" }, { "code": null, "e": 24999, "s": 24636, "text": "“Module [that] implements a number of iterator building blocks inspired by constructs from APL, Haskell, and SML... Together, they form an ‘iterator algebra’ making it possible to construct specialized tools succinctly and efficiently in pure Python.” this basically means that the functions in itertools “operate” on iterators to produce more complex iterators." }, { "code": null, "e": 25116, "s": 24999, "text": "Simply put, iterators are data types that can be used in a for loop. The most common iterator in Python is the list." }, { "code": null, "e": 25216, "s": 25116, "text": "Let’s create a list of strings and named it colors. We can use a for loop to iterate the list like:" }, { "code": "colors = ['red', 'orange', 'yellow', 'green'] # Iterating Listfor each in colors: print(each)", "e": 25314, "s": 25216, "text": null }, { "code": null, "e": 25339, "s": 25314, "text": "red\norange\nyellow\ngreen\n" }, { "code": null, "e": 25429, "s": 25339, "text": "There are many different kinds of iterables but for now, we will be using lists and sets." }, { "code": null, "e": 25465, "s": 25429, "text": "Requirements to work with itertools" }, { "code": null, "e": 25595, "s": 25465, "text": "Must import the itertools module before using. We have to also import the operator module because we want to work with operators." }, { "code": null, "e": 25674, "s": 25595, "text": "import itertools\nimport operator ## only needed if want to play with operators" }, { "code": null, "e": 25781, "s": 25674, "text": "Itertools module is a collection of functions. We are going to explore one of these accumulate() function." }, { "code": null, "e": 25835, "s": 25781, "text": "Note: For more information, refer to Python Itertools" }, { "code": null, "e": 26096, "s": 25835, "text": "This iterator takes two arguments, iterable target and the function which would be followed at each iteration of value in target. If no function is passed, addition takes place by default. If the input iterable is empty, the output iterable will also be empty." }, { "code": null, "e": 26162, "s": 26096, "text": "Syntaxitertools.accumulate(iterable[, func]) –> accumulate object" }, { "code": null, "e": 26234, "s": 26162, "text": "This function makes an iterator that returns the results of a function." }, { "code": null, "e": 26264, "s": 26234, "text": "Parametersiterable & function" }, { "code": null, "e": 26325, "s": 26264, "text": "Now its enough of the theory portion lets play with the code" }, { "code": null, "e": 26333, "s": 26325, "text": "Code: 1" }, { "code": "# import the itertool module # to work with itimport itertools # import operator to work # with operatorimport operator # creating a list GFGGFG = [1, 2, 3, 4, 5] # using the itertools.accumulate() result = itertools.accumulate(GFG, operator.mul) # printing each item from listfor each in result: print(each)", "e": 26679, "s": 26333, "text": null }, { "code": null, "e": 26693, "s": 26679, "text": "1\n2\n6\n24\n120\n" }, { "code": null, "e": 26707, "s": 26693, "text": "Explanation :" }, { "code": null, "e": 26763, "s": 26707, "text": "The operator.mul takes two numbers and multiplies them." }, { "code": null, "e": 26852, "s": 26763, "text": "operator.mul(1, 2)\n2\noperator.mul(2, 3)\n6\noperator.mul(6, 4)\n24\noperator.mul(24, 5)\n120\n" }, { "code": null, "e": 26950, "s": 26852, "text": "Now in the next example, we will use the max function as it takes a function as a parameter also." }, { "code": null, "e": 26958, "s": 26950, "text": "Code 2:" }, { "code": "# import the itertool module # to work with itimport itertools # import operator to work with# operatorimport operator # creating a list GFGGFG = [5, 3, 6, 2, 1, 9, 1] # using the itertools.accumulate() # Now here no need to import operator# as we are not using any operator# Try after removing it gives same resultresult = itertools.accumulate(GFG, max) # printing each item from listfor each in result: print(each)", "e": 27383, "s": 26958, "text": null }, { "code": null, "e": 27398, "s": 27383, "text": "5\n5\n6\n6\n6\n9\n9\n" }, { "code": null, "e": 27411, "s": 27398, "text": "Explanation:" }, { "code": null, "e": 27485, "s": 27411, "text": "5\nmax(5, 3)\n5\nmax(5, 6)\n6\nmax(6, 2)\n6\nmax(6, 1)\n6\nmax(6, 9)\n9\nmax(9, 1)\n9" }, { "code": null, "e": 27605, "s": 27485, "text": "Note: The passing function is optional as if you will not pass any function items will be summed i.e. added by default." }, { "code": null, "e": 27701, "s": 27605, "text": "itertools.accumulate(set.difference)This return accumulate of items of difference between sets." }, { "code": null, "e": 27717, "s": 27701, "text": "Code to explain" }, { "code": "# import the itertool module to# work with itimport itertools # creating a set GFG1 and GFG2GFG1 = { 5, 3, 6, 2, 1, 9 }GFG2 ={ 4, 2, 6, 0, 7 } # using the itertools.accumulate() # Now this will first give difference # and the give result by adding all # the element in result as by default# if no function passed it will add alwaysresult = itertools.accumulate(GFG2.difference(GFG1)) # printing each item from listfor each in result: print(each)", "e": 28173, "s": 27717, "text": null }, { "code": null, "e": 28181, "s": 28173, "text": "0\n4\n11\n" }, { "code": null, "e": 28190, "s": 28181, "text": "srisrinu" }, { "code": null, "e": 28207, "s": 28190, "text": "Python-itertools" }, { "code": null, "e": 28214, "s": 28207, "text": "Python" }, { "code": null, "e": 28312, "s": 28214, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28321, "s": 28312, "text": "Comments" }, { "code": null, "e": 28334, "s": 28321, "text": "Old Comments" }, { "code": null, "e": 28352, "s": 28334, "text": "Python Dictionary" }, { "code": null, "e": 28387, "s": 28352, "text": "Read a file line by line in Python" }, { "code": null, "e": 28409, "s": 28387, "text": "Enumerate() in Python" }, { "code": null, "e": 28439, "s": 28409, "text": "Iterate over a list in Python" }, { "code": null, "e": 28471, "s": 28439, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28513, "s": 28471, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28539, "s": 28513, "text": "Python String | replace()" }, { "code": null, "e": 28576, "s": 28539, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 28619, "s": 28576, "text": "Python program to convert a list to string" } ]
Firebase - Detaching Callbacks
This chapter will show you how to detach callbacks in Firebase. Let us say we want to detach a callback for a function with value event type. var playersRef = firebase.database().ref("players/"); ref.on("value", function(data) { console.log(data.val()); }, function (error) { console.log("Error: " + error.code); }); We need to use off() method. This will remove all callbacks with value event type. playersRef.off("value"); When we want to detach all callbacks, we can use − playersRef.off(); 60 Lectures 5 hours University Code 28 Lectures 2.5 hours Appeteria 85 Lectures 14.5 hours Appeteria 46 Lectures 2.5 hours Gautham Vijayan 13 Lectures 1.5 hours Nishant Kumar 85 Lectures 16.5 hours Rahul Agarwal Print Add Notes Bookmark this page
[ { "code": null, "e": 2230, "s": 2166, "text": "This chapter will show you how to detach callbacks in Firebase." }, { "code": null, "e": 2308, "s": 2230, "text": "Let us say we want to detach a callback for a function with value event type." }, { "code": null, "e": 2490, "s": 2308, "text": "var playersRef = firebase.database().ref(\"players/\");\n\nref.on(\"value\", function(data) {\n console.log(data.val());\n}, function (error) {\n console.log(\"Error: \" + error.code);\n});" }, { "code": null, "e": 2573, "s": 2490, "text": "We need to use off() method. This will remove all callbacks with value event type." }, { "code": null, "e": 2599, "s": 2573, "text": "playersRef.off(\"value\");\n" }, { "code": null, "e": 2650, "s": 2599, "text": "When we want to detach all callbacks, we can use −" }, { "code": null, "e": 2669, "s": 2650, "text": "playersRef.off();\n" }, { "code": null, "e": 2702, "s": 2669, "text": "\n 60 Lectures \n 5 hours \n" }, { "code": null, "e": 2719, "s": 2702, "text": " University Code" }, { "code": null, "e": 2754, "s": 2719, "text": "\n 28 Lectures \n 2.5 hours \n" }, { "code": null, "e": 2765, "s": 2754, "text": " Appeteria" }, { "code": null, "e": 2801, "s": 2765, "text": "\n 85 Lectures \n 14.5 hours \n" }, { "code": null, "e": 2812, "s": 2801, "text": " Appeteria" }, { "code": null, "e": 2847, "s": 2812, "text": "\n 46 Lectures \n 2.5 hours \n" }, { "code": null, "e": 2864, "s": 2847, "text": " Gautham Vijayan" }, { "code": null, "e": 2899, "s": 2864, "text": "\n 13 Lectures \n 1.5 hours \n" }, { "code": null, "e": 2914, "s": 2899, "text": " Nishant Kumar" }, { "code": null, "e": 2950, "s": 2914, "text": "\n 85 Lectures \n 16.5 hours \n" }, { "code": null, "e": 2965, "s": 2950, "text": " Rahul Agarwal" }, { "code": null, "e": 2972, "s": 2965, "text": " Print" }, { "code": null, "e": 2983, "s": 2972, "text": " Add Notes" } ]
Create a QR code generator app using ReactJS - GeeksforGeeks
27 Aug, 2021 Introduction: In this article, we are going to make a simple QR Code generator app. QR code is a two-dimensional barcode readable on smartphones. Allows coding of more than 4000 characters in a double-barcode bar. QR codes can be used to show text to a user, to open a URL, to keep contact in an address book or to write messages. Prerequisites: The pre-requisites for this project are: React Functional Components React Hooks Javascript ES6 Approach: Our app contains two sections. In one section we will take the user inputs such as the text to encode, size of QR code, background color of QR code, and store all of that inside state variables. After that, we will build the required API string to fetch the QR code image. In the other section, we will display the required QR code Creating a React application: Step 1: Create a react application by typing the following command in the terminal. npx create-react-app qrcode-gen Step 2: Now, go to the project folder i.e qrcode.gen by running the following command. cd qrcode-gen Project Structure: It will look like the following. Example: Here App.js is the only default component of our app that contains all the logic. We will be using a free opensource (no auth requires) API called ‘create-qr-code’ to fetch the required QR code image. We will also have a button to download the QR code image. Now write down the following code in the App.js file. Javascript import { useEffect, useState } from 'react';import './App.css'; function App() { const [temp, setTemp] = useState(""); const [word, setWord] = useState(""); const [size, setSize] = useState(400); const [bgColor, setBgColor] = useState("ffffff"); const [qrCode, setQrCode] = useState(""); // Changing the URL only when the user // changes the input useEffect(() => { setQrCode (`http://api.qrserver.com/v1/create-qr-code/?data=${word}!&size=${size}x${size}&bgcolor=${bgColor}`); }, [word, size, bgColor]); // Updating the input word when user // click on the generate button function handleClick() { setWord(temp); } return ( <div className="App"> <h1>QR Code Generator</h1> <div className="input-box"> <div className="gen"> <input type="text" onChange={ (e) => {setTemp(e.target.value)}} placeholder="Enter text to encode" /> <button className="button" onClick={handleClick}> Generate </button> </div> <div className="extra"> <h5>Background Color:</h5> <input type="color" onChange={(e) => { setBgColor(e.target.value.substring(1)) }} /> <h5>Dimension:</h5> <input type="range" min="200" max="600" value={size} onChange={(e) => {setSize(e.target.value)}} /> </div> </div> <div className="output-box"> <img src={qrCode} alt="" /> <a href={qrCode} download="QRCode"> <button type="button">Download</button> </a> </div> </div> );} export default App; Now, let’s edit the file named App.css to design our app. CSS @import url('http://fonts.cdnfonts.com/css/lilly');.App{ display: flex; flex-direction: column; justify-content: center; align-items: center; gap: 50px; padding-top: 30px;}h1{ font-family: 'Lilly', sans-serif; font-size: 50px;}.gen input{ height: 35px; width: 250px; font-size: 20px; padding-left: 5px;}button{ position: relative; height: 38px; width: 100px; top: -2px; font-size: 18px; border: none; color: whitesmoke; background-color: forestgreen; box-shadow: 2px 2px 5px rgb(74, 182, 74); cursor: pointer;}button:active{ box-shadow: none;}.extra{ padding-top: 20px; display: flex; justify-content: space-around; gap: 10px;}.output-box{ display: flex; flex-direction: column; align-items: center; gap: 40px;} Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: React-Questions JavaScript ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request JavaScript | Promises How to filter object array based on attributes? How to fetch data from an API in ReactJS ? How to redirect to another page in ReactJS ? How to pass data from child component to its parent in ReactJS ? How to pass data from one component to other component in ReactJS ? ReactJS Functional Components
[ { "code": null, "e": 26667, "s": 26639, "text": "\n27 Aug, 2021" }, { "code": null, "e": 26998, "s": 26667, "text": "Introduction: In this article, we are going to make a simple QR Code generator app. QR code is a two-dimensional barcode readable on smartphones. Allows coding of more than 4000 characters in a double-barcode bar. QR codes can be used to show text to a user, to open a URL, to keep contact in an address book or to write messages." }, { "code": null, "e": 27054, "s": 26998, "text": "Prerequisites: The pre-requisites for this project are:" }, { "code": null, "e": 27060, "s": 27054, "text": "React" }, { "code": null, "e": 27082, "s": 27060, "text": "Functional Components" }, { "code": null, "e": 27094, "s": 27082, "text": "React Hooks" }, { "code": null, "e": 27109, "s": 27094, "text": "Javascript ES6" }, { "code": null, "e": 27452, "s": 27109, "text": "Approach: Our app contains two sections. In one section we will take the user inputs such as the text to encode, size of QR code, background color of QR code, and store all of that inside state variables. After that, we will build the required API string to fetch the QR code image. In the other section, we will display the required QR code " }, { "code": null, "e": 27484, "s": 27454, "text": "Creating a React application:" }, { "code": null, "e": 27568, "s": 27484, "text": "Step 1: Create a react application by typing the following command in the terminal." }, { "code": null, "e": 27600, "s": 27568, "text": "npx create-react-app qrcode-gen" }, { "code": null, "e": 27687, "s": 27600, "text": "Step 2: Now, go to the project folder i.e qrcode.gen by running the following command." }, { "code": null, "e": 27701, "s": 27687, "text": "cd qrcode-gen" }, { "code": null, "e": 27753, "s": 27701, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 28022, "s": 27753, "text": "Example: Here App.js is the only default component of our app that contains all the logic. We will be using a free opensource (no auth requires) API called ‘create-qr-code’ to fetch the required QR code image. We will also have a button to download the QR code image. " }, { "code": null, "e": 28076, "s": 28022, "text": "Now write down the following code in the App.js file." }, { "code": null, "e": 28087, "s": 28076, "text": "Javascript" }, { "code": "import { useEffect, useState } from 'react';import './App.css'; function App() { const [temp, setTemp] = useState(\"\"); const [word, setWord] = useState(\"\"); const [size, setSize] = useState(400); const [bgColor, setBgColor] = useState(\"ffffff\"); const [qrCode, setQrCode] = useState(\"\"); // Changing the URL only when the user // changes the input useEffect(() => { setQrCode (`http://api.qrserver.com/v1/create-qr-code/?data=${word}!&size=${size}x${size}&bgcolor=${bgColor}`); }, [word, size, bgColor]); // Updating the input word when user // click on the generate button function handleClick() { setWord(temp); } return ( <div className=\"App\"> <h1>QR Code Generator</h1> <div className=\"input-box\"> <div className=\"gen\"> <input type=\"text\" onChange={ (e) => {setTemp(e.target.value)}} placeholder=\"Enter text to encode\" /> <button className=\"button\" onClick={handleClick}> Generate </button> </div> <div className=\"extra\"> <h5>Background Color:</h5> <input type=\"color\" onChange={(e) => { setBgColor(e.target.value.substring(1)) }} /> <h5>Dimension:</h5> <input type=\"range\" min=\"200\" max=\"600\" value={size} onChange={(e) => {setSize(e.target.value)}} /> </div> </div> <div className=\"output-box\"> <img src={qrCode} alt=\"\" /> <a href={qrCode} download=\"QRCode\"> <button type=\"button\">Download</button> </a> </div> </div> );} export default App;", "e": 29692, "s": 28087, "text": null }, { "code": null, "e": 29750, "s": 29692, "text": "Now, let’s edit the file named App.css to design our app." }, { "code": null, "e": 29754, "s": 29750, "text": "CSS" }, { "code": "@import url('http://fonts.cdnfonts.com/css/lilly');.App{ display: flex; flex-direction: column; justify-content: center; align-items: center; gap: 50px; padding-top: 30px;}h1{ font-family: 'Lilly', sans-serif; font-size: 50px;}.gen input{ height: 35px; width: 250px; font-size: 20px; padding-left: 5px;}button{ position: relative; height: 38px; width: 100px; top: -2px; font-size: 18px; border: none; color: whitesmoke; background-color: forestgreen; box-shadow: 2px 2px 5px rgb(74, 182, 74); cursor: pointer;}button:active{ box-shadow: none;}.extra{ padding-top: 20px; display: flex; justify-content: space-around; gap: 10px;}.output-box{ display: flex; flex-direction: column; align-items: center; gap: 40px;}", "e": 30497, "s": 29754, "text": null }, { "code": null, "e": 30610, "s": 30497, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 30620, "s": 30610, "text": "npm start" }, { "code": null, "e": 30719, "s": 30620, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 30735, "s": 30719, "text": "React-Questions" }, { "code": null, "e": 30746, "s": 30735, "text": "JavaScript" }, { "code": null, "e": 30754, "s": 30746, "text": "ReactJS" }, { "code": null, "e": 30771, "s": 30754, "text": "Web Technologies" }, { "code": null, "e": 30869, "s": 30771, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30909, "s": 30869, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 30970, "s": 30909, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 31011, "s": 30970, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 31033, "s": 31011, "text": "JavaScript | Promises" }, { "code": null, "e": 31081, "s": 31033, "text": "How to filter object array based on attributes?" }, { "code": null, "e": 31124, "s": 31081, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 31169, "s": 31124, "text": "How to redirect to another page in ReactJS ?" }, { "code": null, "e": 31234, "s": 31169, "text": "How to pass data from child component to its parent in ReactJS ?" }, { "code": null, "e": 31302, "s": 31234, "text": "How to pass data from one component to other component in ReactJS ?" } ]
C# | Char.IsSymbol() Method - GeeksforGeeks
31 Jan, 2019 In C#, Char.IsSymbol() is a System.Char struct method which is used to check whether a Unicode character is a valid symbol defined under UnicodeCategory as MathSymbol, CurrencySymbol, ModifierSymbol, or OtherSymbol or not. This method can be overloaded by passing different types and number of arguments to it. Char.IsSymbol(Char) MethodChar.IsSymbol(String, Int32) Method Char.IsSymbol(Char) Method Char.IsSymbol(String, Int32) Method This method is used to check whether a specified Unicode character matches with any valid symbol in UnicodeCategory or not. If it matches then it returns True otherwise return False. Syntax: public static bool IsSymbol(char ch); Parameter: ch: It is required unicode character of System.char type which is to be checked for a valid symbol. Return Type: The method returns True if the specified Unicode character is a valid symbol, otherwise returns False. The return type of this method is System.Boolean. Example: // C# program to illustrate the// Char.IsSymbol(Char) Methodusing System; class GFG { // Main Method static public void Main() { // Declaration of data type bool result; // checking if plus sign // is symbol or not char ch1 = '+'; result = Char.IsSymbol(ch1); Console.WriteLine(result); // checking if dollar sign // is symbol or not char ch2 = '$'; result = Char.IsSymbol(ch2); Console.WriteLine(result); // checking if @ // is symbol or not char ch3 = '@'; result = Char.IsSymbol(ch3); Console.WriteLine(result); }} True True False This method is used to check whether a character in the specified string at the specified position is a valid symbol or not. If it is a symbol according to the Unicode standard then it returns True otherwise returns False. Syntax: public static bool IsSymbol(string str, int index); Parameters: Str: It is the required string of System.Stringtype whose character is to be checked.index: It is the position of character in specified string. Type of this parameter is System.Int32. Return Type: The method returns True if the character at specified index in the specified string is a valid symbol according to the Unicode standard, otherwise returns False. The return type of this method is System.Boolean. Example: // C# program to illustrate the// Char.IsSymbol(String, Int32) Methodusing System; class GFG { // Main Method static public void Main() { // Declaration of data type bool result; // checking for symbol in // a string string str1 = "www.GeeksforGeeks.org"; result = Char.IsSymbol(str1, 3); Console.WriteLine(result); // checking for symbol in // a string string str2 = "geeks+"; result = Char.IsSymbol(str2, 5); Console.WriteLine(result); }} False True Reference: https://docs.microsoft.com/en-us/dotnet/api/system.char.issymbol?view=netframework-4.7.2 CSharp-Char-Struct CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between Abstract Class and Interface in C# C# | How to check whether a List contains a specified element C# | IsNullOrEmpty() Method String.Split() Method in C# with Examples C# | Arrays of Strings C# Dictionary with examples C# | Method Overriding Destructors in C# Difference between Ref and Out keywords in C# C# | Delegates
[ { "code": null, "e": 23726, "s": 23698, "text": "\n31 Jan, 2019" }, { "code": null, "e": 24037, "s": 23726, "text": "In C#, Char.IsSymbol() is a System.Char struct method which is used to check whether a Unicode character is a valid symbol defined under UnicodeCategory as MathSymbol, CurrencySymbol, ModifierSymbol, or OtherSymbol or not. This method can be overloaded by passing different types and number of arguments to it." }, { "code": null, "e": 24099, "s": 24037, "text": "Char.IsSymbol(Char) MethodChar.IsSymbol(String, Int32) Method" }, { "code": null, "e": 24126, "s": 24099, "text": "Char.IsSymbol(Char) Method" }, { "code": null, "e": 24162, "s": 24126, "text": "Char.IsSymbol(String, Int32) Method" }, { "code": null, "e": 24345, "s": 24162, "text": "This method is used to check whether a specified Unicode character matches with any valid symbol in UnicodeCategory or not. If it matches then it returns True otherwise return False." }, { "code": null, "e": 24353, "s": 24345, "text": "Syntax:" }, { "code": null, "e": 24392, "s": 24353, "text": "public static bool IsSymbol(char ch);\n" }, { "code": null, "e": 24403, "s": 24392, "text": "Parameter:" }, { "code": null, "e": 24503, "s": 24403, "text": "ch: It is required unicode character of System.char type which is to be checked for a valid symbol." }, { "code": null, "e": 24669, "s": 24503, "text": "Return Type: The method returns True if the specified Unicode character is a valid symbol, otherwise returns False. The return type of this method is System.Boolean." }, { "code": null, "e": 24678, "s": 24669, "text": "Example:" }, { "code": "// C# program to illustrate the// Char.IsSymbol(Char) Methodusing System; class GFG { // Main Method static public void Main() { // Declaration of data type bool result; // checking if plus sign // is symbol or not char ch1 = '+'; result = Char.IsSymbol(ch1); Console.WriteLine(result); // checking if dollar sign // is symbol or not char ch2 = '$'; result = Char.IsSymbol(ch2); Console.WriteLine(result); // checking if @ // is symbol or not char ch3 = '@'; result = Char.IsSymbol(ch3); Console.WriteLine(result); }}", "e": 25344, "s": 24678, "text": null }, { "code": null, "e": 25361, "s": 25344, "text": "True\nTrue\nFalse\n" }, { "code": null, "e": 25584, "s": 25361, "text": "This method is used to check whether a character in the specified string at the specified position is a valid symbol or not. If it is a symbol according to the Unicode standard then it returns True otherwise returns False." }, { "code": null, "e": 25592, "s": 25584, "text": "Syntax:" }, { "code": null, "e": 25645, "s": 25592, "text": "public static bool IsSymbol(string str, int index);\n" }, { "code": null, "e": 25657, "s": 25645, "text": "Parameters:" }, { "code": null, "e": 25842, "s": 25657, "text": "Str: It is the required string of System.Stringtype whose character is to be checked.index: It is the position of character in specified string. Type of this parameter is System.Int32." }, { "code": null, "e": 26067, "s": 25842, "text": "Return Type: The method returns True if the character at specified index in the specified string is a valid symbol according to the Unicode standard, otherwise returns False. The return type of this method is System.Boolean." }, { "code": null, "e": 26076, "s": 26067, "text": "Example:" }, { "code": "// C# program to illustrate the// Char.IsSymbol(String, Int32) Methodusing System; class GFG { // Main Method static public void Main() { // Declaration of data type bool result; // checking for symbol in // a string string str1 = \"www.GeeksforGeeks.org\"; result = Char.IsSymbol(str1, 3); Console.WriteLine(result); // checking for symbol in // a string string str2 = \"geeks+\"; result = Char.IsSymbol(str2, 5); Console.WriteLine(result); }}", "e": 26622, "s": 26076, "text": null }, { "code": null, "e": 26634, "s": 26622, "text": "False\nTrue\n" }, { "code": null, "e": 26734, "s": 26634, "text": "Reference: https://docs.microsoft.com/en-us/dotnet/api/system.char.issymbol?view=netframework-4.7.2" }, { "code": null, "e": 26753, "s": 26734, "text": "CSharp-Char-Struct" }, { "code": null, "e": 26767, "s": 26753, "text": "CSharp-method" }, { "code": null, "e": 26770, "s": 26767, "text": "C#" }, { "code": null, "e": 26868, "s": 26770, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26922, "s": 26868, "text": "Difference between Abstract Class and Interface in C#" }, { "code": null, "e": 26984, "s": 26922, "text": "C# | How to check whether a List contains a specified element" }, { "code": null, "e": 27012, "s": 26984, "text": "C# | IsNullOrEmpty() Method" }, { "code": null, "e": 27054, "s": 27012, "text": "String.Split() Method in C# with Examples" }, { "code": null, "e": 27077, "s": 27054, "text": "C# | Arrays of Strings" }, { "code": null, "e": 27105, "s": 27077, "text": "C# Dictionary with examples" }, { "code": null, "e": 27128, "s": 27105, "text": "C# | Method Overriding" }, { "code": null, "e": 27146, "s": 27128, "text": "Destructors in C#" }, { "code": null, "e": 27192, "s": 27146, "text": "Difference between Ref and Out keywords in C#" } ]
How to remove underscore from column names of an R data frame?
When we import data from outside sources then the header or column names might be imported with underscore separated values and this is also possible if the original data has the same format. Therefore, to make the headers shorter and look better we would prefer to remove the underscore sign and this can be easily done with the help of gsub function. Consider the below data frame − Live Demo x_1<-sample(1:10,20,replace=TRUE) x_2<-sample(1:10,20,replace=TRUE) x_3<-sample(1:10,20,replace=TRUE) x_4<-sample(1:10,20,replace=TRUE) x_5<-sample(1:10,20,replace=TRUE) df1<-data.frame(x_1,x_2,x_3,x_4,x_5) df1 x_1 x_2 x_3 x_4 x_5 1 10 4 6 5 10 2 6 10 2 1 4 3 9 9 6 1 4 4 6 1 5 5 8 5 7 7 4 7 4 6 1 5 2 1 8 7 8 5 5 2 9 8 8 4 1 9 8 9 8 1 7 4 3 10 5 9 3 10 3 11 2 7 5 6 9 12 10 1 4 1 5 13 8 10 10 1 2 14 3 10 5 7 6 15 5 6 9 1 10 16 3 8 6 4 7 17 8 9 5 7 2 18 6 10 5 6 8 19 1 8 3 2 9 20 8 1 5 10 5 Removing underscore from column names − names(df1)<-gsub("\\_","",names(df1)) df1 x1 x2 x3 x4 x5 1 6 8 2 9 6 2 1 9 3 4 10 3 2 1 8 10 10 4 4 10 3 6 1 5 10 6 6 6 5 6 9 4 6 6 2 7 3 9 10 5 9 8 8 1 5 3 8 9 4 9 2 5 6 10 9 3 3 5 4 11 7 1 4 6 3 12 10 6 3 3 1 13 7 6 10 10 8 14 9 6 4 1 1 15 7 5 10 2 1 16 1 3 7 4 8 17 2 1 7 2 8 18 1 10 8 2 3 19 8 7 6 6 10 20 3 8 9 8 3 Let’s have a look at another example − Live Demo y_1<-rnorm(20) y_2<-rnorm(20,2,1) y_3<-rnorm(20,2,0.5) y_4<-rnorm(20,2,0.0003) y_5<-rnorm(20,10,1) df2<-data.frame(y_1,y_2,y_3,y_4,y_5) df2 y_1 y_2 y_3 y_4 y_5 1 0.514450792 2.4374182 3.230083 1.999826 12.625661 2 -0.312792686 0.8350701 2.769788 1.999740 8.699441 3 -0.710758168 2.7832089 1.971917 2.000519 8.430542 4 -0.060647019 1.4626953 1.971298 2.000600 9.568890 5 2.363567996 0.8239008 2.626454 2.000266 10.038633 6 1.227010669 2.6716199 1.844929 1.999768 7.838243 7 -0.994717233 1.1798125 2.084188 1.999643 11.254072 8 2.584374114 1.6053897 2.453163 2.000089 11.256447 9 0.863363636 1.0685646 1.457286 2.000659 11.001834 10 -0.190736476 1.4468239 1.829696 2.000229 10.425032 11 0.716178594 2.7498080 2.406190 1.999487 9.906237 12 -1.670744103 1.1184815 2.206973 2.000288 8.993506 13 1.011970392 2.7794836 2.560877 2.000160 12.564313 14 -0.099591556 1.5176429 1.841669 2.000175 12.050816 15 3.230713917 1.8450534 2.065576 2.000189 9.243683 16 0.734370382 0.8649671 1.550325 2.000698 10.320533 17 1.156661539 3.8099910 2.842250 1.999826 10.134682 18 -0.496844480 2.0082680 1.456640 2.000119 10.498172 19 -0.001995988 1.7054230 2.702496 1.999963 8.572382 20 -0.190562902 2.6200714 1.822893 1.999612 9.683227 Removing underscore from column names − names(df2)<-gsub("\\_","",names(df2)) df2 y1 y2 y3 y4 y5 1 0.35283126 2.7403674 1.5855939 1.999599 10.615962 2 2.04048363 1.7570445 1.9365559 1.999934 10.734033 3 -0.99194313 1.9299296 3.4318183 2.000200 8.821012 4 0.03923376 2.8984508 1.3765896 1.999948 8.371278 5 0.48921437 1.7272755 2.0049735 1.999814 10.769563 6 -1.52296501 1.1843431 1.3387394 1.999670 10.984169 7 -0.43659539 3.0847073 2.0724138 2.000099 10.163438 8 -1.07562516 2.4046583 2.3631921 1.999976 8.119308 9 0.25897051 4.0599361 2.5180669 2.000179 8.780155 10 0.90011031 0.5844179 3.0924616 2.000156 10.945022 11 -1.01455924 1.3601391 1.3491111 2.000197 11.172243 12 -1.21902395 1.5613617 1.6721161 2.000014 9.752595 13 1.10335026 3.0485505 2.5479672 2.000200 10.851384 14 1.66150031 0.9157312 2.0733168 2.000298 10.045139 15 -2.88733135 1.6426962 1.4906487 1.999932 10.596103 16 -0.20689147 1.7962494 0.9636048 1.999893 10.489436 17 -0.66668766 2.0058826 1.7932363 2.000102 10.702172 18 -0.32072057 2.8834813 2.1764040 2.000017 10.699573 19 -0.29862766 4.6416591 2.8638125 1.999819 10.211451 20 -0.47632229 1.2781510 2.8128627 1.999981 9.046588
[ { "code": null, "e": 1415, "s": 1062, "text": "When we import data from outside sources then the header or column names might be imported with underscore separated values and this is also possible if the original data has the same format. Therefore, to make the headers shorter and look better we would prefer to remove the underscore sign and this can be easily done with the help of gsub function." }, { "code": null, "e": 1447, "s": 1415, "text": "Consider the below data frame −" }, { "code": null, "e": 1458, "s": 1447, "text": " Live Demo" }, { "code": null, "e": 1669, "s": 1458, "text": "x_1<-sample(1:10,20,replace=TRUE)\nx_2<-sample(1:10,20,replace=TRUE)\nx_3<-sample(1:10,20,replace=TRUE)\nx_4<-sample(1:10,20,replace=TRUE)\nx_5<-sample(1:10,20,replace=TRUE)\ndf1<-data.frame(x_1,x_2,x_3,x_4,x_5)\ndf1" }, { "code": null, "e": 1951, "s": 1669, "text": "x_1 x_2 x_3 x_4 x_5\n1 10 4 6 5 10\n2 6 10 2 1 4\n3 9 9 6 1 4\n4 6 1 5 5 8\n5 7 7 4 7 4\n6 1 5 2 1 8\n7 8 5 5 2 9\n8 8 4 1 9 8\n9 8 1 7 4 3\n10 5 9 3 10 3\n11 2 7 5 6 9\n12 10 1 4 1 5\n13 8 10 10 1 2\n14 3 10 5 7 6\n15 5 6 9 1 10\n16 3 8 6 4 7\n17 8 9 5 7 2\n18 6 10 5 6 8\n19 1 8 3 2 9\n20 8 1 5 10 5" }, { "code": null, "e": 1991, "s": 1951, "text": "Removing underscore from column names −" }, { "code": null, "e": 2033, "s": 1991, "text": "names(df1)<-gsub(\"\\\\_\",\"\",names(df1))\ndf1" }, { "code": null, "e": 2313, "s": 2033, "text": " x1 x2 x3 x4 x5\n1 6 8 2 9 6\n2 1 9 3 4 10\n3 2 1 8 10 10\n4 4 10 3 6 1\n5 10 6 6 6 5\n6 9 4 6 6 2\n7 3 9 10 5 9\n8 8 1 5 3 8\n9 4 9 2 5 6\n10 9 3 3 5 4\n11 7 1 4 6 3\n12 10 6 3 3 1\n13 7 6 10 10 8\n14 9 6 4 1 1\n15 7 5 10 2 1\n16 1 3 7 4 8\n17 2 1 7 2 8\n18 1 10 8 2 3\n19 8 7 6 6 10\n20 3 8 9 8 3" }, { "code": null, "e": 2352, "s": 2313, "text": "Let’s have a look at another example −" }, { "code": null, "e": 2363, "s": 2352, "text": " Live Demo" }, { "code": null, "e": 2503, "s": 2363, "text": "y_1<-rnorm(20)\ny_2<-rnorm(20,2,1)\ny_3<-rnorm(20,2,0.5)\ny_4<-rnorm(20,2,0.0003)\ny_5<-rnorm(20,10,1)\ndf2<-data.frame(y_1,y_2,y_3,y_4,y_5)\ndf2" }, { "code": null, "e": 3640, "s": 2503, "text": " y_1 y_2 y_3 y_4 y_5\n1 0.514450792 2.4374182 3.230083 1.999826 12.625661\n2 -0.312792686 0.8350701 2.769788 1.999740 8.699441\n3 -0.710758168 2.7832089 1.971917 2.000519 8.430542\n4 -0.060647019 1.4626953 1.971298 2.000600 9.568890\n5 2.363567996 0.8239008 2.626454 2.000266 10.038633\n6 1.227010669 2.6716199 1.844929 1.999768 7.838243\n7 -0.994717233 1.1798125 2.084188 1.999643 11.254072\n8 2.584374114 1.6053897 2.453163 2.000089 11.256447\n9 0.863363636 1.0685646 1.457286 2.000659 11.001834\n10 -0.190736476 1.4468239 1.829696 2.000229 10.425032\n11 0.716178594 2.7498080 2.406190 1.999487 9.906237\n12 -1.670744103 1.1184815 2.206973 2.000288 8.993506\n13 1.011970392 2.7794836 2.560877 2.000160 12.564313\n14 -0.099591556 1.5176429 1.841669 2.000175 12.050816\n15 3.230713917 1.8450534 2.065576 2.000189 9.243683\n16 0.734370382 0.8649671 1.550325 2.000698 10.320533\n17 1.156661539 3.8099910 2.842250 1.999826 10.134682\n18 -0.496844480 2.0082680 1.456640 2.000119 10.498172\n19 -0.001995988 1.7054230 2.702496 1.999963 8.572382\n20 -0.190562902 2.6200714 1.822893 1.999612 9.683227" }, { "code": null, "e": 3680, "s": 3640, "text": "Removing underscore from column names −" }, { "code": null, "e": 3722, "s": 3680, "text": "names(df2)<-gsub(\"\\\\_\",\"\",names(df2))\ndf2" }, { "code": null, "e": 4800, "s": 3722, "text": " y1 y2 y3 y4 y5\n1 0.35283126 2.7403674 1.5855939 1.999599 10.615962\n2 2.04048363 1.7570445 1.9365559 1.999934 10.734033\n3 -0.99194313 1.9299296 3.4318183 2.000200 8.821012\n4 0.03923376 2.8984508 1.3765896 1.999948 8.371278\n5 0.48921437 1.7272755 2.0049735 1.999814 10.769563\n6 -1.52296501 1.1843431 1.3387394 1.999670 10.984169\n7 -0.43659539 3.0847073 2.0724138 2.000099 10.163438\n8 -1.07562516 2.4046583 2.3631921 1.999976 8.119308\n9 0.25897051 4.0599361 2.5180669 2.000179 8.780155\n10 0.90011031 0.5844179 3.0924616 2.000156 10.945022\n11 -1.01455924 1.3601391 1.3491111 2.000197 11.172243\n12 -1.21902395 1.5613617 1.6721161 2.000014 9.752595\n13 1.10335026 3.0485505 2.5479672 2.000200 10.851384\n14 1.66150031 0.9157312 2.0733168 2.000298 10.045139\n15 -2.88733135 1.6426962 1.4906487 1.999932 10.596103\n 16 -0.20689147 1.7962494 0.9636048 1.999893 10.489436\n 17 -0.66668766 2.0058826 1.7932363 2.000102 10.702172\n18 -0.32072057 2.8834813 2.1764040 2.000017 10.699573\n19 -0.29862766 4.6416591 2.8638125 1.999819 10.211451\n20 -0.47632229 1.2781510 2.8128627 1.999981 9.046588" } ]
Math.Pow() Method in C#
The Math.Pow() method in C# is used to compute a number raised to the power of some other number. Following is the syntax − public static double Pow(double val1, double val2) Above, val1 is a double-precision floating-point number to be raised to a power., whereas val2 is a double-precision floating-point number that specifies a power. Let us now see an example to implement Math.Pow() method − using System; public class Demo { public static void Main(){ double res; res = Math.Pow(5, 0); Console.WriteLine("Math.Pow(5,0) = "+res); res = Math.Pow(0,5); Console.WriteLine("Math.Pow(0,5) = "+res); } } This will produce the following output − Math.Pow(5,0) = 1 Math.Pow(0,5) = 0 Let us see another example to implement Math.Pow() method − using System; public class Demo { public static void Main(){ int val1 = 10, val2 = 15; float val3 = 12.8f, val4 = 25.6f; double res = Math.Pow(3, 2); Console.WriteLine("Minimum Value from two int values = "+Math.Min(val1, val2)); Console.WriteLine("Minimum Value from two float values = "+Math.Min(val3, val4)); Console.WriteLine("Math.Pow(3,2) = "+res); } } This will produce the following output − Minimum Value from two int values = 10 Minimum Value from two float values = 12.8 Math.Pow(3,2) = 9
[ { "code": null, "e": 1160, "s": 1062, "text": "The Math.Pow() method in C# is used to compute a number raised to the power of some other number." }, { "code": null, "e": 1186, "s": 1160, "text": "Following is the syntax −" }, { "code": null, "e": 1237, "s": 1186, "text": "public static double Pow(double val1, double val2)" }, { "code": null, "e": 1400, "s": 1237, "text": "Above, val1 is a double-precision floating-point number to be raised to a power., whereas val2 is a double-precision floating-point number that specifies a power." }, { "code": null, "e": 1459, "s": 1400, "text": "Let us now see an example to implement Math.Pow() method −" }, { "code": null, "e": 1701, "s": 1459, "text": "using System;\npublic class Demo {\n public static void Main(){\n double res;\n res = Math.Pow(5, 0);\n Console.WriteLine(\"Math.Pow(5,0) = \"+res);\n res = Math.Pow(0,5);\n Console.WriteLine(\"Math.Pow(0,5) = \"+res);\n }\n}" }, { "code": null, "e": 1742, "s": 1701, "text": "This will produce the following output −" }, { "code": null, "e": 1778, "s": 1742, "text": "Math.Pow(5,0) = 1\nMath.Pow(0,5) = 0" }, { "code": null, "e": 1838, "s": 1778, "text": "Let us see another example to implement Math.Pow() method −" }, { "code": null, "e": 2239, "s": 1838, "text": "using System;\npublic class Demo {\n public static void Main(){\n int val1 = 10, val2 = 15;\n float val3 = 12.8f, val4 = 25.6f;\n double res = Math.Pow(3, 2);\n Console.WriteLine(\"Minimum Value from two int values = \"+Math.Min(val1, val2));\n Console.WriteLine(\"Minimum Value from two float values = \"+Math.Min(val3, val4));\n Console.WriteLine(\"Math.Pow(3,2) = \"+res);\n }\n}" }, { "code": null, "e": 2280, "s": 2239, "text": "This will produce the following output −" }, { "code": null, "e": 2380, "s": 2280, "text": "Minimum Value from two int values = 10\nMinimum Value from two float values = 12.8\nMath.Pow(3,2) = 9" } ]
Robot Return to Origin in C++
Suppose there is a robot and its starting position is (0, 0). If we have a sequence of its movements, we have to check whether this robot ends up at (0, 0) after it completes its moves. The move sequence is given as a string, and the character moves[i] represents its ith move. Symbols are R for right, L for left, U for up, and D for down. If the robot returns to the origin after it finishes all of its moves, return true. Otherwise, return false. So, if the input is like "RRULLD", then the output will be true, Right two-unit, then go up, then left two unit then again down, so this is the starting position. To solve this, we will follow these steps − l := size of moves array l := size of moves array if l is same as 0, then −return true if l is same as 0, then − return true return true lft := 0, up := 0 lft := 0, up := 0 for initialize i := 0, when i < l, update (increase i by 1), do −if moves[i] is same as 'L', then −(increase lft by 1)if moves[i] is same as 'R', then −(decrease lft by 1)if moves[i] is same as 'U', then −(increase up by 1)if moves[i] is same as 'D', then −(decrease up by 1) for initialize i := 0, when i < l, update (increase i by 1), do − if moves[i] is same as 'L', then −(increase lft by 1) if moves[i] is same as 'L', then − (increase lft by 1) (increase lft by 1) if moves[i] is same as 'R', then −(decrease lft by 1) if moves[i] is same as 'R', then − (decrease lft by 1) (decrease lft by 1) if moves[i] is same as 'U', then −(increase up by 1) if moves[i] is same as 'U', then − (increase up by 1) (increase up by 1) if moves[i] is same as 'D', then −(decrease up by 1) if moves[i] is same as 'D', then − (decrease up by 1) (decrease up by 1) if lft is same as 0 and up is same as 0, then −return true if lft is same as 0 and up is same as 0, then − return true return true return false return false Let us see the following implementation to get a better understanding − Live Demo #include <bits/stdc++.h> using namespace std; class Solution { public: bool judgeCircle(string moves) { int l = moves.length(); if (l == 0) { return true; } int lft = 0, up = 0; for (int i = 0; i < l; i++) { if (moves[i] == 'L') { lft++; } if (moves[i] == 'R') { lft--; } if (moves[i] == 'U') { up++; } if (moves[i] == 'D') { up--; } } if (lft == 0 && up == 0) { return true; } return false; } }; main(){ Solution ob; cout << (ob.judgeCircle("RRULLD")); } "RRULLD" 1
[ { "code": null, "e": 1248, "s": 1062, "text": "Suppose there is a robot and its starting position is (0, 0). If we have a sequence of its movements, we have to check whether this robot ends up at (0, 0) after it completes its moves." }, { "code": null, "e": 1512, "s": 1248, "text": "The move sequence is given as a string, and the character moves[i] represents its ith move. Symbols are R for right, L for left, U for up, and D for down. If the robot returns to the origin after it finishes all of its moves, return true. Otherwise, return false." }, { "code": null, "e": 1675, "s": 1512, "text": "So, if the input is like \"RRULLD\", then the output will be true, Right two-unit, then go up, then left two unit then again down, so this is the starting position." }, { "code": null, "e": 1719, "s": 1675, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1744, "s": 1719, "text": "l := size of moves array" }, { "code": null, "e": 1769, "s": 1744, "text": "l := size of moves array" }, { "code": null, "e": 1806, "s": 1769, "text": "if l is same as 0, then −return true" }, { "code": null, "e": 1832, "s": 1806, "text": "if l is same as 0, then −" }, { "code": null, "e": 1844, "s": 1832, "text": "return true" }, { "code": null, "e": 1856, "s": 1844, "text": "return true" }, { "code": null, "e": 1874, "s": 1856, "text": "lft := 0, up := 0" }, { "code": null, "e": 1892, "s": 1874, "text": "lft := 0, up := 0" }, { "code": null, "e": 2168, "s": 1892, "text": "for initialize i := 0, when i < l, update (increase i by 1), do −if moves[i] is same as 'L', then −(increase lft by 1)if moves[i] is same as 'R', then −(decrease lft by 1)if moves[i] is same as 'U', then −(increase up by 1)if moves[i] is same as 'D', then −(decrease up by 1)" }, { "code": null, "e": 2234, "s": 2168, "text": "for initialize i := 0, when i < l, update (increase i by 1), do −" }, { "code": null, "e": 2288, "s": 2234, "text": "if moves[i] is same as 'L', then −(increase lft by 1)" }, { "code": null, "e": 2323, "s": 2288, "text": "if moves[i] is same as 'L', then −" }, { "code": null, "e": 2343, "s": 2323, "text": "(increase lft by 1)" }, { "code": null, "e": 2363, "s": 2343, "text": "(increase lft by 1)" }, { "code": null, "e": 2417, "s": 2363, "text": "if moves[i] is same as 'R', then −(decrease lft by 1)" }, { "code": null, "e": 2452, "s": 2417, "text": "if moves[i] is same as 'R', then −" }, { "code": null, "e": 2472, "s": 2452, "text": "(decrease lft by 1)" }, { "code": null, "e": 2492, "s": 2472, "text": "(decrease lft by 1)" }, { "code": null, "e": 2545, "s": 2492, "text": "if moves[i] is same as 'U', then −(increase up by 1)" }, { "code": null, "e": 2580, "s": 2545, "text": "if moves[i] is same as 'U', then −" }, { "code": null, "e": 2599, "s": 2580, "text": "(increase up by 1)" }, { "code": null, "e": 2618, "s": 2599, "text": "(increase up by 1)" }, { "code": null, "e": 2671, "s": 2618, "text": "if moves[i] is same as 'D', then −(decrease up by 1)" }, { "code": null, "e": 2706, "s": 2671, "text": "if moves[i] is same as 'D', then −" }, { "code": null, "e": 2725, "s": 2706, "text": "(decrease up by 1)" }, { "code": null, "e": 2744, "s": 2725, "text": "(decrease up by 1)" }, { "code": null, "e": 2803, "s": 2744, "text": "if lft is same as 0 and up is same as 0, then −return true" }, { "code": null, "e": 2851, "s": 2803, "text": "if lft is same as 0 and up is same as 0, then −" }, { "code": null, "e": 2863, "s": 2851, "text": "return true" }, { "code": null, "e": 2875, "s": 2863, "text": "return true" }, { "code": null, "e": 2888, "s": 2875, "text": "return false" }, { "code": null, "e": 2901, "s": 2888, "text": "return false" }, { "code": null, "e": 2973, "s": 2901, "text": "Let us see the following implementation to get a better understanding −" }, { "code": null, "e": 2984, "s": 2973, "text": " Live Demo" }, { "code": null, "e": 3644, "s": 2984, "text": "#include <bits/stdc++.h>\nusing namespace std;\nclass Solution {\npublic:\n bool judgeCircle(string moves) {\n int l = moves.length();\n if (l == 0) {\n return true;\n }\n int lft = 0, up = 0;\n for (int i = 0; i < l; i++) {\n if (moves[i] == 'L') {\n lft++;\n }\n if (moves[i] == 'R') {\n lft--;\n }\n if (moves[i] == 'U') {\n up++;\n }\n if (moves[i] == 'D') {\n up--;\n }\n }\n if (lft == 0 && up == 0) {\n return true;\n }\n return false;\n }\n};\nmain(){\n Solution ob;\n cout << (ob.judgeCircle(\"RRULLD\"));\n}" }, { "code": null, "e": 3653, "s": 3644, "text": "\"RRULLD\"" }, { "code": null, "e": 3655, "s": 3653, "text": "1" } ]
How to ceate right justified JTextField in Java?
To create right justified JTextField, set the alignment to be RIGHT. Here, we will be using the setHorizontalAlignment() method as well and within that the alignment would be set. Create a JTextField − JTextField emailId = new JTextField(20); Now, align it to the right − emailId.setHorizontalAlignment(JTextField.RIGHT); The following is an example to create right justified JTextField − package my; import java.awt.FlowLayout; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JTextField; import javax.swing.SwingConstants; public class SwingDemo { public static void main(String[] args) throws Exception { JFrame frame = new JFrame("Enter emailid..."); JLabel label; frame.setLayout(new FlowLayout()); label = new JLabel("TextField (Right Justified)", SwingConstants.LEFT); JTextField emailId = new JTextField(20); emailId.setHorizontalAlignment(JTextField.RIGHT); frame.add(label); frame.add(emailId); frame.setSize(550,250); frame.setVisible(true); } } This will produce the following output. Now, if yiu will tyoe any text in the component, it would begin from the right −
[ { "code": null, "e": 1242, "s": 1062, "text": "To create right justified JTextField, set the alignment to be RIGHT. Here, we will be using the setHorizontalAlignment() method as well and within that the alignment would be set." }, { "code": null, "e": 1264, "s": 1242, "text": "Create a JTextField −" }, { "code": null, "e": 1305, "s": 1264, "text": "JTextField emailId = new JTextField(20);" }, { "code": null, "e": 1334, "s": 1305, "text": "Now, align it to the right −" }, { "code": null, "e": 1384, "s": 1334, "text": "emailId.setHorizontalAlignment(JTextField.RIGHT);" }, { "code": null, "e": 1451, "s": 1384, "text": "The following is an example to create right justified JTextField −" }, { "code": null, "e": 2109, "s": 1451, "text": "package my;\nimport java.awt.FlowLayout;\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\nimport javax.swing.JTextField;\nimport javax.swing.SwingConstants;\npublic class SwingDemo {\n public static void main(String[] args) throws Exception {\n JFrame frame = new JFrame(\"Enter emailid...\");\n JLabel label;\n frame.setLayout(new FlowLayout());\n label = new JLabel(\"TextField (Right Justified)\", SwingConstants.LEFT);\n JTextField emailId = new JTextField(20);\n emailId.setHorizontalAlignment(JTextField.RIGHT);\n frame.add(label);\n frame.add(emailId);\n frame.setSize(550,250);\n frame.setVisible(true);\n }\n}" }, { "code": null, "e": 2230, "s": 2109, "text": "This will produce the following output. Now, if yiu will tyoe any text in the component, it would begin from the right −" } ]
1st to Kth shortest path lengths from node 1 to N in given Graph - GeeksforGeeks
28 Oct, 2021 Given a directed and weighted graph of N nodes and M edges, the task is to find the 1st to Kth shortest path lengths from node 1 to N. Examples: Input: N = 4, M = 6, K = 3, edges = {{1, 2, 1}, {1, 3, 3}, {2, 3, 2}, {2, 4, 6}, {3, 2, 8}, {3, 4, 1}}Output: 4 4 7Explanation: The shortest path length from 1 to N is 4, 2nd shortest length is also 4 and 3rd shortest length is 7. Input: N = 3, M = 3, K = 2, edges = {{1, 2, 2}, {2, 3, 2}, {1, 3, 1}}Output: 1 4 Approach: The idea is to traverse all vertices of the graph using BFS and use priority queue to store the vertices for which the shortest distance is not finalized yet, and also to get the minimum distance vertex. Follow the steps below for the approach. Initialize a priority queue, say, pq of size N to store the vertex number and distance value. Initialize a 2-d vector, say, dis of size N*K and initialize all values with a very large number, say, 1e9. Set dis[1][0] to zero, the distance value of the source vertex. Iterate while pq is not empty.Pop the value from pq, and store the vertex value in variable u and vertex distance in variable d.If d is greater than the distance u, then continue.For every adjacent vertex v of u check if the Kth distance value is more than the weight of u-v plus the distance value of u, then update the Kth distance value of v and sort the k distances of vertex v. Pop the value from pq, and store the vertex value in variable u and vertex distance in variable d. If d is greater than the distance u, then continue. For every adjacent vertex v of u check if the Kth distance value is more than the weight of u-v plus the distance value of u, then update the Kth distance value of v and sort the k distances of vertex v. Below is the implementation of the above approach: C++14 Javascript // C++ implementation of above approach#include <bits/stdc++.h>using namespace std; // Function to find K shortest path lengthsvoid findKShortest(int edges[][3], int n, int m, int k){ // Initialize graph vector<vector<pair<int, int> > > g(n + 1); for (int i = 0; i < m; i++) { // Storing edges g[edges[i][0]].push_back({ edges[i][1], edges[i][2] }); } // Vector to store distances vector<vector<int> > dis(n + 1, vector<int>(k, 1e9)); // Initialization of priority queue priority_queue<pair<int, int>, vector<pair<int, int> >, greater<pair<int, int> > > pq; pq.push({ 0, 1 }); dis[1][0] = 0; // while pq has elements while (!pq.empty()) { // Storing the node value int u = pq.top().second; // Storing the distance value int d = (pq.top().first); pq.pop(); if (dis[u][k - 1] < d) continue; vector<pair<int, int> > v = g[u]; // Traversing the adjacency list for (int i = 0; i < v.size(); i++) { int dest = v[i].first; int cost = v[i].second; // Checking for the cost if (d + cost < dis[dest][k - 1]) { dis[dest][k - 1] = d + cost; // Sorting the distances sort(dis[dest].begin(), dis[dest].end()); // Pushing elements to priority queue pq.push({ (d + cost), dest }); } } } // Printing K shortest paths for (int i = 0; i < k; i++) { cout << dis[n][i] << " "; }} // Driver Codeint main(){ // Given Input int N = 4, M = 6, K = 3; int edges[][3] = { { 1, 2, 1 }, { 1, 3, 3 }, { 2, 3, 2 }, { 2, 4, 6 }, { 3, 2, 8 }, { 3, 4, 1 } }; // Function Call findKShortest(edges, N, M, K); return 0;} <script> // Javascript implementation of above approach // Function to find K shortest path lengthsfunction findKShortest(edges, n, m, k){ // Initialize graph var g = Array.from(Array(n + 1), ()=>new Array()); for (var i = 0; i < m; i++) { // Storing edges g[edges[i][0]].push([edges[i][1], edges[i][2]]); } // Vector to store distances var dis = Array.from(Array(n+1), ()=> Array(k).fill(1000000000)); // Initialization of priority queue var pq = []; pq.push([0, 1]); dis[1][0] = 0; // while pq has elements while (pq.length != 0) { // Storing the node value var u = pq[pq.length-1][1]; // Storing the distance value var d = (pq[pq.length-1][0]); pq.pop(); if (dis[u][k - 1] < d) continue; var v = g[u]; // Traversing the adjacency list for (var i = 0; i < v.length; i++) { var dest = v[i][0]; var cost = v[i][1]; // Checking for the cost if (d + cost < dis[dest][k - 1]) { dis[dest][k - 1] = d + cost; // Sorting the distances dis[dest].sort((a,b)=>a-b); // Pushing elements to priority queue pq.push([(d + cost), dest ]); pq.sort(); } } } // Printing K shortest paths for (var i = 0; i < k; i++) { document.write(dis[n][i] + " "); }} // Driver Code // Given Inputvar N = 4, M = 6, K = 3;var edges = [ [ 1, 2, 1 ], [ 1, 3, 3 ], [ 2, 3, 2 ], [ 2, 4, 6 ], [ 3, 2, 8 ], [ 3, 4, 1 ] ]; // Function CallfindKShortest(edges, N, M, K); // This code is contributed by rrrtnx.</script> 4 4 7 Time Complexity: O((N+M)*KlogK)Auxiliary Space: O(NK) rrrtnx BFS priority-queue Shortest Path Graph Sorting Sorting Graph Shortest Path BFS priority-queue Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Vertex Cover Problem | Set 1 (Introduction and Approximate Algorithm) Graph Coloring | Set 2 (Greedy Algorithm) Best First Search (Informed Search) Find if there is a path between two vertices in a directed graph Shortest Path in a weighted Graph where weight of an edge is 1 or 2
[ { "code": null, "e": 25010, "s": 24982, "text": "\n28 Oct, 2021" }, { "code": null, "e": 25145, "s": 25010, "text": "Given a directed and weighted graph of N nodes and M edges, the task is to find the 1st to Kth shortest path lengths from node 1 to N." }, { "code": null, "e": 25155, "s": 25145, "text": "Examples:" }, { "code": null, "e": 25386, "s": 25155, "text": "Input: N = 4, M = 6, K = 3, edges = {{1, 2, 1}, {1, 3, 3}, {2, 3, 2}, {2, 4, 6}, {3, 2, 8}, {3, 4, 1}}Output: 4 4 7Explanation: The shortest path length from 1 to N is 4, 2nd shortest length is also 4 and 3rd shortest length is 7." }, { "code": null, "e": 25467, "s": 25386, "text": "Input: N = 3, M = 3, K = 2, edges = {{1, 2, 2}, {2, 3, 2}, {1, 3, 1}}Output: 1 4" }, { "code": null, "e": 25723, "s": 25467, "text": "Approach: The idea is to traverse all vertices of the graph using BFS and use priority queue to store the vertices for which the shortest distance is not finalized yet, and also to get the minimum distance vertex. Follow the steps below for the approach. " }, { "code": null, "e": 25817, "s": 25723, "text": "Initialize a priority queue, say, pq of size N to store the vertex number and distance value." }, { "code": null, "e": 25925, "s": 25817, "text": "Initialize a 2-d vector, say, dis of size N*K and initialize all values with a very large number, say, 1e9." }, { "code": null, "e": 25989, "s": 25925, "text": "Set dis[1][0] to zero, the distance value of the source vertex." }, { "code": null, "e": 26372, "s": 25989, "text": "Iterate while pq is not empty.Pop the value from pq, and store the vertex value in variable u and vertex distance in variable d.If d is greater than the distance u, then continue.For every adjacent vertex v of u check if the Kth distance value is more than the weight of u-v plus the distance value of u, then update the Kth distance value of v and sort the k distances of vertex v." }, { "code": null, "e": 26471, "s": 26372, "text": "Pop the value from pq, and store the vertex value in variable u and vertex distance in variable d." }, { "code": null, "e": 26523, "s": 26471, "text": "If d is greater than the distance u, then continue." }, { "code": null, "e": 26727, "s": 26523, "text": "For every adjacent vertex v of u check if the Kth distance value is more than the weight of u-v plus the distance value of u, then update the Kth distance value of v and sort the k distances of vertex v." }, { "code": null, "e": 26778, "s": 26727, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 26784, "s": 26778, "text": "C++14" }, { "code": null, "e": 26795, "s": 26784, "text": "Javascript" }, { "code": "// C++ implementation of above approach#include <bits/stdc++.h>using namespace std; // Function to find K shortest path lengthsvoid findKShortest(int edges[][3], int n, int m, int k){ // Initialize graph vector<vector<pair<int, int> > > g(n + 1); for (int i = 0; i < m; i++) { // Storing edges g[edges[i][0]].push_back({ edges[i][1], edges[i][2] }); } // Vector to store distances vector<vector<int> > dis(n + 1, vector<int>(k, 1e9)); // Initialization of priority queue priority_queue<pair<int, int>, vector<pair<int, int> >, greater<pair<int, int> > > pq; pq.push({ 0, 1 }); dis[1][0] = 0; // while pq has elements while (!pq.empty()) { // Storing the node value int u = pq.top().second; // Storing the distance value int d = (pq.top().first); pq.pop(); if (dis[u][k - 1] < d) continue; vector<pair<int, int> > v = g[u]; // Traversing the adjacency list for (int i = 0; i < v.size(); i++) { int dest = v[i].first; int cost = v[i].second; // Checking for the cost if (d + cost < dis[dest][k - 1]) { dis[dest][k - 1] = d + cost; // Sorting the distances sort(dis[dest].begin(), dis[dest].end()); // Pushing elements to priority queue pq.push({ (d + cost), dest }); } } } // Printing K shortest paths for (int i = 0; i < k; i++) { cout << dis[n][i] << \" \"; }} // Driver Codeint main(){ // Given Input int N = 4, M = 6, K = 3; int edges[][3] = { { 1, 2, 1 }, { 1, 3, 3 }, { 2, 3, 2 }, { 2, 4, 6 }, { 3, 2, 8 }, { 3, 4, 1 } }; // Function Call findKShortest(edges, N, M, K); return 0;}", "e": 28676, "s": 26795, "text": null }, { "code": "<script> // Javascript implementation of above approach // Function to find K shortest path lengthsfunction findKShortest(edges, n, m, k){ // Initialize graph var g = Array.from(Array(n + 1), ()=>new Array()); for (var i = 0; i < m; i++) { // Storing edges g[edges[i][0]].push([edges[i][1], edges[i][2]]); } // Vector to store distances var dis = Array.from(Array(n+1), ()=> Array(k).fill(1000000000)); // Initialization of priority queue var pq = []; pq.push([0, 1]); dis[1][0] = 0; // while pq has elements while (pq.length != 0) { // Storing the node value var u = pq[pq.length-1][1]; // Storing the distance value var d = (pq[pq.length-1][0]); pq.pop(); if (dis[u][k - 1] < d) continue; var v = g[u]; // Traversing the adjacency list for (var i = 0; i < v.length; i++) { var dest = v[i][0]; var cost = v[i][1]; // Checking for the cost if (d + cost < dis[dest][k - 1]) { dis[dest][k - 1] = d + cost; // Sorting the distances dis[dest].sort((a,b)=>a-b); // Pushing elements to priority queue pq.push([(d + cost), dest ]); pq.sort(); } } } // Printing K shortest paths for (var i = 0; i < k; i++) { document.write(dis[n][i] + \" \"); }} // Driver Code // Given Inputvar N = 4, M = 6, K = 3;var edges = [ [ 1, 2, 1 ], [ 1, 3, 3 ], [ 2, 3, 2 ], [ 2, 4, 6 ], [ 3, 2, 8 ], [ 3, 4, 1 ] ]; // Function CallfindKShortest(edges, N, M, K); // This code is contributed by rrrtnx.</script>", "e": 30431, "s": 28676, "text": null }, { "code": null, "e": 30438, "s": 30431, "text": "4 4 7 " }, { "code": null, "e": 30492, "s": 30438, "text": "Time Complexity: O((N+M)*KlogK)Auxiliary Space: O(NK)" }, { "code": null, "e": 30499, "s": 30492, "text": "rrrtnx" }, { "code": null, "e": 30503, "s": 30499, "text": "BFS" }, { "code": null, "e": 30518, "s": 30503, "text": "priority-queue" }, { "code": null, "e": 30532, "s": 30518, "text": "Shortest Path" }, { "code": null, "e": 30538, "s": 30532, "text": "Graph" }, { "code": null, "e": 30546, "s": 30538, "text": "Sorting" }, { "code": null, "e": 30554, "s": 30546, "text": "Sorting" }, { "code": null, "e": 30560, "s": 30554, "text": "Graph" }, { "code": null, "e": 30574, "s": 30560, "text": "Shortest Path" }, { "code": null, "e": 30578, "s": 30574, "text": "BFS" }, { "code": null, "e": 30593, "s": 30578, "text": "priority-queue" }, { "code": null, "e": 30691, "s": 30593, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30700, "s": 30691, "text": "Comments" }, { "code": null, "e": 30713, "s": 30700, "text": "Old Comments" }, { "code": null, "e": 30783, "s": 30713, "text": "Vertex Cover Problem | Set 1 (Introduction and Approximate Algorithm)" }, { "code": null, "e": 30825, "s": 30783, "text": "Graph Coloring | Set 2 (Greedy Algorithm)" }, { "code": null, "e": 30861, "s": 30825, "text": "Best First Search (Informed Search)" }, { "code": null, "e": 30926, "s": 30861, "text": "Find if there is a path between two vertices in a directed graph" } ]
Fruit Into Baskets in C++
Suppose we have a row of trees, the i-th tree produces fruit with type tree[i]. we can start at any tree of our choice, then repeatedly perform these steps − Add one piece of fruit from this tree to our baskets. If there is no chance, then stop. Move to the next tree to the right of the current one. If there is no tree to the right, then stop. We have two baskets, and each basket can carry any quantity of fruit, but we want each basket should only carry one type of fruit each. We have to find the total amount of fruit that we can collect with this procedure? So if the trees are like [0, 1, 2, 2], then the output will be 3. We can collect [1,2,2], if we start from the first tree, then we would only collect [0, 1] To solve this, we will follow these steps − n := tree size, j := 0, ans := 0 create one map m for i in range 0 to n – 1increase m[tree[i]] by 1while size of m is > 2 and j <= i, thendecrease m[tree[j]] by 1if m[tree[j]] = 0, then delete tree[j] from mincrease j by 1ans := max of i – j + 1 and ans increase m[tree[i]] by 1 while size of m is > 2 and j <= i, thendecrease m[tree[j]] by 1if m[tree[j]] = 0, then delete tree[j] from mincrease j by 1 decrease m[tree[j]] by 1 if m[tree[j]] = 0, then delete tree[j] from m increase j by 1 ans := max of i – j + 1 and ans return ans Let us see the following implementation to get better understanding − Live Demo #include <bits/stdc++.h> using namespace std; class Solution { public: int totalFruit(vector<int>& tree) { int n = tree.size(); int j = 0; map <int, int> m; int ans = 0; for(int i = 0; i < n; i++){ m[tree[i]] += 1; while(m.size() > 2 && j <= i){ m[tree[j]]--; if(m[tree[j]] == 0)m.erase(tree[j]); j++; } ans = max(i - j + 1, ans); } return ans; } }; main(){ vector<int> v = {3,3,3,1,2,1,1,2,3,3,4}; Solution ob; cout <<(ob.totalFruit(v)); } [3,3,3,1,2,1,1,2,3,3,4] 5
[ { "code": null, "e": 1220, "s": 1062, "text": "Suppose we have a row of trees, the i-th tree produces fruit with type tree[i]. we can start at any tree of our choice, then repeatedly perform these steps −" }, { "code": null, "e": 1308, "s": 1220, "text": "Add one piece of fruit from this tree to our baskets. If there is no chance, then stop." }, { "code": null, "e": 1408, "s": 1308, "text": "Move to the next tree to the right of the current one. If there is no tree to the right, then stop." }, { "code": null, "e": 1784, "s": 1408, "text": "We have two baskets, and each basket can carry any quantity of fruit, but we want each basket should only carry one type of fruit each. We have to find the total amount of fruit that we can collect with this procedure? So if the trees are like [0, 1, 2, 2], then the output will be 3. We can collect [1,2,2], if we start from the first tree, then we would only collect [0, 1]" }, { "code": null, "e": 1828, "s": 1784, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1861, "s": 1828, "text": "n := tree size, j := 0, ans := 0" }, { "code": null, "e": 1878, "s": 1861, "text": "create one map m" }, { "code": null, "e": 2082, "s": 1878, "text": "for i in range 0 to n – 1increase m[tree[i]] by 1while size of m is > 2 and j <= i, thendecrease m[tree[j]] by 1if m[tree[j]] = 0, then delete tree[j] from mincrease j by 1ans := max of i – j + 1 and ans" }, { "code": null, "e": 2107, "s": 2082, "text": "increase m[tree[i]] by 1" }, { "code": null, "e": 2231, "s": 2107, "text": "while size of m is > 2 and j <= i, thendecrease m[tree[j]] by 1if m[tree[j]] = 0, then delete tree[j] from mincrease j by 1" }, { "code": null, "e": 2256, "s": 2231, "text": "decrease m[tree[j]] by 1" }, { "code": null, "e": 2302, "s": 2256, "text": "if m[tree[j]] = 0, then delete tree[j] from m" }, { "code": null, "e": 2318, "s": 2302, "text": "increase j by 1" }, { "code": null, "e": 2350, "s": 2318, "text": "ans := max of i – j + 1 and ans" }, { "code": null, "e": 2361, "s": 2350, "text": "return ans" }, { "code": null, "e": 2431, "s": 2361, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 2442, "s": 2431, "text": " Live Demo" }, { "code": null, "e": 3015, "s": 2442, "text": "#include <bits/stdc++.h>\nusing namespace std;\nclass Solution {\n public:\n int totalFruit(vector<int>& tree) {\n int n = tree.size();\n int j = 0;\n map <int, int> m;\n int ans = 0;\n for(int i = 0; i < n; i++){\n m[tree[i]] += 1;\n while(m.size() > 2 && j <= i){\n m[tree[j]]--;\n if(m[tree[j]] == 0)m.erase(tree[j]);\n j++;\n }\n ans = max(i - j + 1, ans);\n }\n return ans;\n }\n};\nmain(){\n vector<int> v = {3,3,3,1,2,1,1,2,3,3,4};\n Solution ob;\n cout <<(ob.totalFruit(v));\n}" }, { "code": null, "e": 3039, "s": 3015, "text": "[3,3,3,1,2,1,1,2,3,3,4]" }, { "code": null, "e": 3041, "s": 3039, "text": "5" } ]
Python - FTP
FTP or File Transfer Protocol is a well-known network protocol used to transfer files between computers in a network. It is created on client server architecture and can be used along with user authentication. It can also be used without authentication but that will be less secure. FTP connection which maintains a current working directory and other flags, and each transfer requires a secondary connection through which the data is transferred. Most common web browsers can retrieve files hosted on FTP servers. In python we use the module ftplib which has the below required methods to list the files as we will transfer the files. Below are the examples of some of the above methods. The below example uses anonymous login to the ftp server and lists the content of the current directory. It treates through the name of the files and directories and stores them as a list. Then prints them out. import ftplib ftp = ftplib.FTP("ftp.nluug.nl") ftp.login("anonymous", "ftplib-example-1") data = [] ftp.dir(data.append) ftp.quit() for line in data: print "-", line When we run the above program, we get the following output − - lrwxrwxrwx 1 0 0 1 Nov 13 2012 ftp -> . - lrwxrwxrwx 1 0 0 3 Nov 13 2012 mirror -> pub - drwxr-xr-x 23 0 0 4096 Nov 27 2017 pub - drwxr-sr-x 88 0 450 4096 May 04 19:30 site - drwxr-xr-x 9 0 0 4096 Jan 23 2014 vol The below program uses the cwd method available in the ftplib module to change the directory and then fetch the required content. import ftplib ftp = ftplib.FTP("ftp.nluug.nl") ftp.login("anonymous", "ftplib-example-1") data = [] ftp.cwd('/pub/') change directory to /pub/ ftp.dir(data.append) ftp.quit() for line in data: print "-", line When we run the above program, we get the following output − - lrwxrwxrwx 1 504 450 14 Nov 02 2007 FreeBSD -> os/BSD/FreeBSD - lrwxrwxrwx 1 504 450 20 Nov 02 2007 ImageMagick -> graphics/ImageMagick - lrwxrwxrwx 1 504 450 13 Nov 02 2007 NetBSD -> os/BSD/NetBSD - lrwxrwxrwx 1 504 450 14 Nov 02 2007 OpenBSD -> os/BSD/OpenBSD - -rw-rw-r-- 1 504 450 932 Jan 04 2015 README.nluug - -rw-r--r-- 1 504 450 2023 May 03 2005 WhereToFindWhat.txt - drwxr-sr-x 2 0 450 4096 Jan 26 2008 av - drwxrwsr-x 2 0 450 4096 Aug 12 2004 comp After getting the list of files as shown above, we can fetch a specific file by using the getfile method. This method moves a copy of the file from the remote system to the local system from where the ftp connection was initiated. import ftplib import sys def getFile(ftp, filename): try: ftp.retrbinary("RETR " + filename ,open(filename, 'wb').write) except: print "Error" ftp = ftplib.FTP("ftp.nluug.nl") ftp.login("anonymous", "ftplib-example-1") ftp.cwd('/pub/') change directory to /pub/ getFile(ftp,'README.nluug') ftp.quit() When we run the above program, we find the file README.nlug to be present in the local system from where the connection was initiated. 187 Lectures 17.5 hours Malhar Lathkar 55 Lectures 8 hours Arnab Chakraborty 136 Lectures 11 hours In28Minutes Official 75 Lectures 13 hours Eduonix Learning Solutions 70 Lectures 8.5 hours Lets Kode It 63 Lectures 6 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 2843, "s": 2326, "text": "FTP or File Transfer Protocol is a well-known network protocol used to transfer files between computers in a network. \nIt is created on client server architecture and can be used along with user authentication. It can also be used without authentication but that \nwill be less secure. FTP connection which maintains a current working directory and other flags, and each transfer requires a secondary connection through which the data is transferred. Most common web browsers can retrieve files hosted on FTP servers." }, { "code": null, "e": 2964, "s": 2843, "text": "In python we use the module ftplib which has the below required methods to list the files as we will transfer the files." }, { "code": null, "e": 3017, "s": 2964, "text": "Below are the examples of some of the above methods." }, { "code": null, "e": 3229, "s": 3017, "text": "The below example uses anonymous login to the ftp server and lists the content of the current directory. It treates through the name of the files and directories and \nstores them as a list. Then prints them out." }, { "code": null, "e": 3409, "s": 3229, "text": "import ftplib\n \nftp = ftplib.FTP(\"ftp.nluug.nl\")\nftp.login(\"anonymous\", \"ftplib-example-1\")\n \ndata = []\n \nftp.dir(data.append)\n \nftp.quit()\n \nfor line in data:\n print \"-\", line" }, { "code": null, "e": 3470, "s": 3409, "text": "When we run the above program, we get the following output −" }, { "code": null, "e": 3797, "s": 3470, "text": "- lrwxrwxrwx 1 0 0 1 Nov 13 2012 ftp -> .\n- lrwxrwxrwx 1 0 0 3 Nov 13 2012 mirror -> pub\n- drwxr-xr-x 23 0 0 4096 Nov 27 2017 pub\n- drwxr-sr-x 88 0 450 4096 May 04 19:30 site\n- drwxr-xr-x 9 0 0 4096 Jan 23 2014 vol\n" }, { "code": null, "e": 3927, "s": 3797, "text": "The below program uses the cwd method available in the ftplib module to change the directory and then fetch the required content." }, { "code": null, "e": 4159, "s": 3927, "text": "import ftplib\n \nftp = ftplib.FTP(\"ftp.nluug.nl\")\nftp.login(\"anonymous\", \"ftplib-example-1\")\n \ndata = []\n \nftp.cwd('/pub/') change directory to /pub/\nftp.dir(data.append)\n \nftp.quit()\n \nfor line in data:\n print \"-\", line" }, { "code": null, "e": 4220, "s": 4159, "text": "When we run the above program, we get the following output −" }, { "code": null, "e": 4840, "s": 4220, "text": "- lrwxrwxrwx 1 504 450 14 Nov 02 2007 FreeBSD -> os/BSD/FreeBSD\n- lrwxrwxrwx 1 504 450 20 Nov 02 2007 ImageMagick -> graphics/ImageMagick\n- lrwxrwxrwx 1 504 450 13 Nov 02 2007 NetBSD -> os/BSD/NetBSD\n- lrwxrwxrwx 1 504 450 14 Nov 02 2007 OpenBSD -> os/BSD/OpenBSD\n- -rw-rw-r-- 1 504 450 932 Jan 04 2015 README.nluug\n- -rw-r--r-- 1 504 450 2023 May 03 2005 WhereToFindWhat.txt\n- drwxr-sr-x 2 0 450 4096 Jan 26 2008 av\n- drwxrwsr-x 2 0 450 4096 Aug 12 2004 comp\n\n\n" }, { "code": null, "e": 5072, "s": 4840, "text": "After getting the list of files as shown above, we can fetch a specific file by using the getfile method. This method moves a copy of the file from the remote system to \nthe local system from where the ftp connection was initiated." }, { "code": null, "e": 5417, "s": 5072, "text": "import ftplib\nimport sys\n \ndef getFile(ftp, filename):\n try:\n ftp.retrbinary(\"RETR \" + filename ,open(filename, 'wb').write)\n except:\n print \"Error\"\n \n \nftp = ftplib.FTP(\"ftp.nluug.nl\")\nftp.login(\"anonymous\", \"ftplib-example-1\")\n \nftp.cwd('/pub/') change directory to /pub/\ngetFile(ftp,'README.nluug')\n \nftp.quit()\n" }, { "code": null, "e": 5553, "s": 5417, "text": " When we run the above program, we find the file README.nlug to be present in the local system from where the connection was initiated." }, { "code": null, "e": 5590, "s": 5553, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 5606, "s": 5590, "text": " Malhar Lathkar" }, { "code": null, "e": 5639, "s": 5606, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 5658, "s": 5639, "text": " Arnab Chakraborty" }, { "code": null, "e": 5693, "s": 5658, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 5715, "s": 5693, "text": " In28Minutes Official" }, { "code": null, "e": 5749, "s": 5715, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 5777, "s": 5749, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 5812, "s": 5777, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 5826, "s": 5812, "text": " Lets Kode It" }, { "code": null, "e": 5859, "s": 5826, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 5876, "s": 5859, "text": " Abhilash Nelson" }, { "code": null, "e": 5883, "s": 5876, "text": " Print" }, { "code": null, "e": 5894, "s": 5883, "text": " Add Notes" } ]
Left justify output in Java
Including a minus sign after the %, makes it left justified. Note − By default, output is right justified Firstly, create a formatter object − Formatter f = new Formatter(); Now, use the format() method to left justify output − f.format("|%-15.5f|", 299.675796) The following is an example − Live Demo import java.util.*; public class Demo { public static void main(String args[]) { Formatter f = new Formatter(); // left justify f = new Formatter(); System.out.println(f.format("|%-15.5f|", 299.675796)); } } |299.67580 |
[ { "code": null, "e": 1123, "s": 1062, "text": "Including a minus sign after the %, makes it left justified." }, { "code": null, "e": 1168, "s": 1123, "text": "Note − By default, output is right justified" }, { "code": null, "e": 1205, "s": 1168, "text": "Firstly, create a formatter object −" }, { "code": null, "e": 1236, "s": 1205, "text": "Formatter f = new Formatter();" }, { "code": null, "e": 1290, "s": 1236, "text": "Now, use the format() method to left justify output −" }, { "code": null, "e": 1324, "s": 1290, "text": "f.format(\"|%-15.5f|\", 299.675796)" }, { "code": null, "e": 1354, "s": 1324, "text": "The following is an example −" }, { "code": null, "e": 1365, "s": 1354, "text": " Live Demo" }, { "code": null, "e": 1603, "s": 1365, "text": "import java.util.*;\npublic class Demo {\n public static void main(String args[]) {\n Formatter f = new Formatter();\n // left justify\n f = new Formatter();\n System.out.println(f.format(\"|%-15.5f|\", 299.675796));\n }\n}" }, { "code": null, "e": 1616, "s": 1603, "text": "|299.67580 |" } ]
Compute the histogram of a set of data using NumPy in Python - GeeksforGeeks
05 Sep, 2020 Numpy provides us the feature to compute the Histogram for the given data set using NumPy.histogram() function. The formation of histogram depends on the data set, whether it is predefined or randomly generated. Syntax : numpy.histogram(data, bins=10, range=None, normed=None, weights=None, density=None) Case 1: Computing the Numpy Histogram with the help of Random Data set Python3 # import Numpy and matplotlibfrom matplotlib import pyplot as pltimport numpy as np # Creating random datasetdata_set = np.random.randint(100, size=(50)) # Creation of plotfig = plt.figure(figsize=(10, 6)) # plotting the Histogram with certain intervalsplt.hist(data_set, bins=[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]) # Giving title to Histogramplt.title("Random Histogram") # Displaying Histogramplt.show() Output: In the above example, we created a random data set using np.random.randint() and plot the Numpy Histogram Case 2: Computing the Numpy Histogram with the help of Pre-defined Data set Python3 # import Numpy and matplotlibfrom matplotlib import pyplot as pltimport numpy as np # Using predefined datasetdata_set = [45, 85, 95, 10, 58, 77, 92, 72, 52, 22, 32, 5, 95, 2, 23, 24, 50, 40, 60, 69, 44, 80, 21, 15, 17, 55, 21, 88] # Creation of plotfig = plt.figure(figsize=(10, 5)) # plotting the Histogram with certain intervalsplt.hist(data_set, bins=[0, 15, 30, 45, 60, 75, 90, 105]) # Giving title to Histogramplt.title("Predefined Histogram") # Displaying Histogramplt.show() In the above example, we take a predefined data set and plot the Numpy Histogram. Python-matplotlib Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Pandas dataframe.groupby() Python | Get unique values from a list Defaultdict in Python Python | os.path.join() method Python Classes and Objects Create a directory in Python
[ { "code": null, "e": 23901, "s": 23873, "text": "\n05 Sep, 2020" }, { "code": null, "e": 24113, "s": 23901, "text": "Numpy provides us the feature to compute the Histogram for the given data set using NumPy.histogram() function. The formation of histogram depends on the data set, whether it is predefined or randomly generated." }, { "code": null, "e": 24206, "s": 24113, "text": "Syntax : numpy.histogram(data, bins=10, range=None, normed=None, weights=None, density=None)" }, { "code": null, "e": 24277, "s": 24206, "text": "Case 1: Computing the Numpy Histogram with the help of Random Data set" }, { "code": null, "e": 24285, "s": 24277, "text": "Python3" }, { "code": "# import Numpy and matplotlibfrom matplotlib import pyplot as pltimport numpy as np # Creating random datasetdata_set = np.random.randint(100, size=(50)) # Creation of plotfig = plt.figure(figsize=(10, 6)) # plotting the Histogram with certain intervalsplt.hist(data_set, bins=[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]) # Giving title to Histogramplt.title(\"Random Histogram\") # Displaying Histogramplt.show()", "e": 24729, "s": 24285, "text": null }, { "code": null, "e": 24737, "s": 24729, "text": "Output:" }, { "code": null, "e": 24843, "s": 24737, "text": "In the above example, we created a random data set using np.random.randint() and plot the Numpy Histogram" }, { "code": null, "e": 24919, "s": 24843, "text": "Case 2: Computing the Numpy Histogram with the help of Pre-defined Data set" }, { "code": null, "e": 24927, "s": 24919, "text": "Python3" }, { "code": "# import Numpy and matplotlibfrom matplotlib import pyplot as pltimport numpy as np # Using predefined datasetdata_set = [45, 85, 95, 10, 58, 77, 92, 72, 52, 22, 32, 5, 95, 2, 23, 24, 50, 40, 60, 69, 44, 80, 21, 15, 17, 55, 21, 88] # Creation of plotfig = plt.figure(figsize=(10, 5)) # plotting the Histogram with certain intervalsplt.hist(data_set, bins=[0, 15, 30, 45, 60, 75, 90, 105]) # Giving title to Histogramplt.title(\"Predefined Histogram\") # Displaying Histogramplt.show()", "e": 25439, "s": 24927, "text": null }, { "code": null, "e": 25521, "s": 25439, "text": "In the above example, we take a predefined data set and plot the Numpy Histogram." }, { "code": null, "e": 25539, "s": 25521, "text": "Python-matplotlib" }, { "code": null, "e": 25552, "s": 25539, "text": "Python-numpy" }, { "code": null, "e": 25559, "s": 25552, "text": "Python" }, { "code": null, "e": 25657, "s": 25559, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25666, "s": 25657, "text": "Comments" }, { "code": null, "e": 25679, "s": 25666, "text": "Old Comments" }, { "code": null, "e": 25711, "s": 25679, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 25767, "s": 25711, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 25809, "s": 25767, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 25851, "s": 25809, "text": "Check if element exists in list in Python" }, { "code": null, "e": 25887, "s": 25851, "text": "Python | Pandas dataframe.groupby()" }, { "code": null, "e": 25926, "s": 25887, "text": "Python | Get unique values from a list" }, { "code": null, "e": 25948, "s": 25926, "text": "Defaultdict in Python" }, { "code": null, "e": 25979, "s": 25948, "text": "Python | os.path.join() method" }, { "code": null, "e": 26006, "s": 25979, "text": "Python Classes and Objects" } ]
Optional Parameters with Default Values
Function parameters can also be assigned values by default. However, such parameters can also be explicitly passed values. function_name(param1,{param2= default_value}) { //...... } void main() { test_param(123); } void test_param(n1,{s1:12}) { print(n1); print(s1); } It should return the following output− 123 12 Note − All required parameters in a function must occur before optional parameters. 44 Lectures 4.5 hours Sriyank Siddhartha 34 Lectures 4 hours Sriyank Siddhartha 69 Lectures 4 hours Frahaan Hussain 117 Lectures 10 hours Frahaan Hussain 22 Lectures 1.5 hours Pranjal Srivastava 34 Lectures 3 hours Pranjal Srivastava Print Add Notes Bookmark this page
[ { "code": null, "e": 2648, "s": 2525, "text": "Function parameters can also be assigned values by default. However, such parameters can also be explicitly passed values." }, { "code": null, "e": 2714, "s": 2648, "text": "function_name(param1,{param2= default_value}) { \n //...... \n} \n" }, { "code": null, "e": 2820, "s": 2714, "text": "void main() { \n test_param(123); \n} \nvoid test_param(n1,{s1:12}) { \n print(n1); \n print(s1); \n} " }, { "code": null, "e": 2859, "s": 2820, "text": "It should return the following output−" }, { "code": null, "e": 2869, "s": 2859, "text": "123 \n12 \n" }, { "code": null, "e": 2953, "s": 2869, "text": "Note − All required parameters in a function must occur before optional parameters." }, { "code": null, "e": 2988, "s": 2953, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3008, "s": 2988, "text": " Sriyank Siddhartha" }, { "code": null, "e": 3041, "s": 3008, "text": "\n 34 Lectures \n 4 hours \n" }, { "code": null, "e": 3061, "s": 3041, "text": " Sriyank Siddhartha" }, { "code": null, "e": 3094, "s": 3061, "text": "\n 69 Lectures \n 4 hours \n" }, { "code": null, "e": 3111, "s": 3094, "text": " Frahaan Hussain" }, { "code": null, "e": 3146, "s": 3111, "text": "\n 117 Lectures \n 10 hours \n" }, { "code": null, "e": 3163, "s": 3146, "text": " Frahaan Hussain" }, { "code": null, "e": 3198, "s": 3163, "text": "\n 22 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3218, "s": 3198, "text": " Pranjal Srivastava" }, { "code": null, "e": 3251, "s": 3218, "text": "\n 34 Lectures \n 3 hours \n" }, { "code": null, "e": 3271, "s": 3251, "text": " Pranjal Srivastava" }, { "code": null, "e": 3278, "s": 3271, "text": " Print" }, { "code": null, "e": 3289, "s": 3278, "text": " Add Notes" } ]
Print the Alphabets A to Z in Star Pattern - GeeksforGeeks
17 Aug, 2021 Given any alphabet between A to Z, the task is to print the pattern of the given alphabet using star. Examples: Input: A Output: ** * * ****** * * * * Input: P Output: ***** * * ***** * * Approach: The code to print each alphabet is created in a separate function. Use switch statement to call the desired function on the basis of the alphabet’s pattern required. Below is the implementation. C++ C Java Python3 C# Javascript // C++ implementation to print the// pattern of alphabets A to Z using * #include <iostream>using namespace std; // Below height and width variable can be used// to create a user-defined sized alphabet's pattern // Number of lines for the alphabet's patternint height = 5;// Number of character width in each lineint width = (2 * height) - 1; // Function to find the absolute value// of a number Dint abs(int d){ return d < 0 ? -1 * d : d;} // Function to print the pattern of 'A'void printA(){ int n = width / 2, i, j; for (i = 0; i < height; i++) { for (j = 0; j <= width; j++) { if (j == n || j == (width - n) || (i == height / 2 && j > n && j < (width - n))) cout <<"*"; else cout <<" "; } cout <<"\n"; n--; }} // Function to print the pattern of 'B'void printB(){ int i, j, half = (height / 2); for (i = 0; i < height; i++) { cout <<"*"; for (j = 0; j < width; j++) { if ((i == 0 || i == height - 1 || i == half) && j < (width - 2)) cout <<"*"; else if (j == (width - 2) && !(i == 0 || i == height - 1 || i == half)) cout <<"*"; else cout <<" "; } cout <<"\n"; }} // Function to print the pattern of 'C'void printC(){ int i, j; for (i = 0; i < height; i++) { cout <<"*"; for (j = 0; j < (height - 1); j++) { if (i == 0 || i == height - 1) cout <<"*"; else continue; } cout <<"\n"; }} // Function to print the pattern of 'D'void printD(){ int i, j; for (i = 0; i < height; i++) { cout <<"*"; for (j = 0; j < height; j++) { if ((i == 0 || i == height - 1) && j < height - 1) cout <<"*"; else if (j == height - 1 && i != 0 && i != height - 1) cout <<"*"; else cout <<" "; } cout <<"\n"; }} // Function to print the pattern of 'E'void printE(){ int i, j; for (i = 0; i < height; i++) { cout <<"*"; for (j = 0; j < height; j++) { if ((i == 0 || i == height - 1) || (i == height / 2 && j <= height / 2)) cout <<"*"; else continue; } cout <<"\n"; }} // Function to print the pattern of 'F'void printF(){ int i, j; for (i = 0; i < height; i++) { cout <<"*"; for (j = 0; j < height; j++) { if ((i == 0) || (i == height / 2 && j <= height / 2)) cout <<"*"; else continue; } cout <<"\n"; }} // Function to print the pattern of 'G'void printG(){ int i, j; width--; for (i = 0; i < height; i++) { for (j = 0; j < width; j++) { if ((i == 0 || i == height - 1) && (j == 0 || j == width - 1)) cout <<" "; else if (j == 0) cout <<"*"; else if (i == 0 && j <= height) cout <<"*"; else if (i == height / 2 && j > height / 2) cout <<"*"; else if (i > height / 2 && j == width - 1) cout <<"*"; else if (i == height - 1 && j < width) cout <<"*"; else cout <<" "; } cout <<"\n"; }} // Function to print the pattern of 'H'void printH(){ int i, j; for (i = 0; i < height; i++) { cout <<"*"; for (j = 0; j < height; j++) { if ((j == height - 1) || (i == height / 2)) cout <<"*"; else cout <<" "; } cout <<"\n"; }} // Function to print the pattern of 'I'void printI(){ int i, j; for (i = 0; i < height; i++) { for (j = 0; j < height; j++) { if (i == 0 || i == height - 1) cout <<"*"; else if (j == height / 2) cout <<"*"; else cout <<" "; } cout <<"\n"; }} // Function to print the pattern of 'J'void printJ(){ int i, j; for (i = 0; i < height; i++) { for (j = 0; j < height; j++) { if (i == height - 1 && (j > 0 && j < height - 1)) cout <<"*"; else if ((j == height - 1 && i != height - 1) || (i > (height / 2) - 1 && j == 0 && i != height - 1)) cout <<"*"; else cout <<" "; } cout <<"\n"; }} // Function to print the pattern of 'K'void printK(){ int i, j, half = height / 2, dummy = half; for (i = 0; i < height; i++) { cout <<"*"; for (j = 0; j <= half; j++) { if (j == abs(dummy)) cout <<"*"; else cout <<" "; } cout <<"\n"; dummy--; }} // Function to print the pattern of 'L'void printL(){ int i, j; for (i = 0; i < height; i++) { cout <<"*"; for (j = 0; j <= height; j++) { if (i == height - 1) cout <<"*"; else cout <<" "; } cout <<"\n"; }} // Function to print the pattern of 'M'void printM(){ int i, j, counter = 0; for (i = 0; i < height; i++) { cout <<"*"; for (j = 0; j <= height; j++) { if (j == height) cout <<"*"; else if (j == counter || j == height - counter - 1) cout <<"*"; else cout <<" "; } if (counter == height / 2) { counter = -99999; } else counter++; cout <<"\n"; }} // Function to print the pattern of 'N'void printN(){ int i, j, counter = 0; for (i = 0; i < height; i++) { cout <<"*"; for (j = 0; j <= height; j++) { if (j == height) cout <<"*"; else if (j == counter) cout <<"*"; else cout <<" "; } counter++; cout <<"\n"; }} // Function to print the pattern of 'O'void printO(){ int i, j, space = (height / 3); int width = height / 2 + height / 5 + space + space; for (i = 0; i < height; i++) { for (j = 0; j <= width; j++) { if (j == width - abs(space) || j == abs(space)) cout <<"*"; else if ((i == 0 || i == height - 1) && j > abs(space) && j < width - abs(space)) cout <<"*"; else cout <<" "; } if (space != 0 && i < height / 2) { space--; } else if (i >= (height / 2 + height / 5)) space--; cout <<"\n"; }} // Function to print the pattern of 'P'void printP(){ int i, j; for (i = 0; i < height; i++) { cout <<"*"; for (j = 0; j < height; j++) { if ((i == 0 || i == height / 2) && j < height - 1) cout <<"*"; else if (i < height / 2 && j == height - 1 && i != 0) cout <<"*"; else cout <<" "; } cout <<"\n"; }} // Function to print the pattern of 'Q'void printQ(){ printO(); int i, j, d = height; for (i = 0; i < height / 2; i++) { for (j = 0; j <= d; j++) { if (j == d) cout <<"*"; else cout <<" "; } cout <<"\n"; d++; }} // Function to print the pattern of 'R'void printR(){ int i, j, half = (height / 2); for (i = 0; i < height; i++) { cout <<"*"; for (j = 0; j < width; j++) { if ((i == 0 || i == half) && j < (width - 2)) cout <<"*"; else if (j == (width - 2) && !(i == 0 || i == half)) cout <<"*"; else cout <<" "; } cout <<"\n"; }} // Function to print the pattern of 'S'void printS(){ int i, j; for (i = 0; i < height; i++) { for (j = 0; j < height; j++) { if ((i == 0 || i == height / 2 || i == height - 1)) cout <<"*"; else if (i < height / 2 && j == 0) cout <<"*"; else if (i > height / 2 && j == height - 1) cout <<"*"; else cout <<" "; } cout <<"\n"; }} // Function to print the pattern of 'T'void printT(){ int i, j; for (i = 0; i < height; i++) { for (j = 0; j < height; j++) { if (i == 0) cout <<"*"; else if (j == height / 2) cout <<"*"; else cout <<" "; } cout <<"\n"; }} // Function to print the pattern of 'U'void printU(){ int i, j; for (i = 0; i < height; i++) { if (i != 0 && i != height - 1) cout <<"*"; else cout <<" "; for (j = 0; j < height; j++) { if (((i == height - 1) && j >= 0 && j < height - 1)) cout <<"*"; else if (j == height - 1 && i != 0 && i != height - 1) cout <<"*"; else cout <<" "; } cout <<"\n"; }} // Function to print the pattern of 'V'void printV(){ int i, j, counter = 0; for (i = 0; i < height; i++) { for (j = 0; j <= width; j++) { if (j == counter || j == width - counter - 1) cout <<"*"; else cout <<" "; } counter++; cout <<"\n"; }} // Function to print the pattern of 'W'void printW(){ int i, j, counter = height / 2; for (i = 0; i < height; i++) { cout <<"*"; for (j = 0; j <= height; j++) { if (j == height) cout <<"*"; else if ((i >= height / 2) && (j == counter || j == height - counter - 1)) cout <<"*"; else cout <<" "; } if (i >= height / 2) { counter++; } cout <<"\n"; }} // Function to print the pattern of 'X'void printX(){ int i, j, counter = 0; for (i = 0; i <= height; i++) { for (j = 0; j <= height; j++) { if (j == counter || j == height - counter) cout <<"*"; else cout <<" "; } counter++; cout <<"\n"; }} // Function to print the pattern of 'Y'void printY(){ int i, j, counter = 0; for (i = 0; i < height; i++) { for (j = 0; j <= height; j++) { if (j == counter || j == height - counter && i <= height / 2) cout <<"*"; else cout <<" "; } cout <<"\n"; if (i < height / 2) counter++; }} // Function to print the pattern of 'Z'void printZ(){ int i, j, counter = height - 1; for (i = 0; i < height; i++) { for (j = 0; j < height; j++) { if (i == 0 || i == height - 1 || j == counter) cout <<"*"; else cout <<" "; } counter--; cout <<"\n"; }} // Function print the pattern of the// alphabets from A to Zvoid printPattern(char character){ switch (character) { case 'A': printA(); break; case 'B': printB(); break; case 'C': printC(); break; case 'D': printD(); break; case 'E': printE(); break; case 'F': printF(); break; case 'G': printG(); break; case 'H': printH(); break; case 'I': printI(); break; case 'J': printJ(); break; case 'K': printK(); break; case 'L': printL(); break; case 'M': printM(); break; case 'N': printN(); break; case 'O': printO(); break; case 'P': printP(); break; case 'Q': printQ(); break; case 'R': printR(); break; case 'S': printS(); break; case 'T': printT(); break; case 'U': printU(); break; case 'V': printV(); break; case 'W': printW(); break; case 'X': printX(); break; case 'Y': printY(); break; case 'Z': printZ(); break; }} // Driver Codeint main(){ char character = 'A'; printPattern(character); return 0;} // This code is contributed by shivani. // C++ implementation to print the// pattern of alphabets A to Z using * #include <stdio.h> // Below height and width variable can be used// to create a user-defined sized alphabet's pattern // Number of lines for the alphabet's patternint height = 5;// Number of character width in each lineint width = (2 * height) - 1; // Function to find the absolute value// of a number Dint abs(int d){ return d < 0 ? -1 * d : d;} // Function to print the pattern of 'A'void printA(){ int n = width / 2, i, j; for (i = 0; i < height; i++) { for (j = 0; j <= width; j++) { if (j == n || j == (width - n) || (i == height / 2 && j > n && j < (width - n))) printf("*"); else printf(" "); } printf("\n"); n--; }} // Function to print the pattern of 'B'void printB(){ int i, j, half = (height / 2); for (i = 0; i < height; i++) { printf("*"); for (j = 0; j < width; j++) { if ((i == 0 || i == height - 1 || i == half) && j < (width - 2)) printf("*"); else if (j == (width - 2) && !(i == 0 || i == height - 1 || i == half)) printf("*"); else printf(" "); } printf("\n"); }} // Function to print the pattern of 'C'void printC(){ int i, j; for (i = 0; i < height; i++) { printf("*"); for (j = 0; j < (height - 1); j++) { if (i == 0 || i == height - 1) printf("*"); else continue; } printf("\n"); }} // Function to print the pattern of 'D'void printD(){ int i, j; for (i = 0; i < height; i++) { printf("*"); for (j = 0; j < height; j++) { if ((i == 0 || i == height - 1) && j < height - 1) printf("*"); else if (j == height - 1 && i != 0 && i != height - 1) printf("*"); else printf(" "); } printf("\n"); }} // Function to print the pattern of 'E'void printE(){ int i, j; for (i = 0; i < height; i++) { printf("*"); for (j = 0; j < height; j++) { if ((i == 0 || i == height - 1) || (i == height / 2 && j <= height / 2)) printf("*"); else continue; } printf("\n"); }} // Function to print the pattern of 'F'void printF(){ int i, j; for (i = 0; i < height; i++) { printf("*"); for (j = 0; j < height; j++) { if ((i == 0) || (i == height / 2 && j <= height / 2)) printf("*"); else continue; } printf("\n"); }} // Function to print the pattern of 'G'void printG(){ int i, j; width--; for (i = 0; i < height; i++) { for (j = 0; j < width; j++) { if ((i == 0 || i == height - 1) && (j == 0 || j == width - 1)) printf(" "); else if (j == 0) printf("*"); else if (i == 0 && j <= height) printf("*"); else if (i == height / 2 && j > height / 2) printf("*"); else if (i > height / 2 && j == width - 1) printf("*"); else if (i == height - 1 && j < width) printf("*"); else printf(" "); } printf("\n"); }} // Function to print the pattern of 'H'void printH(){ int i, j; for (i = 0; i < height; i++) { printf("*"); for (j = 0; j < height; j++) { if ((j == height - 1) || (i == height / 2)) printf("*"); else printf(" "); } printf("\n"); }} // Function to print the pattern of 'I'void printI(){ int i, j; for (i = 0; i < height; i++) { for (j = 0; j < height; j++) { if (i == 0 || i == height - 1) printf("*"); else if (j == height / 2) printf("*"); else printf(" "); } printf("\n"); }} // Function to print the pattern of 'J'void printJ(){ int i, j; for (i = 0; i < height; i++) { for (j = 0; j < height; j++) { if (i == height - 1 && (j > 0 && j < height - 1)) printf("*"); else if ((j == height - 1 && i != height - 1) || (i > (height / 2) - 1 && j == 0 && i != height - 1)) printf("*"); else printf(" "); } printf("\n"); }} // Function to print the pattern of 'K'void printK(){ int i, j, half = height / 2, dummy = half; for (i = 0; i < height; i++) { printf("*"); for (j = 0; j <= half; j++) { if (j == abs(dummy)) printf("*"); else printf(" "); } printf("\n"); dummy--; }} // Function to print the pattern of 'L'void printL(){ int i, j; for (i = 0; i < height; i++) { printf("*"); for (j = 0; j <= height; j++) { if (i == height - 1) printf("*"); else printf(" "); } printf("\n"); }} // Function to print the pattern of 'M'void printM(){ int i, j, counter = 0; for (i = 0; i < height; i++) { printf("*"); for (j = 0; j <= height; j++) { if (j == height) printf("*"); else if (j == counter || j == height - counter - 1) printf("*"); else printf(" "); } if (counter == height / 2) { counter = -99999; } else counter++; printf("\n"); }} // Function to print the pattern of 'N'void printN(){ int i, j, counter = 0; for (i = 0; i < height; i++) { printf("*"); for (j = 0; j <= height; j++) { if (j == height) printf("*"); else if (j == counter) printf("*"); else printf(" "); } counter++; printf("\n"); }} // Function to print the pattern of 'O'void printO(){ int i, j, space = (height / 3); int width = height / 2 + height / 5 + space + space; for (i = 0; i < height; i++) { for (j = 0; j <= width; j++) { if (j == width - abs(space) || j == abs(space)) printf("*"); else if ((i == 0 || i == height - 1) && j > abs(space) && j < width - abs(space)) printf("*"); else printf(" "); } if (space != 0 && i < height / 2) { space--; } else if (i >= (height / 2 + height / 5)) space--; printf("\n"); }} // Function to print the pattern of 'P'void printP(){ int i, j; for (i = 0; i < height; i++) { printf("*"); for (j = 0; j < height; j++) { if ((i == 0 || i == height / 2) && j < height - 1) printf("*"); else if (i < height / 2 && j == height - 1 && i != 0) printf("*"); else printf(" "); } printf("\n"); }} // Function to print the pattern of 'Q'void printQ(){ printO(); int i, j, d = height; for (i = 0; i < height / 2; i++) { for (j = 0; j <= d; j++) { if (j == d) printf("*"); else printf(" "); } printf("\n"); d++; }} // Function to print the pattern of 'R'void printR(){ int i, j, half = (height / 2); for (i = 0; i < height; i++) { printf("*"); for (j = 0; j < width; j++) { if ((i == 0 || i == half) && j < (width - 2)) printf("*"); else if (j == (width - 2) && !(i == 0 || i == half)) printf("*"); else printf(" "); } printf("\n"); }} // Function to print the pattern of 'S'void printS(){ int i, j; for (i = 0; i < height; i++) { for (j = 0; j < height; j++) { if ((i == 0 || i == height / 2 || i == height - 1)) printf("*"); else if (i < height / 2 && j == 0) printf("*"); else if (i > height / 2 && j == height - 1) printf("*"); else printf(" "); } printf("\n"); }} // Function to print the pattern of 'T'void printT(){ int i, j; for (i = 0; i < height; i++) { for (j = 0; j < height; j++) { if (i == 0) printf("*"); else if (j == height / 2) printf("*"); else printf(" "); } printf("\n"); }} // Function to print the pattern of 'U'void printU(){ int i, j; for (i = 0; i < height; i++) { if (i != 0 && i != height - 1) printf("*"); else printf(" "); for (j = 0; j < height; j++) { if (((i == height - 1) && j >= 0 && j < height - 1)) printf("*"); else if (j == height - 1 && i != 0 && i != height - 1) printf("*"); else printf(" "); } printf("\n"); }} // Function to print the pattern of 'V'void printV(){ int i, j, counter = 0; for (i = 0; i < height; i++) { for (j = 0; j <= width; j++) { if (j == counter || j == width - counter - 1) printf("*"); else printf(" "); } counter++; printf("\n"); }} // Function to print the pattern of 'W'void printW(){ int i, j, counter = height / 2; for (i = 0; i < height; i++) { printf("*"); for (j = 0; j <= height; j++) { if (j == height) printf("*"); else if ((i >= height / 2) && (j == counter || j == height - counter - 1)) printf("*"); else printf(" "); } if (i >= height / 2) { counter++; } printf("\n"); }} // Function to print the pattern of 'X'void printX(){ int i, j, counter = 0; for (i = 0; i <= height; i++) { for (j = 0; j <= height; j++) { if (j == counter || j == height - counter) printf("*"); else printf(" "); } counter++; printf("\n"); }} // Function to print the pattern of 'Y'void printY(){ int i, j, counter = 0; for (i = 0; i < height; i++) { for (j = 0; j <= height; j++) { if (j == counter || j == height - counter && i <= height / 2) printf("*"); else printf(" "); } printf("\n"); if (i < height / 2) counter++; }} // Function to print the pattern of 'Z'void printZ(){ int i, j, counter = height - 1; for (i = 0; i < height; i++) { for (j = 0; j < height; j++) { if (i == 0 || i == height - 1 || j == counter) printf("*"); else printf(" "); } counter--; printf("\n"); }} // Function print the pattern of the// alphabets from A to Zvoid printPattern(char character){ switch (character) { case 'A': printA(); break; case 'B': printB(); break; case 'C': printC(); break; case 'D': printD(); break; case 'E': printE(); break; case 'F': printF(); break; case 'G': printG(); break; case 'H': printH(); break; case 'I': printI(); break; case 'J': printJ(); break; case 'K': printK(); break; case 'L': printL(); break; case 'M': printM(); break; case 'N': printN(); break; case 'O': printO(); break; case 'P': printP(); break; case 'Q': printQ(); break; case 'R': printR(); break; case 'S': printS(); break; case 'T': printT(); break; case 'U': printU(); break; case 'V': printV(); break; case 'W': printW(); break; case 'X': printX(); break; case 'Y': printY(); break; case 'Z': printZ(); break; }} // Driver Codeint main(){ char character = 'A'; printPattern(character); return 0;} // Java implementation to print the// pattern of alphabets A to Z using *class GFG{ // Below height and width variable can be used// to create a user-defined sized alphabet's pattern // Number of lines for the alphabet's patternstatic int height = 5; // Number of character width in each linestatic int width = (2 * height) - 1; // Function to find the absolute value// of a number Dstatic int abs(int d){ return d < 0 ? -1 * d : d;} // Function to print the pattern of 'A'static void printA(){ int n = width / 2, i, j; for (i = 0; i < height; i++) { for (j = 0; j <= width; j++) { if (j == n || j == (width - n) || (i == height / 2 && j > n && j < (width - n))) System.out.printf("*"); else System.out.printf(" "); } System.out.printf("\n"); n--; }} // Function to print the pattern of 'B'static void printB(){ int i, j, half = (height / 2); for (i = 0; i < height; i++) { System.out.printf("*"); for (j = 0; j < width; j++) { if ((i == 0 || i == height - 1 || i == half) && j < (width - 2)) System.out.printf("*"); else if (j == (width - 2) && !(i == 0 || i == height - 1 || i == half)) System.out.printf("*"); else System.out.printf(" "); } System.out.printf("\n"); }} // Function to print the pattern of 'C'static void printC(){ int i, j; for (i = 0; i < height; i++) { System.out.printf("*"); for (j = 0; j < (height - 1); j++) { if (i == 0 || i == height - 1) System.out.printf("*"); else continue; } System.out.printf("\n"); }} // Function to print the pattern of 'D'static void printD(){ int i, j; for (i = 0; i < height; i++) { System.out.printf("*"); for (j = 0; j < height; j++) { if ((i == 0 || i == height - 1) && j < height - 1) System.out.printf("*"); else if (j == height - 1 && i != 0 && i != height - 1) System.out.printf("*"); else System.out.printf(" "); } System.out.printf("\n"); }} // Function to print the pattern of 'E'static void printE(){ int i, j; for (i = 0; i < height; i++) { System.out.printf("*"); for (j = 0; j < height; j++) { if ((i == 0 || i == height - 1) || (i == height / 2 && j <= height / 2)) System.out.printf("*"); else continue; } System.out.printf("\n"); }} // Function to print the pattern of 'F'static void printF(){ int i, j; for (i = 0; i < height; i++) { System.out.printf("*"); for (j = 0; j < height; j++) { if ((i == 0) || (i == height / 2 && j <= height / 2)) System.out.printf("*"); else continue; } System.out.printf("\n"); }} // Function to print the pattern of 'G'static void printG(){ int i, j; width--; for (i = 0; i < height; i++) { for (j = 0; j < width; j++) { if ((i == 0 || i == height - 1) && (j == 0 || j == width - 1)) System.out.printf(" "); else if (j == 0) System.out.printf("*"); else if (i == 0 && j <= height) System.out.printf("*"); else if (i == height / 2 && j > height / 2) System.out.printf("*"); else if (i > height / 2 && j == width - 1) System.out.printf("*"); else if (i == height - 1 && j < width) System.out.printf("*"); else System.out.printf(" "); } System.out.printf("\n"); }} // Function to print the pattern of 'H'static void printH(){ int i, j; for (i = 0; i < height; i++) { System.out.printf("*"); for (j = 0; j < height; j++) { if ((j == height - 1) || (i == height / 2)) System.out.printf("*"); else System.out.printf(" "); } System.out.printf("\n"); }} // Function to print the pattern of 'I'static void printI(){ int i, j; for (i = 0; i < height; i++) { for (j = 0; j < height; j++) { if (i == 0 || i == height - 1) System.out.printf("*"); else if (j == height / 2) System.out.printf("*"); else System.out.printf(" "); } System.out.printf("\n"); }} // Function to print the pattern of 'J'static void printJ(){ int i, j; for (i = 0; i < height; i++) { for (j = 0; j < height; j++) { if (i == height - 1 && (j > 0 && j < height - 1)) System.out.printf("*"); else if ((j == height - 1 && i != height - 1) || (i > (height / 2) - 1 && j == 0 && i != height - 1)) System.out.printf("*"); else System.out.printf(" "); } System.out.printf("\n"); }} // Function to print the pattern of 'K'static void printK(){ int i, j, half = height / 2, dummy = half; for (i = 0; i < height; i++) { System.out.printf("*"); for (j = 0; j <= half; j++) { if (j == abs(dummy)) System.out.printf("*"); else System.out.printf(" "); } System.out.printf("\n"); dummy--; }} // Function to print the pattern of 'L'static void printL(){ int i, j; for (i = 0; i < height; i++) { System.out.printf("*"); for (j = 0; j <= height; j++) { if (i == height - 1) System.out.printf("*"); else System.out.printf(" "); } System.out.printf("\n"); }} // Function to print the pattern of 'M'static void printM(){ int i, j, counter = 0; for (i = 0; i < height; i++) { System.out.printf("*"); for (j = 0; j <= height; j++) { if (j == height) System.out.printf("*"); else if (j == counter || j == height - counter - 1) System.out.printf("*"); else System.out.printf(" "); } if (counter == height / 2) { counter = -99999; } else counter++; System.out.printf("\n"); }} // Function to print the pattern of 'N'static void printN(){ int i, j, counter = 0; for (i = 0; i < height; i++) { System.out.printf("*"); for (j = 0; j <= height; j++) { if (j == height) System.out.printf("*"); else if (j == counter) System.out.printf("*"); else System.out.printf(" "); } counter++; System.out.printf("\n"); }} // Function to print the pattern of 'O'static void printO(){ int i, j, space = (height / 3); int width = height / 2 + height / 5 + space + space; for (i = 0; i < height; i++) { for (j = 0; j <= width; j++) { if (j == width - abs(space) || j == abs(space)) System.out.printf("*"); else if ((i == 0 || i == height - 1) && j > abs(space) && j < width - abs(space)) System.out.printf("*"); else System.out.printf(" "); } if (space != 0 && i < height / 2) { space--; } else if (i >= (height / 2 + height / 5)) space--; System.out.printf("\n"); }} // Function to print the pattern of 'P'static void printP(){ int i, j; for (i = 0; i < height; i++) { System.out.printf("*"); for (j = 0; j < height; j++) { if ((i == 0 || i == height / 2) && j < height - 1) System.out.printf("*"); else if (i < height / 2 && j == height - 1 && i != 0) System.out.printf("*"); else System.out.printf(" "); } System.out.printf("\n"); }} // Function to print the pattern of 'Q'static void printQ(){ printO(); int i, j, d = height; for (i = 0; i < height / 2; i++) { for (j = 0; j <= d; j++) { if (j == d) System.out.printf("*"); else System.out.printf(" "); } System.out.printf("\n"); d++; }} // Function to print the pattern of 'R'static void printR(){ int i, j, half = (height / 2); for (i = 0; i < height; i++) { System.out.printf("*"); for (j = 0; j < width; j++) { if ((i == 0 || i == half) && j < (width - 2)) System.out.printf("*"); else if (j == (width - 2) && !(i == 0 || i == half)) System.out.printf("*"); else System.out.printf(" "); } System.out.printf("\n"); }} // Function to print the pattern of 'S'static void printS(){ int i, j; for (i = 0; i < height; i++) { for (j = 0; j < height; j++) { if ((i == 0 || i == height / 2 || i == height - 1)) System.out.printf("*"); else if (i < height / 2 && j == 0) System.out.printf("*"); else if (i > height / 2 && j == height - 1) System.out.printf("*"); else System.out.printf(" "); } System.out.printf("\n"); }} // Function to print the pattern of 'T'static void printT(){ int i, j; for (i = 0; i < height; i++) { for (j = 0; j < height; j++) { if (i == 0) System.out.printf("*"); else if (j == height / 2) System.out.printf("*"); else System.out.printf(" "); } System.out.printf("\n"); }} // Function to print the pattern of 'U'static void printU(){ int i, j; for (i = 0; i < height; i++) { if (i != 0 && i != height - 1) System.out.printf("*"); else System.out.printf(" "); for (j = 0; j < height; j++) { if (((i == height - 1) && j >= 0 && j < height - 1)) System.out.printf("*"); else if (j == height - 1 && i != 0 && i != height - 1) System.out.printf("*"); else System.out.printf(" "); } System.out.printf("\n"); }} // Function to print the pattern of 'V'static void printV(){ int i, j, counter = 0; for (i = 0; i < height; i++) { for (j = 0; j <= width; j++) { if (j == counter || j == width - counter - 1) System.out.printf("*"); else System.out.printf(" "); } counter++; System.out.printf("\n"); }} // Function to print the pattern of 'W'static void printW(){ int i, j, counter = height / 2; for (i = 0; i < height; i++) { System.out.printf("*"); for (j = 0; j <= height; j++) { if (j == height) System.out.printf("*"); else if ((i >= height / 2) && (j == counter || j == height - counter - 1)) System.out.printf("*"); else System.out.printf(" "); } if (i >= height / 2) { counter++; } System.out.printf("\n"); }} // Function to print the pattern of 'X'static void printX(){ int i, j, counter = 0; for (i = 0; i <= height; i++) { for (j = 0; j <= height; j++) { if (j == counter || j == height - counter) System.out.printf("*"); else System.out.printf(" "); } counter++; System.out.printf("\n"); }} // Function to print the pattern of 'Y'static void printY(){ int i, j, counter = 0; for (i = 0; i < height; i++) { for (j = 0; j <= height; j++) { if (j == counter || j == height - counter && i <= height / 2) System.out.printf("*"); else System.out.printf(" "); } System.out.printf("\n"); if (i < height / 2) counter++; }} // Function to print the pattern of 'Z'static void printZ(){ int i, j, counter = height - 1; for (i = 0; i < height; i++) { for (j = 0; j < height; j++) { if (i == 0 || i == height - 1 || j == counter) System.out.printf("*"); else System.out.printf(" "); } counter--; System.out.printf("\n"); }} // Function print the pattern of the// alphabets from A to Zstatic void printPattern(char character){ switch (character) { case 'A': printA(); break; case 'B': printB(); break; case 'C': printC(); break; case 'D': printD(); break; case 'E': printE(); break; case 'F': printF(); break; case 'G': printG(); break; case 'H': printH(); break; case 'I': printI(); break; case 'J': printJ(); break; case 'K': printK(); break; case 'L': printL(); break; case 'M': printM(); break; case 'N': printN(); break; case 'O': printO(); break; case 'P': printP(); break; case 'Q': printQ(); break; case 'R': printR(); break; case 'S': printS(); break; case 'T': printT(); break; case 'U': printU(); break; case 'V': printV(); break; case 'W': printW(); break; case 'X': printX(); break; case 'Y': printY(); break; case 'Z': printZ(); break; }} // Driver Codepublic static void main(String[] args){ char character = 'A'; printPattern(character);}} // This code is contributed by PrinciRaj1992 # Python implementation to print the# pattern of alphabets A to Z using * # Below height and width variable can be used# to create a user-defined sized alphabet's pattern # Number of lines for the alphabet's pattern height = 5 # Number of character width in each line width = (2 * height) - 1 # Function to find the absolute value# of a number D def abs(d): if d < 0: return -1*d else: return d # Function to print the pattern of 'A' def printA(): n = width // 2 for i in range(0, height): for j in range(0, width+1): if (j == n or j == (width - n) or (i == (height // 2) and j > n and j < (width - n))): print("*", end="") else: print(end=" ") print() n = n-1 # Function to print the pattern of 'B'def printB() : half = height // 2 for i in range(0,height) : print("*",end="") for j in range(0,width) : if ((i == 0 or i == height - 1 or i == half) and j < (width - 2)) : print("*",end="") elif (j == (width - 2) and not(i == 0 or i == height - 1 or i == half)) : print("*",end="") else : print(end=" ") print() # Function to print the pattern of 'C'def printC() : for i in range(0,height) : print("*",end="") for j in range(0,height - 1) : if (i == 0 or i == height - 1 ) : print("*",end="") else : continue print() # Function to print the pattern of 'D'def printD() : for i in range(0,height) : print("*",end="") for j in range(0,height) : if ( (i == 0 or i == height - 1) and j < height - 1 ): print("*",end="") elif (j == height - 1 and i != 0 and i != height - 1) : print("*",end="") else : print(end=" ") print() # Function to print the pattern of 'E'def printE() : for i in range(0,height) : print("*",end="") for j in range(0,height) : if ( (i == 0 or i == height - 1) or (i == height // 2 and j <= height // 2) ): print("*",end="") else : continue print() # Function to print the pattern of 'F'def printF() : for i in range(0,height) : print("*",end="") for j in range(0,height) : if ( (i == 0) or (i == height // 2 and j <= height // 2) ): print("*",end="") else : continue print() # Function to print the pattern of 'G'def printG() : for i in range(0,height) : for j in range(0,width-1) : if ((i == 0 or i == height - 1) and (j == 0 or j == width - 2)) : print(end=" ") elif (j == 0) : print("*",end="") elif (i == 0 and j <= height) : print("*",end="") elif (i == height // 2 and j > height // 2) : print("*",end="") elif (i > height // 2 and j == width - 2) : print("*",end="") elif (i == height - 1 and j < width - 1 ) : print("*",end="") else : print(end=" ") print() # Function to print the pattern of 'H'def printH() : for i in range(0,height) : print("*",end="") for j in range(0,height) : if ( (j == height - 1) or (i == height // 2) ): print("*",end="") else : print(end=" ") print() # Function to print the pattern of 'I'def printI() : for i in range(0,height) : for j in range(0,height) : if ( i == 0 or i == height - 1 ): print("*",end="") elif ( j == height // 2 ) : print("*",end="") else : print(end=" ") print() # Function to print the pattern of 'J'def printJ() : for i in range(0,height) : for j in range(0,height) : if ( i == height - 1 and (j > 0 and j < height - 1) ): print("*",end="") elif ( (j == height - 1 and i != height - 1) or (i > (height // 2) - 1 and j == 0 and i != height - 1) ) : print("*",end="") else : print(end=" ") print() # Function to print the pattern of 'K'def printK() : half = height // 2 dummy = half for i in range(0,height) : print("*",end="") for j in range(0,half+1) : if ( j == abs(dummy) ): print("*",end="") else : print(end=" ") print() dummy = dummy -1 # Function to print the pattern of 'L'def printL() : for i in range(0,height) : print("*",end="") for j in range(0,height+1) : if ( i == height - 1 ): print("*",end="") else : print(end=" ") print() # Function to print the pattern of 'M'def printM() : counter = 0 for i in range(0,height) : print("*",end="") for j in range(0,height+1) : if ( j == height ): print("*",end="") elif ( j == counter or j == height - counter - 1 ) : print("*",end="") else : print(end=" ") if(counter == height // 2) : counter = -99999 else : counter = counter + 1 print() # Function to print the pattern of 'N'def printN() : counter = 0 for i in range(0,height) : print("*",end="") for j in range(0,height+1) : if ( j == height ): print("*",end="") elif ( j == counter) : print("*",end="") else : print(end=" ") counter = counter + 1 print() # Function to print the pattern of 'O'def printO() : space = height // 3 width = height // 2 + height // 5 + space + space for i in range(0,height) : for j in range(0,width + 1) : if ( j == width - abs(space) or j == abs(space)): print("*",end="") elif( (i == 0 or i == height - 1) and j > abs(space) and j < width - abs(space) ) : print("*",end="") else : print(end=" ") if( space != 0 and i < height // 2) : space = space -1 elif ( i >= (height // 2 + height // 5) ) : space = space -1 print() # Function to print the pattern of 'P'def printP() : for i in range(0,height) : print("*",end="") for j in range(0,height) : if ( (i == 0 or i == height // 2) and j < height - 1 ): print("*",end="") elif ( i < height // 2 and j == height - 1 and i != 0 ) : print("*",end="") else : print(end=" ") print() # Function to print the pattern of 'Q'def printQ() : printO() d = height for i in range(0,height//2) : for j in range(0,d+1) : if ( j == d ): print("*",end="") else : print(end=" ") print() d = d+1 # Function to print the pattern of 'R'def printR() : half = (height // 2) for i in range(0,height) : print("*",end="") for j in range(0,width) : if ( (i == 0 or i == half) and j < (width - 2) ): print("*",end="") elif ( j == (width - 2) and not(i == 0 or i == half) ) : print("*",end="") else : print(end=" ") print() # Function to print the pattern of 'S'def printS() : for i in range(0,height) : for j in range(0,height) : if ( (i == 0 or i == height // 2 or i == height - 1) ): print("*",end="") elif ( i < height // 2 and j == 0 ) : print("*",end="") elif ( i > height // 2 and j == height - 1 ) : print("*",end="") else : print(end=" ") print() # Function to print the pattern of 'T'def printT() : for i in range(0,height) : for j in range(0,height) : if ( i == 0 ): print("*",end="") elif ( j == height // 2 ) : print("*",end="") else : print(end=" ") print() # Function to print the pattern of 'U'def printU() : for i in range(0,height) : if (i != 0 and i != height - 1) : print("*",end="") else : print(end = " ") for j in range(0,height) : if ( ((i == height - 1) and j >= 0 and j < height - 1) ): print("*",end="") elif ( j == height - 1 and i != 0 and i != height - 1 ) : print("*",end="") else : print(end=" ") print() # Function to print the pattern of 'V'def printV() : counter = 0 for i in range(0,height) : for j in range(0,width+1) : if ( j == counter or j == width - counter - 1 ): print("*",end="") else : print(end=" ") counter = counter + 1 print() # Function to print the pattern of 'W'def printW() : counter = height // 2 for i in range(0,height) : print("*",end="") for j in range(0,height+1) : if ( j == height ): print("*",end="") elif ( (i >= height // 2) and (j == counter or j == height - counter - 1) ) : print("*",end="") else : print(end=" ") if( i >= height // 2) : counter = counter + 1 print() # Function to print the pattern of 'X'def printX() : counter = 0 for i in range(0,height+1) : for j in range(0,height+1) : if ( j == counter or j == height - counter ): print("*",end="") else : print(end=" ") counter = counter + 1 print() # Function to print the pattern of 'Y'def printY() : counter = 0 for i in range(0,height) : for j in range(0,height+1) : if ( j == counter or j == height - counter and i <= height // 2 ): print("*",end="") else : print(end=" ") print() if (i < height // 2) : counter = counter + 1 # Function to print the pattern of 'Z'def printZ() : counter = height - 1 for i in range(0,height) : for j in range(0,height) : if ( i == 0 or i == height - 1 or j == counter ): print("*",end="") else : print(end=" ") counter = counter - 1 print() # Function print the pattern of the# alphabets from A to Z def printPattern(character) : if character == 'A' : return printA() elif character == 'B': return printB() elif character == 'C': return printC() elif character == 'D': return printD() elif character == 'E': return printE(), elif character == 'F': return printF(), elif character == 'G': return printG(), elif character == 'H': return printH(), elif character == 'I': return printI(), elif character == 'J': return printJ(), elif character == 'K': return printK(), elif character == 'L': return printL(), elif character == 'M': return printM(), elif character == 'N': return printN(), elif character == 'O': return printO(), elif character == 'P': return printP(), elif character == 'Q': return printQ(), elif character == 'R': return printR(), elif character == 'S': return printS(), elif character == 'T': return printT(), elif character == 'U': return printU(), elif character == 'V': return printV(), elif character == 'W': return printW(), elif character == 'X': return printX(), elif character == 'Y': return printY() else : printZ() # Driver Codeif __name__ == "__main__": character = 'A' printPattern(character) # This code is contributed by rakeshsahni // C# implementation to print the// pattern of alphabets A to Z using *using System; class GFG{ // Below height and width variable can be used// to create a user-defined sized alphabet's pattern // Number of lines for the alphabet's patternstatic int height = 5; // Number of character width in each linestatic int width = (2 * height) - 1; // Function to find the absolute value// of a number Dstatic int abs(int d){ return d < 0 ? -1 * d : d;} // Function to print the pattern of 'A'static void printA(){ int n = width / 2, i, j; for (i = 0; i < height; i++) { for (j = 0; j <= width; j++) { if (j == n || j == (width - n) || (i == height / 2 && j > n && j < (width - n))) Console.Write("*"); else Console.Write(" "); } Console.Write("\n"); n--; }} // Function to print the pattern of 'B'static void printB(){ int i, j, half = (height / 2); for (i = 0; i < height; i++) { Console.Write("*"); for (j = 0; j < width; j++) { if ((i == 0 || i == height - 1 || i == half) && j < (width - 2)) Console.Write("*"); else if (j == (width - 2) && !(i == 0 || i == height - 1 || i == half)) Console.Write("*"); else Console.Write(" "); } Console.Write("\n"); }} // Function to print the pattern of 'C'static void printC(){ int i, j; for (i = 0; i < height; i++) { Console.Write("*"); for (j = 0; j < (height - 1); j++) { if (i == 0 || i == height - 1) Console.Write("*"); else continue; } Console.Write("\n"); }} // Function to print the pattern of 'D'static void printD(){ int i, j; for (i = 0; i < height; i++) { Console.Write("*"); for (j = 0; j < height; j++) { if ((i == 0 || i == height - 1) && j < height - 1) Console.Write("*"); else if (j == height - 1 && i != 0 && i != height - 1) Console.Write("*"); else Console.Write(" "); } Console.Write("\n"); }} // Function to print the pattern of 'E'static void printE(){ int i, j; for (i = 0; i < height; i++) { Console.Write("*"); for (j = 0; j < height; j++) { if ((i == 0 || i == height - 1) || (i == height / 2 && j <= height / 2)) Console.Write("*"); else continue; } Console.Write("\n"); }} // Function to print the pattern of 'F'static void printF(){ int i, j; for (i = 0; i < height; i++) { Console.Write("*"); for (j = 0; j < height; j++) { if ((i == 0) || (i == height / 2 && j <= height / 2)) Console.Write("*"); else continue; } Console.Write("\n"); }} // Function to print the pattern of 'G'static void printG(){ int i, j; width--; for (i = 0; i < height; i++) { for (j = 0; j < width; j++) { if ((i == 0 || i == height - 1) && (j == 0 || j == width - 1)) Console.Write(" "); else if (j == 0) Console.Write("*"); else if (i == 0 && j <= height) Console.Write("*"); else if (i == height / 2 && j > height / 2) Console.Write("*"); else if (i > height / 2 && j == width - 1) Console.Write("*"); else if (i == height - 1 && j < width) Console.Write("*"); else Console.Write(" "); } Console.Write("\n"); }} // Function to print the pattern of 'H'static void printH(){ int i, j; for (i = 0; i < height; i++) { Console.Write("*"); for (j = 0; j < height; j++) { if ((j == height - 1) || (i == height / 2)) Console.Write("*"); else Console.Write(" "); } Console.Write("\n"); }} // Function to print the pattern of 'I'static void printI(){ int i, j; for (i = 0; i < height; i++) { for (j = 0; j < height; j++) { if (i == 0 || i == height - 1) Console.Write("*"); else if (j == height / 2) Console.Write("*"); else Console.Write(" "); } Console.Write("\n"); }} // Function to print the pattern of 'J'static void printJ(){ int i, j; for (i = 0; i < height; i++) { for (j = 0; j < height; j++) { if (i == height - 1 && (j > 0 && j < height - 1)) Console.Write("*"); else if ((j == height - 1 && i != height - 1) || (i > (height / 2) - 1 && j == 0 && i != height - 1)) Console.Write("*"); else Console.Write(" "); } Console.Write("\n"); }} // Function to print the pattern of 'K'static void printK(){ int i, j, half = height / 2, dummy = half; for (i = 0; i < height; i++) { Console.Write("*"); for (j = 0; j <= half; j++) { if (j == abs(dummy)) Console.Write("*"); else Console.Write(" "); } Console.Write("\n"); dummy--; }} // Function to print the pattern of 'L'static void printL(){ int i, j; for (i = 0; i < height; i++) { Console.Write("*"); for (j = 0; j <= height; j++) { if (i == height - 1) Console.Write("*"); else Console.Write(" "); } Console.Write("\n"); }} // Function to print the pattern of 'M'static void printM(){ int i, j, counter = 0; for (i = 0; i < height; i++) { Console.Write("*"); for (j = 0; j <= height; j++) { if (j == height) Console.Write("*"); else if (j == counter || j == height - counter - 1) Console.Write("*"); else Console.Write(" "); } if (counter == height / 2) { counter = -99999; } else counter++; Console.Write("\n"); }} // Function to print the pattern of 'N'static void printN(){ int i, j, counter = 0; for (i = 0; i < height; i++) { Console.Write("*"); for (j = 0; j <= height; j++) { if (j == height) Console.Write("*"); else if (j == counter) Console.Write("*"); else Console.Write(" "); } counter++; Console.Write("\n"); }} // Function to print the pattern of 'O'static void printO(){ int i, j, space = (height / 3); int width = height / 2 + height / 5 + space + space; for (i = 0; i < height; i++) { for (j = 0; j <= width; j++) { if (j == width - abs(space) || j == abs(space)) Console.Write("*"); else if ((i == 0 || i == height - 1) && j > abs(space) && j < width - abs(space)) Console.Write("*"); else Console.Write(" "); } if (space != 0 && i < height / 2) { space--; } else if (i >= (height / 2 + height / 5)) space--; Console.Write("\n"); }} // Function to print the pattern of 'P'static void printP(){ int i, j; for (i = 0; i < height; i++) { Console.Write("*"); for (j = 0; j < height; j++) { if ((i == 0 || i == height / 2) && j < height - 1) Console.Write("*"); else if (i < height / 2 && j == height - 1 && i != 0) Console.Write("*"); else Console.Write(" "); } Console.Write("\n"); }} // Function to print the pattern of 'Q'static void printQ(){ printO(); int i, j, d = height; for (i = 0; i < height / 2; i++) { for (j = 0; j <= d; j++) { if (j == d) Console.Write("*"); else Console.Write(" "); } Console.Write("\n"); d++; }} // Function to print the pattern of 'R'static void printR(){ int i, j, half = (height / 2); for (i = 0; i < height; i++) { Console.Write("*"); for (j = 0; j < width; j++) { if ((i == 0 || i == half) && j < (width - 2)) Console.Write("*"); else if (j == (width - 2) && !(i == 0 || i == half)) Console.Write("*"); else Console.Write(" "); } Console.Write("\n"); }} // Function to print the pattern of 'S'static void printS(){ int i, j; for (i = 0; i < height; i++) { for (j = 0; j < height; j++) { if ((i == 0 || i == height / 2 || i == height - 1)) Console.Write("*"); else if (i < height / 2 && j == 0) Console.Write("*"); else if (i > height / 2 && j == height - 1) Console.Write("*"); else Console.Write(" "); } Console.Write("\n"); }} // Function to print the pattern of 'T'static void printT(){ int i, j; for (i = 0; i < height; i++) { for (j = 0; j < height; j++) { if (i == 0) Console.Write("*"); else if (j == height / 2) Console.Write("*"); else Console.Write(" "); } Console.Write("\n"); }} // Function to print the pattern of 'U'static void printU(){ int i, j; for (i = 0; i < height; i++) { if (i != 0 && i != height - 1) Console.Write("*"); else Console.Write(" "); for (j = 0; j < height; j++) { if (((i == height - 1) && j >= 0 && j < height - 1)) Console.Write("*"); else if (j == height - 1 && i != 0 && i != height - 1) Console.Write("*"); else Console.Write(" "); } Console.Write("\n"); }} // Function to print the pattern of 'V'static void printV(){ int i, j, counter = 0; for (i = 0; i < height; i++) { for (j = 0; j <= width; j++) { if (j == counter || j == width - counter - 1) Console.Write("*"); else Console.Write(" "); } counter++; Console.Write("\n"); }} // Function to print the pattern of 'W'static void printW(){ int i, j, counter = height / 2; for (i = 0; i < height; i++) { Console.Write("*"); for (j = 0; j <= height; j++) { if (j == height) Console.Write("*"); else if ((i >= height / 2) && (j == counter || j == height - counter - 1)) Console.Write("*"); else Console.Write(" "); } if (i >= height / 2) { counter++; } Console.Write("\n"); }} // Function to print the pattern of 'X'static void printX(){ int i, j, counter = 0; for (i = 0; i <= height; i++) { for (j = 0; j <= height; j++) { if (j == counter || j == height - counter) Console.Write("*"); else Console.Write(" "); } counter++; Console.Write("\n"); }} // Function to print the pattern of 'Y'static void printY(){ int i, j, counter = 0; for (i = 0; i < height; i++) { for (j = 0; j <= height; j++) { if (j == counter || j == height - counter && i <= height / 2) Console.Write("*"); else Console.Write(" "); } Console.Write("\n"); if (i < height / 2) counter++; }} // Function to print the pattern of 'Z'static void printZ(){ int i, j, counter = height - 1; for (i = 0; i < height; i++) { for (j = 0; j < height; j++) { if (i == 0 || i == height - 1 || j == counter) Console.Write("*"); else Console.Write(" "); } counter--; Console.Write("\n"); }} // Function print the pattern of the// alphabets from A to Zstatic void printPattern(char character){ switch (character) { case 'A': printA(); break; case 'B': printB(); break; case 'C': printC(); break; case 'D': printD(); break; case 'E': printE(); break; case 'F': printF(); break; case 'G': printG(); break; case 'H': printH(); break; case 'I': printI(); break; case 'J': printJ(); break; case 'K': printK(); break; case 'L': printL(); break; case 'M': printM(); break; case 'N': printN(); break; case 'O': printO(); break; case 'P': printP(); break; case 'Q': printQ(); break; case 'R': printR(); break; case 'S': printS(); break; case 'T': printT(); break; case 'U': printU(); break; case 'V': printV(); break; case 'W': printW(); break; case 'X': printX(); break; case 'Y': printY(); break; case 'Z': printZ(); break; }} // Driver Codepublic static void Main(String[] args){ char character = 'A'; printPattern(character);}} // This code is contributed by PrinciRaj1992 <script> // JavaScript implementation to print the // pattern of alphabets A to Z using * // Below height and width variable can be used // to create a user-defined sized alphabet's pattern // Number of lines for the alphabet's pattern let height = 5; // Number of character width in each line let width = (2 * height) - 1; // Function to find the absolute value // of a number D const abs = (d) => { return d < 0 ? -1 * d : d; } // Function to print the pattern of 'A' const printA = () => { let n = parseInt(width / 2), i, j; for (i = 0; i < height; i++) { for (j = 0; j <= width; j++) { if (j == n || j == (width - n) || (i == parseInt(height / 2) && j > n && j < (width - n))) document.write("*"); else document.write(" "); } document.write(`<br/>`); n--; } } // Function to print the pattern of 'B' const printB = () => { let i, j, half = parseInt(height / 2); for (i = 0; i < height; i++) { document.write("*"); for (j = 0; j < width; j++) { if ((i == 0 || i == height - 1 || i == half) && j < (width - 2)) document.write("*"); else if (j == (width - 2) && !(i == 0 || i == height - 1 || i == half)) document.write("*"); else document.write(" "); } document.write(`<br/>`); } } // Function to print the pattern of 'C' const printC = () => { let i, j; for (i = 0; i < height; i++) { document.write("*"); for (j = 0; j < (height - 1); j++) { if (i == 0 || i == height - 1) document.write("*"); else continue; } document.write(`<br/>`); } } // Function to print the pattern of 'D' const printD = () => { let i, j; for (i = 0; i < height; i++) { document.write("*"); for (j = 0; j < height; j++) { if ((i == 0 || i == height - 1) && j < height - 1) document.write("*"); else if (j == height - 1 && i != 0 && i != height - 1) document.write("*"); else document.write(" "); } document.write(`<br/>`); } } // Function to print the pattern of 'E' const printE = () => { let i, j; for (i = 0; i < height; i++) { document.write("*"); for (j = 0; j < height; j++) { if ((i == 0 || i == height - 1) || (i == parseInt(height / 2) && j <= parseInt(height / 2))) document.write("*"); else continue; } document.write(`<br/>`); } } // Function to print the pattern of 'F' const printF = () => { let i, j; for (i = 0; i < height; i++) { document.write("*"); for (j = 0; j < height; j++) { if ((i == 0) || (i == parseInt(height / 2) && j <= parseInt(height / 2))) document.write("*"); else continue; } document.write(`<br/>`); } } // Function to print the pattern of 'G' const printG = () => { let i, j; width--; for (i = 0; i < height; i++) { for (j = 0; j < width; j++) { if ((i == 0 || i == height - 1) && (j == 0 || j == width - 1)) document.write(" "); else if (j == 0) document.write("*"); else if (i == 0 && j <= height) document.write("*"); else if (i == parseInt(height / 2) && j > parseInt(height / 2)) document.write("*"); else if (i > parseInt(height / 2) && j == width - 1) document.write("*"); else if (i == height - 1 && j < width) document.write("*"); else document.write(" "); } document.write(`<br/>`); } } // Function to print the pattern of 'H' const printH = () => { let i, j; for (i = 0; i < height; i++) { document.write("*"); for (j = 0; j < height; j++) { if ((j == height - 1) || (i == parseInt(height / 2))) document.write("*"); else document.write(" "); } document.write(`<br/>`); } } // Function to print the pattern of 'I' const printI = () => { let i, j; for (i = 0; i < height; i++) { for (j = 0; j < height; j++) { if (i == 0 || i == height - 1) document.write("*"); else if (j == parseInt(height / 2)) document.write("*"); else document.write(" "); } document.write(`<br/>`); } } // Function to print the pattern of 'J' const printJ = () => { let i, j; for (i = 0; i < height; i++) { for (j = 0; j < height; j++) { if (i == height - 1 && (j > 0 && j < height - 1)) document.write("*"); else if ((j == height - 1 && i != height - 1) || (i > parseInt(height / 2) - 1 && j == 0 && i != height - 1)) document.write("*"); else document.write(" "); } document.write(`<br/>`); } } // Function to print the pattern of 'K' const printK = () => { let i, j, half = parseInt(height / 2), dummy = half; for (i = 0; i < height; i++) { document.write("*"); for (j = 0; j <= half; j++) { if (j == abs(dummy)) document.write("*"); else document.write(" "); } document.write(`<br/>`); dummy--; } } // Function to print the pattern of 'L' const printL = () => { let i, j; for (i = 0; i < height; i++) { document.write("*"); for (j = 0; j <= height; j++) { if (i == height - 1) document.write("*"); else document.write(" "); } document.write(`<br/>`); } } // Function to print the pattern of 'M' const printM = () => { let i, j, counter = 0; for (i = 0; i < height; i++) { document.write("*"); for (j = 0; j <= height; j++) { if (j == height) document.write("*"); else if (j == counter || j == height - counter - 1) document.write("*"); else document.write(" "); } if (counter == parseInt(height / 2)) { counter = -99999; } else counter++; document.write(`<br/>`); } } // Function to print the pattern of 'N' const printN = () => { let i, j, counter = 0; for (i = 0; i < height; i++) { document.write("*"); for (j = 0; j <= height; j++) { if (j == height) document.write("*"); else if (j == counter) document.write("*"); else document.write(" "); } counter++; document.write(`<br/>`); } } // Function to print the pattern of 'O' const printO = () => { let i, j, space = parseInt(height / 3); let width = parseInt(height / 2) + parseInt(height / 5) + space + space; for (i = 0; i < height; i++) { for (j = 0; j <= width; j++) { if (j == width - abs(space) || j == abs(space)) document.write("*"); else if ((i == 0 || i == height - 1) && j > abs(space) && j < width - abs(space)) document.write("*"); else document.write(" "); } if (space != 0 && i < parseInt(height / 2)) { space--; } else if (i >= (parseInt(height / 2) + parseInt(height / 5))) space--; document.write(`<br/>`); } } // Function to print the pattern of 'P' const printP = () => { let i, j; for (i = 0; i < height; i++) { document.write("*"); for (j = 0; j < height; j++) { if ((i == 0 || i == parseInt(height / 2)) && j < height - 1) document.write("*"); else if (i < parseInt(height / 2) && j == height - 1 && i != 0) document.write("*"); else document.write(" "); } document.write(`<br/>`); } } // Function to print the pattern of 'Q' const printQ = () => { printO(); let i, j, d = height; for (i = 0; i < parseInt(height / 2); i++) { for (j = 0; j <= d; j++) { if (j == d) document.write("*"); else document.write(" "); } document.write(`<br/>`); d++; } } // Function to print the pattern of 'R' const printR = () => { let i, j, half = parseInt(height / 2); for (i = 0; i < height; i++) { document.write("*"); for (j = 0; j < width; j++) { if ((i == 0 || i == half) && j < (width - 2)) document.write("*"); else if (j == (width - 2) && !(i == 0 || i == half)) document.write("*"); else document.write(" "); } document.write(`<br/>`); } } // Function to print the pattern of 'S' const printS = () => { let i, j; for (i = 0; i < height; i++) { for (j = 0; j < height; j++) { if ((i == 0 || i == parseInt(height / 2) || i == height - 1)) document.write("*"); else if (i < parseInt(height / 2) && j == 0) document.write("*"); else if (i > parseInt(height / 2) && j == height - 1) document.write("*"); else document.write(" "); } document.write(`<br/>`); } } // Function to print the pattern of 'T' const printT = () => { let i, j; for (i = 0; i < height; i++) { for (j = 0; j < height; j++) { if (i == 0) document.write("*"); else if (j == parseInt(height / 2)) document.write("*"); else document.write(" "); } document.write(`<br/>`); } } // Function to print the pattern of 'U' const printU = () => { let i, j; for (i = 0; i < height; i++) { if (i != 0 && i != height - 1) document.write("*"); else document.write(" "); for (j = 0; j < height; j++) { if (((i == height - 1) && j >= 0 && j < height - 1)) document.write("*"); else if (j == height - 1 && i != 0 && i != height - 1) document.write("*"); else document.write(" "); } document.write(`<br/>`); } } // Function to print the pattern of 'V' const printV = () => { let i, j, counter = 0; for (i = 0; i < height; i++) { for (j = 0; j <= width; j++) { if (j == counter || j == width - counter - 1) document.write("*"); else document.write(" "); } counter++; document.write(`<br/>`); } } // Function to print the pattern of 'W' const printW = () => { let i, j, counter = parseInt(height / 2); for (i = 0; i < height; i++) { document.write("*"); for (j = 0; j <= height; j++) { if (j == height) document.write("*"); else if ((i >= parseInt(height / 2)) && (j == counter || j == height - counter - 1)) document.write("*"); else document.write(" "); } if (i >= parseInt(height / 2)) { counter++; } document.write(`<br/>`); } } // Function to print the pattern of 'X' const printX = () => { let i, j, counter = 0; for (i = 0; i <= height; i++) { for (j = 0; j <= height; j++) { if (j == counter || j == height - counter) document.write("*"); else document.write(" "); } counter++; document.write(`<br/>`); } } // Function to print the pattern of 'Y' const printY = () => { let i, j, counter = 0; for (i = 0; i < height; i++) { for (j = 0; j <= height; j++) { if (j == counter || j == height - counter && i <= parseInt(height / 2)) document.write("*"); else document.write(" "); } document.write(`<br/>`); if (i < parseInt(height / 2)) counter++; } } // Function to print the pattern of 'Z' const printZ = () => { let i, j, counter = height - 1; for (i = 0; i < height; i++) { for (j = 0; j < height; j++) { if (i == 0 || i == height - 1 || j == counter) document.write("*"); else document.write(" "); } counter--; document.write(`<br/>`); } } // Function print the pattern of the // alphabets from A to Z const printPattern = (character) => { switch (character) { case 'A': printA(); break; case 'B': printB(); break; case 'C': printC(); break; case 'D': printD(); break; case 'E': printE(); break; case 'F': printF(); break; case 'G': printG(); break; case 'H': printH(); break; case 'I': printI(); break; case 'J': printJ(); break; case 'K': printK(); break; case 'L': printL(); break; case 'M': printM(); break; case 'N': printN(); break; case 'O': printO(); break; case 'P': printP(); break; case 'Q': printQ(); break; case 'R': printR(); break; case 'S': printS(); break; case 'T': printT(); break; case 'U': printU(); break; case 'V': printV(); break; case 'W': printW(); break; case 'X': printX(); break; case 'Y': printY(); break; case 'Z': printZ(); break; } } // Driver Code let character = 'A'; printPattern(character); // This code is contributed by rakeshsahni </script> ** * * ****** * * * * princiraj1992 kk773572498 rakeshsahni shivanisinghss2110 pattern-printing Technical Scripter 2019 School Programming Technical Scripter pattern-printing Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Interfaces in Java Operator Overloading in C++ Constructors in C++ Copy Constructor in C++ Overriding in Java C++ Data Types Friend class and function in C++ Types of Operating Systems Different ways of Reading a text file in Java Polymorphism in C++
[ { "code": null, "e": 24332, "s": 24304, "text": "\n17 Aug, 2021" }, { "code": null, "e": 24434, "s": 24332, "text": "Given any alphabet between A to Z, the task is to print the pattern of the given alphabet using star." }, { "code": null, "e": 24445, "s": 24434, "text": "Examples: " }, { "code": null, "e": 24573, "s": 24445, "text": "Input: A\nOutput: \n ** \n * * \n ****** \n * * \n* *\n\nInput: P\nOutput:\n***** \n* *\n***** \n* \n* " }, { "code": null, "e": 24749, "s": 24573, "text": "Approach: The code to print each alphabet is created in a separate function. Use switch statement to call the desired function on the basis of the alphabet’s pattern required." }, { "code": null, "e": 24780, "s": 24749, "text": "Below is the implementation. " }, { "code": null, "e": 24784, "s": 24780, "text": "C++" }, { "code": null, "e": 24786, "s": 24784, "text": "C" }, { "code": null, "e": 24791, "s": 24786, "text": "Java" }, { "code": null, "e": 24799, "s": 24791, "text": "Python3" }, { "code": null, "e": 24802, "s": 24799, "text": "C#" }, { "code": null, "e": 24813, "s": 24802, "text": "Javascript" }, { "code": "// C++ implementation to print the// pattern of alphabets A to Z using * #include <iostream>using namespace std; // Below height and width variable can be used// to create a user-defined sized alphabet's pattern // Number of lines for the alphabet's patternint height = 5;// Number of character width in each lineint width = (2 * height) - 1; // Function to find the absolute value// of a number Dint abs(int d){ return d < 0 ? -1 * d : d;} // Function to print the pattern of 'A'void printA(){ int n = width / 2, i, j; for (i = 0; i < height; i++) { for (j = 0; j <= width; j++) { if (j == n || j == (width - n) || (i == height / 2 && j > n && j < (width - n))) cout <<\"*\"; else cout <<\" \"; } cout <<\"\\n\"; n--; }} // Function to print the pattern of 'B'void printB(){ int i, j, half = (height / 2); for (i = 0; i < height; i++) { cout <<\"*\"; for (j = 0; j < width; j++) { if ((i == 0 || i == height - 1 || i == half) && j < (width - 2)) cout <<\"*\"; else if (j == (width - 2) && !(i == 0 || i == height - 1 || i == half)) cout <<\"*\"; else cout <<\" \"; } cout <<\"\\n\"; }} // Function to print the pattern of 'C'void printC(){ int i, j; for (i = 0; i < height; i++) { cout <<\"*\"; for (j = 0; j < (height - 1); j++) { if (i == 0 || i == height - 1) cout <<\"*\"; else continue; } cout <<\"\\n\"; }} // Function to print the pattern of 'D'void printD(){ int i, j; for (i = 0; i < height; i++) { cout <<\"*\"; for (j = 0; j < height; j++) { if ((i == 0 || i == height - 1) && j < height - 1) cout <<\"*\"; else if (j == height - 1 && i != 0 && i != height - 1) cout <<\"*\"; else cout <<\" \"; } cout <<\"\\n\"; }} // Function to print the pattern of 'E'void printE(){ int i, j; for (i = 0; i < height; i++) { cout <<\"*\"; for (j = 0; j < height; j++) { if ((i == 0 || i == height - 1) || (i == height / 2 && j <= height / 2)) cout <<\"*\"; else continue; } cout <<\"\\n\"; }} // Function to print the pattern of 'F'void printF(){ int i, j; for (i = 0; i < height; i++) { cout <<\"*\"; for (j = 0; j < height; j++) { if ((i == 0) || (i == height / 2 && j <= height / 2)) cout <<\"*\"; else continue; } cout <<\"\\n\"; }} // Function to print the pattern of 'G'void printG(){ int i, j; width--; for (i = 0; i < height; i++) { for (j = 0; j < width; j++) { if ((i == 0 || i == height - 1) && (j == 0 || j == width - 1)) cout <<\" \"; else if (j == 0) cout <<\"*\"; else if (i == 0 && j <= height) cout <<\"*\"; else if (i == height / 2 && j > height / 2) cout <<\"*\"; else if (i > height / 2 && j == width - 1) cout <<\"*\"; else if (i == height - 1 && j < width) cout <<\"*\"; else cout <<\" \"; } cout <<\"\\n\"; }} // Function to print the pattern of 'H'void printH(){ int i, j; for (i = 0; i < height; i++) { cout <<\"*\"; for (j = 0; j < height; j++) { if ((j == height - 1) || (i == height / 2)) cout <<\"*\"; else cout <<\" \"; } cout <<\"\\n\"; }} // Function to print the pattern of 'I'void printI(){ int i, j; for (i = 0; i < height; i++) { for (j = 0; j < height; j++) { if (i == 0 || i == height - 1) cout <<\"*\"; else if (j == height / 2) cout <<\"*\"; else cout <<\" \"; } cout <<\"\\n\"; }} // Function to print the pattern of 'J'void printJ(){ int i, j; for (i = 0; i < height; i++) { for (j = 0; j < height; j++) { if (i == height - 1 && (j > 0 && j < height - 1)) cout <<\"*\"; else if ((j == height - 1 && i != height - 1) || (i > (height / 2) - 1 && j == 0 && i != height - 1)) cout <<\"*\"; else cout <<\" \"; } cout <<\"\\n\"; }} // Function to print the pattern of 'K'void printK(){ int i, j, half = height / 2, dummy = half; for (i = 0; i < height; i++) { cout <<\"*\"; for (j = 0; j <= half; j++) { if (j == abs(dummy)) cout <<\"*\"; else cout <<\" \"; } cout <<\"\\n\"; dummy--; }} // Function to print the pattern of 'L'void printL(){ int i, j; for (i = 0; i < height; i++) { cout <<\"*\"; for (j = 0; j <= height; j++) { if (i == height - 1) cout <<\"*\"; else cout <<\" \"; } cout <<\"\\n\"; }} // Function to print the pattern of 'M'void printM(){ int i, j, counter = 0; for (i = 0; i < height; i++) { cout <<\"*\"; for (j = 0; j <= height; j++) { if (j == height) cout <<\"*\"; else if (j == counter || j == height - counter - 1) cout <<\"*\"; else cout <<\" \"; } if (counter == height / 2) { counter = -99999; } else counter++; cout <<\"\\n\"; }} // Function to print the pattern of 'N'void printN(){ int i, j, counter = 0; for (i = 0; i < height; i++) { cout <<\"*\"; for (j = 0; j <= height; j++) { if (j == height) cout <<\"*\"; else if (j == counter) cout <<\"*\"; else cout <<\" \"; } counter++; cout <<\"\\n\"; }} // Function to print the pattern of 'O'void printO(){ int i, j, space = (height / 3); int width = height / 2 + height / 5 + space + space; for (i = 0; i < height; i++) { for (j = 0; j <= width; j++) { if (j == width - abs(space) || j == abs(space)) cout <<\"*\"; else if ((i == 0 || i == height - 1) && j > abs(space) && j < width - abs(space)) cout <<\"*\"; else cout <<\" \"; } if (space != 0 && i < height / 2) { space--; } else if (i >= (height / 2 + height / 5)) space--; cout <<\"\\n\"; }} // Function to print the pattern of 'P'void printP(){ int i, j; for (i = 0; i < height; i++) { cout <<\"*\"; for (j = 0; j < height; j++) { if ((i == 0 || i == height / 2) && j < height - 1) cout <<\"*\"; else if (i < height / 2 && j == height - 1 && i != 0) cout <<\"*\"; else cout <<\" \"; } cout <<\"\\n\"; }} // Function to print the pattern of 'Q'void printQ(){ printO(); int i, j, d = height; for (i = 0; i < height / 2; i++) { for (j = 0; j <= d; j++) { if (j == d) cout <<\"*\"; else cout <<\" \"; } cout <<\"\\n\"; d++; }} // Function to print the pattern of 'R'void printR(){ int i, j, half = (height / 2); for (i = 0; i < height; i++) { cout <<\"*\"; for (j = 0; j < width; j++) { if ((i == 0 || i == half) && j < (width - 2)) cout <<\"*\"; else if (j == (width - 2) && !(i == 0 || i == half)) cout <<\"*\"; else cout <<\" \"; } cout <<\"\\n\"; }} // Function to print the pattern of 'S'void printS(){ int i, j; for (i = 0; i < height; i++) { for (j = 0; j < height; j++) { if ((i == 0 || i == height / 2 || i == height - 1)) cout <<\"*\"; else if (i < height / 2 && j == 0) cout <<\"*\"; else if (i > height / 2 && j == height - 1) cout <<\"*\"; else cout <<\" \"; } cout <<\"\\n\"; }} // Function to print the pattern of 'T'void printT(){ int i, j; for (i = 0; i < height; i++) { for (j = 0; j < height; j++) { if (i == 0) cout <<\"*\"; else if (j == height / 2) cout <<\"*\"; else cout <<\" \"; } cout <<\"\\n\"; }} // Function to print the pattern of 'U'void printU(){ int i, j; for (i = 0; i < height; i++) { if (i != 0 && i != height - 1) cout <<\"*\"; else cout <<\" \"; for (j = 0; j < height; j++) { if (((i == height - 1) && j >= 0 && j < height - 1)) cout <<\"*\"; else if (j == height - 1 && i != 0 && i != height - 1) cout <<\"*\"; else cout <<\" \"; } cout <<\"\\n\"; }} // Function to print the pattern of 'V'void printV(){ int i, j, counter = 0; for (i = 0; i < height; i++) { for (j = 0; j <= width; j++) { if (j == counter || j == width - counter - 1) cout <<\"*\"; else cout <<\" \"; } counter++; cout <<\"\\n\"; }} // Function to print the pattern of 'W'void printW(){ int i, j, counter = height / 2; for (i = 0; i < height; i++) { cout <<\"*\"; for (j = 0; j <= height; j++) { if (j == height) cout <<\"*\"; else if ((i >= height / 2) && (j == counter || j == height - counter - 1)) cout <<\"*\"; else cout <<\" \"; } if (i >= height / 2) { counter++; } cout <<\"\\n\"; }} // Function to print the pattern of 'X'void printX(){ int i, j, counter = 0; for (i = 0; i <= height; i++) { for (j = 0; j <= height; j++) { if (j == counter || j == height - counter) cout <<\"*\"; else cout <<\" \"; } counter++; cout <<\"\\n\"; }} // Function to print the pattern of 'Y'void printY(){ int i, j, counter = 0; for (i = 0; i < height; i++) { for (j = 0; j <= height; j++) { if (j == counter || j == height - counter && i <= height / 2) cout <<\"*\"; else cout <<\" \"; } cout <<\"\\n\"; if (i < height / 2) counter++; }} // Function to print the pattern of 'Z'void printZ(){ int i, j, counter = height - 1; for (i = 0; i < height; i++) { for (j = 0; j < height; j++) { if (i == 0 || i == height - 1 || j == counter) cout <<\"*\"; else cout <<\" \"; } counter--; cout <<\"\\n\"; }} // Function print the pattern of the// alphabets from A to Zvoid printPattern(char character){ switch (character) { case 'A': printA(); break; case 'B': printB(); break; case 'C': printC(); break; case 'D': printD(); break; case 'E': printE(); break; case 'F': printF(); break; case 'G': printG(); break; case 'H': printH(); break; case 'I': printI(); break; case 'J': printJ(); break; case 'K': printK(); break; case 'L': printL(); break; case 'M': printM(); break; case 'N': printN(); break; case 'O': printO(); break; case 'P': printP(); break; case 'Q': printQ(); break; case 'R': printR(); break; case 'S': printS(); break; case 'T': printT(); break; case 'U': printU(); break; case 'V': printV(); break; case 'W': printW(); break; case 'X': printX(); break; case 'Y': printY(); break; case 'Z': printZ(); break; }} // Driver Codeint main(){ char character = 'A'; printPattern(character); return 0;} // This code is contributed by shivani.", "e": 37940, "s": 24813, "text": null }, { "code": "// C++ implementation to print the// pattern of alphabets A to Z using * #include <stdio.h> // Below height and width variable can be used// to create a user-defined sized alphabet's pattern // Number of lines for the alphabet's patternint height = 5;// Number of character width in each lineint width = (2 * height) - 1; // Function to find the absolute value// of a number Dint abs(int d){ return d < 0 ? -1 * d : d;} // Function to print the pattern of 'A'void printA(){ int n = width / 2, i, j; for (i = 0; i < height; i++) { for (j = 0; j <= width; j++) { if (j == n || j == (width - n) || (i == height / 2 && j > n && j < (width - n))) printf(\"*\"); else printf(\" \"); } printf(\"\\n\"); n--; }} // Function to print the pattern of 'B'void printB(){ int i, j, half = (height / 2); for (i = 0; i < height; i++) { printf(\"*\"); for (j = 0; j < width; j++) { if ((i == 0 || i == height - 1 || i == half) && j < (width - 2)) printf(\"*\"); else if (j == (width - 2) && !(i == 0 || i == height - 1 || i == half)) printf(\"*\"); else printf(\" \"); } printf(\"\\n\"); }} // Function to print the pattern of 'C'void printC(){ int i, j; for (i = 0; i < height; i++) { printf(\"*\"); for (j = 0; j < (height - 1); j++) { if (i == 0 || i == height - 1) printf(\"*\"); else continue; } printf(\"\\n\"); }} // Function to print the pattern of 'D'void printD(){ int i, j; for (i = 0; i < height; i++) { printf(\"*\"); for (j = 0; j < height; j++) { if ((i == 0 || i == height - 1) && j < height - 1) printf(\"*\"); else if (j == height - 1 && i != 0 && i != height - 1) printf(\"*\"); else printf(\" \"); } printf(\"\\n\"); }} // Function to print the pattern of 'E'void printE(){ int i, j; for (i = 0; i < height; i++) { printf(\"*\"); for (j = 0; j < height; j++) { if ((i == 0 || i == height - 1) || (i == height / 2 && j <= height / 2)) printf(\"*\"); else continue; } printf(\"\\n\"); }} // Function to print the pattern of 'F'void printF(){ int i, j; for (i = 0; i < height; i++) { printf(\"*\"); for (j = 0; j < height; j++) { if ((i == 0) || (i == height / 2 && j <= height / 2)) printf(\"*\"); else continue; } printf(\"\\n\"); }} // Function to print the pattern of 'G'void printG(){ int i, j; width--; for (i = 0; i < height; i++) { for (j = 0; j < width; j++) { if ((i == 0 || i == height - 1) && (j == 0 || j == width - 1)) printf(\" \"); else if (j == 0) printf(\"*\"); else if (i == 0 && j <= height) printf(\"*\"); else if (i == height / 2 && j > height / 2) printf(\"*\"); else if (i > height / 2 && j == width - 1) printf(\"*\"); else if (i == height - 1 && j < width) printf(\"*\"); else printf(\" \"); } printf(\"\\n\"); }} // Function to print the pattern of 'H'void printH(){ int i, j; for (i = 0; i < height; i++) { printf(\"*\"); for (j = 0; j < height; j++) { if ((j == height - 1) || (i == height / 2)) printf(\"*\"); else printf(\" \"); } printf(\"\\n\"); }} // Function to print the pattern of 'I'void printI(){ int i, j; for (i = 0; i < height; i++) { for (j = 0; j < height; j++) { if (i == 0 || i == height - 1) printf(\"*\"); else if (j == height / 2) printf(\"*\"); else printf(\" \"); } printf(\"\\n\"); }} // Function to print the pattern of 'J'void printJ(){ int i, j; for (i = 0; i < height; i++) { for (j = 0; j < height; j++) { if (i == height - 1 && (j > 0 && j < height - 1)) printf(\"*\"); else if ((j == height - 1 && i != height - 1) || (i > (height / 2) - 1 && j == 0 && i != height - 1)) printf(\"*\"); else printf(\" \"); } printf(\"\\n\"); }} // Function to print the pattern of 'K'void printK(){ int i, j, half = height / 2, dummy = half; for (i = 0; i < height; i++) { printf(\"*\"); for (j = 0; j <= half; j++) { if (j == abs(dummy)) printf(\"*\"); else printf(\" \"); } printf(\"\\n\"); dummy--; }} // Function to print the pattern of 'L'void printL(){ int i, j; for (i = 0; i < height; i++) { printf(\"*\"); for (j = 0; j <= height; j++) { if (i == height - 1) printf(\"*\"); else printf(\" \"); } printf(\"\\n\"); }} // Function to print the pattern of 'M'void printM(){ int i, j, counter = 0; for (i = 0; i < height; i++) { printf(\"*\"); for (j = 0; j <= height; j++) { if (j == height) printf(\"*\"); else if (j == counter || j == height - counter - 1) printf(\"*\"); else printf(\" \"); } if (counter == height / 2) { counter = -99999; } else counter++; printf(\"\\n\"); }} // Function to print the pattern of 'N'void printN(){ int i, j, counter = 0; for (i = 0; i < height; i++) { printf(\"*\"); for (j = 0; j <= height; j++) { if (j == height) printf(\"*\"); else if (j == counter) printf(\"*\"); else printf(\" \"); } counter++; printf(\"\\n\"); }} // Function to print the pattern of 'O'void printO(){ int i, j, space = (height / 3); int width = height / 2 + height / 5 + space + space; for (i = 0; i < height; i++) { for (j = 0; j <= width; j++) { if (j == width - abs(space) || j == abs(space)) printf(\"*\"); else if ((i == 0 || i == height - 1) && j > abs(space) && j < width - abs(space)) printf(\"*\"); else printf(\" \"); } if (space != 0 && i < height / 2) { space--; } else if (i >= (height / 2 + height / 5)) space--; printf(\"\\n\"); }} // Function to print the pattern of 'P'void printP(){ int i, j; for (i = 0; i < height; i++) { printf(\"*\"); for (j = 0; j < height; j++) { if ((i == 0 || i == height / 2) && j < height - 1) printf(\"*\"); else if (i < height / 2 && j == height - 1 && i != 0) printf(\"*\"); else printf(\" \"); } printf(\"\\n\"); }} // Function to print the pattern of 'Q'void printQ(){ printO(); int i, j, d = height; for (i = 0; i < height / 2; i++) { for (j = 0; j <= d; j++) { if (j == d) printf(\"*\"); else printf(\" \"); } printf(\"\\n\"); d++; }} // Function to print the pattern of 'R'void printR(){ int i, j, half = (height / 2); for (i = 0; i < height; i++) { printf(\"*\"); for (j = 0; j < width; j++) { if ((i == 0 || i == half) && j < (width - 2)) printf(\"*\"); else if (j == (width - 2) && !(i == 0 || i == half)) printf(\"*\"); else printf(\" \"); } printf(\"\\n\"); }} // Function to print the pattern of 'S'void printS(){ int i, j; for (i = 0; i < height; i++) { for (j = 0; j < height; j++) { if ((i == 0 || i == height / 2 || i == height - 1)) printf(\"*\"); else if (i < height / 2 && j == 0) printf(\"*\"); else if (i > height / 2 && j == height - 1) printf(\"*\"); else printf(\" \"); } printf(\"\\n\"); }} // Function to print the pattern of 'T'void printT(){ int i, j; for (i = 0; i < height; i++) { for (j = 0; j < height; j++) { if (i == 0) printf(\"*\"); else if (j == height / 2) printf(\"*\"); else printf(\" \"); } printf(\"\\n\"); }} // Function to print the pattern of 'U'void printU(){ int i, j; for (i = 0; i < height; i++) { if (i != 0 && i != height - 1) printf(\"*\"); else printf(\" \"); for (j = 0; j < height; j++) { if (((i == height - 1) && j >= 0 && j < height - 1)) printf(\"*\"); else if (j == height - 1 && i != 0 && i != height - 1) printf(\"*\"); else printf(\" \"); } printf(\"\\n\"); }} // Function to print the pattern of 'V'void printV(){ int i, j, counter = 0; for (i = 0; i < height; i++) { for (j = 0; j <= width; j++) { if (j == counter || j == width - counter - 1) printf(\"*\"); else printf(\" \"); } counter++; printf(\"\\n\"); }} // Function to print the pattern of 'W'void printW(){ int i, j, counter = height / 2; for (i = 0; i < height; i++) { printf(\"*\"); for (j = 0; j <= height; j++) { if (j == height) printf(\"*\"); else if ((i >= height / 2) && (j == counter || j == height - counter - 1)) printf(\"*\"); else printf(\" \"); } if (i >= height / 2) { counter++; } printf(\"\\n\"); }} // Function to print the pattern of 'X'void printX(){ int i, j, counter = 0; for (i = 0; i <= height; i++) { for (j = 0; j <= height; j++) { if (j == counter || j == height - counter) printf(\"*\"); else printf(\" \"); } counter++; printf(\"\\n\"); }} // Function to print the pattern of 'Y'void printY(){ int i, j, counter = 0; for (i = 0; i < height; i++) { for (j = 0; j <= height; j++) { if (j == counter || j == height - counter && i <= height / 2) printf(\"*\"); else printf(\" \"); } printf(\"\\n\"); if (i < height / 2) counter++; }} // Function to print the pattern of 'Z'void printZ(){ int i, j, counter = height - 1; for (i = 0; i < height; i++) { for (j = 0; j < height; j++) { if (i == 0 || i == height - 1 || j == counter) printf(\"*\"); else printf(\" \"); } counter--; printf(\"\\n\"); }} // Function print the pattern of the// alphabets from A to Zvoid printPattern(char character){ switch (character) { case 'A': printA(); break; case 'B': printB(); break; case 'C': printC(); break; case 'D': printD(); break; case 'E': printE(); break; case 'F': printF(); break; case 'G': printG(); break; case 'H': printH(); break; case 'I': printI(); break; case 'J': printJ(); break; case 'K': printK(); break; case 'L': printL(); break; case 'M': printM(); break; case 'N': printN(); break; case 'O': printO(); break; case 'P': printP(); break; case 'Q': printQ(); break; case 'R': printR(); break; case 'S': printS(); break; case 'T': printT(); break; case 'U': printU(); break; case 'V': printV(); break; case 'W': printW(); break; case 'X': printX(); break; case 'Y': printY(); break; case 'Z': printZ(); break; }} // Driver Codeint main(){ char character = 'A'; printPattern(character); return 0;}", "e": 51115, "s": 37940, "text": null }, { "code": "// Java implementation to print the// pattern of alphabets A to Z using *class GFG{ // Below height and width variable can be used// to create a user-defined sized alphabet's pattern // Number of lines for the alphabet's patternstatic int height = 5; // Number of character width in each linestatic int width = (2 * height) - 1; // Function to find the absolute value// of a number Dstatic int abs(int d){ return d < 0 ? -1 * d : d;} // Function to print the pattern of 'A'static void printA(){ int n = width / 2, i, j; for (i = 0; i < height; i++) { for (j = 0; j <= width; j++) { if (j == n || j == (width - n) || (i == height / 2 && j > n && j < (width - n))) System.out.printf(\"*\"); else System.out.printf(\" \"); } System.out.printf(\"\\n\"); n--; }} // Function to print the pattern of 'B'static void printB(){ int i, j, half = (height / 2); for (i = 0; i < height; i++) { System.out.printf(\"*\"); for (j = 0; j < width; j++) { if ((i == 0 || i == height - 1 || i == half) && j < (width - 2)) System.out.printf(\"*\"); else if (j == (width - 2) && !(i == 0 || i == height - 1 || i == half)) System.out.printf(\"*\"); else System.out.printf(\" \"); } System.out.printf(\"\\n\"); }} // Function to print the pattern of 'C'static void printC(){ int i, j; for (i = 0; i < height; i++) { System.out.printf(\"*\"); for (j = 0; j < (height - 1); j++) { if (i == 0 || i == height - 1) System.out.printf(\"*\"); else continue; } System.out.printf(\"\\n\"); }} // Function to print the pattern of 'D'static void printD(){ int i, j; for (i = 0; i < height; i++) { System.out.printf(\"*\"); for (j = 0; j < height; j++) { if ((i == 0 || i == height - 1) && j < height - 1) System.out.printf(\"*\"); else if (j == height - 1 && i != 0 && i != height - 1) System.out.printf(\"*\"); else System.out.printf(\" \"); } System.out.printf(\"\\n\"); }} // Function to print the pattern of 'E'static void printE(){ int i, j; for (i = 0; i < height; i++) { System.out.printf(\"*\"); for (j = 0; j < height; j++) { if ((i == 0 || i == height - 1) || (i == height / 2 && j <= height / 2)) System.out.printf(\"*\"); else continue; } System.out.printf(\"\\n\"); }} // Function to print the pattern of 'F'static void printF(){ int i, j; for (i = 0; i < height; i++) { System.out.printf(\"*\"); for (j = 0; j < height; j++) { if ((i == 0) || (i == height / 2 && j <= height / 2)) System.out.printf(\"*\"); else continue; } System.out.printf(\"\\n\"); }} // Function to print the pattern of 'G'static void printG(){ int i, j; width--; for (i = 0; i < height; i++) { for (j = 0; j < width; j++) { if ((i == 0 || i == height - 1) && (j == 0 || j == width - 1)) System.out.printf(\" \"); else if (j == 0) System.out.printf(\"*\"); else if (i == 0 && j <= height) System.out.printf(\"*\"); else if (i == height / 2 && j > height / 2) System.out.printf(\"*\"); else if (i > height / 2 && j == width - 1) System.out.printf(\"*\"); else if (i == height - 1 && j < width) System.out.printf(\"*\"); else System.out.printf(\" \"); } System.out.printf(\"\\n\"); }} // Function to print the pattern of 'H'static void printH(){ int i, j; for (i = 0; i < height; i++) { System.out.printf(\"*\"); for (j = 0; j < height; j++) { if ((j == height - 1) || (i == height / 2)) System.out.printf(\"*\"); else System.out.printf(\" \"); } System.out.printf(\"\\n\"); }} // Function to print the pattern of 'I'static void printI(){ int i, j; for (i = 0; i < height; i++) { for (j = 0; j < height; j++) { if (i == 0 || i == height - 1) System.out.printf(\"*\"); else if (j == height / 2) System.out.printf(\"*\"); else System.out.printf(\" \"); } System.out.printf(\"\\n\"); }} // Function to print the pattern of 'J'static void printJ(){ int i, j; for (i = 0; i < height; i++) { for (j = 0; j < height; j++) { if (i == height - 1 && (j > 0 && j < height - 1)) System.out.printf(\"*\"); else if ((j == height - 1 && i != height - 1) || (i > (height / 2) - 1 && j == 0 && i != height - 1)) System.out.printf(\"*\"); else System.out.printf(\" \"); } System.out.printf(\"\\n\"); }} // Function to print the pattern of 'K'static void printK(){ int i, j, half = height / 2, dummy = half; for (i = 0; i < height; i++) { System.out.printf(\"*\"); for (j = 0; j <= half; j++) { if (j == abs(dummy)) System.out.printf(\"*\"); else System.out.printf(\" \"); } System.out.printf(\"\\n\"); dummy--; }} // Function to print the pattern of 'L'static void printL(){ int i, j; for (i = 0; i < height; i++) { System.out.printf(\"*\"); for (j = 0; j <= height; j++) { if (i == height - 1) System.out.printf(\"*\"); else System.out.printf(\" \"); } System.out.printf(\"\\n\"); }} // Function to print the pattern of 'M'static void printM(){ int i, j, counter = 0; for (i = 0; i < height; i++) { System.out.printf(\"*\"); for (j = 0; j <= height; j++) { if (j == height) System.out.printf(\"*\"); else if (j == counter || j == height - counter - 1) System.out.printf(\"*\"); else System.out.printf(\" \"); } if (counter == height / 2) { counter = -99999; } else counter++; System.out.printf(\"\\n\"); }} // Function to print the pattern of 'N'static void printN(){ int i, j, counter = 0; for (i = 0; i < height; i++) { System.out.printf(\"*\"); for (j = 0; j <= height; j++) { if (j == height) System.out.printf(\"*\"); else if (j == counter) System.out.printf(\"*\"); else System.out.printf(\" \"); } counter++; System.out.printf(\"\\n\"); }} // Function to print the pattern of 'O'static void printO(){ int i, j, space = (height / 3); int width = height / 2 + height / 5 + space + space; for (i = 0; i < height; i++) { for (j = 0; j <= width; j++) { if (j == width - abs(space) || j == abs(space)) System.out.printf(\"*\"); else if ((i == 0 || i == height - 1) && j > abs(space) && j < width - abs(space)) System.out.printf(\"*\"); else System.out.printf(\" \"); } if (space != 0 && i < height / 2) { space--; } else if (i >= (height / 2 + height / 5)) space--; System.out.printf(\"\\n\"); }} // Function to print the pattern of 'P'static void printP(){ int i, j; for (i = 0; i < height; i++) { System.out.printf(\"*\"); for (j = 0; j < height; j++) { if ((i == 0 || i == height / 2) && j < height - 1) System.out.printf(\"*\"); else if (i < height / 2 && j == height - 1 && i != 0) System.out.printf(\"*\"); else System.out.printf(\" \"); } System.out.printf(\"\\n\"); }} // Function to print the pattern of 'Q'static void printQ(){ printO(); int i, j, d = height; for (i = 0; i < height / 2; i++) { for (j = 0; j <= d; j++) { if (j == d) System.out.printf(\"*\"); else System.out.printf(\" \"); } System.out.printf(\"\\n\"); d++; }} // Function to print the pattern of 'R'static void printR(){ int i, j, half = (height / 2); for (i = 0; i < height; i++) { System.out.printf(\"*\"); for (j = 0; j < width; j++) { if ((i == 0 || i == half) && j < (width - 2)) System.out.printf(\"*\"); else if (j == (width - 2) && !(i == 0 || i == half)) System.out.printf(\"*\"); else System.out.printf(\" \"); } System.out.printf(\"\\n\"); }} // Function to print the pattern of 'S'static void printS(){ int i, j; for (i = 0; i < height; i++) { for (j = 0; j < height; j++) { if ((i == 0 || i == height / 2 || i == height - 1)) System.out.printf(\"*\"); else if (i < height / 2 && j == 0) System.out.printf(\"*\"); else if (i > height / 2 && j == height - 1) System.out.printf(\"*\"); else System.out.printf(\" \"); } System.out.printf(\"\\n\"); }} // Function to print the pattern of 'T'static void printT(){ int i, j; for (i = 0; i < height; i++) { for (j = 0; j < height; j++) { if (i == 0) System.out.printf(\"*\"); else if (j == height / 2) System.out.printf(\"*\"); else System.out.printf(\" \"); } System.out.printf(\"\\n\"); }} // Function to print the pattern of 'U'static void printU(){ int i, j; for (i = 0; i < height; i++) { if (i != 0 && i != height - 1) System.out.printf(\"*\"); else System.out.printf(\" \"); for (j = 0; j < height; j++) { if (((i == height - 1) && j >= 0 && j < height - 1)) System.out.printf(\"*\"); else if (j == height - 1 && i != 0 && i != height - 1) System.out.printf(\"*\"); else System.out.printf(\" \"); } System.out.printf(\"\\n\"); }} // Function to print the pattern of 'V'static void printV(){ int i, j, counter = 0; for (i = 0; i < height; i++) { for (j = 0; j <= width; j++) { if (j == counter || j == width - counter - 1) System.out.printf(\"*\"); else System.out.printf(\" \"); } counter++; System.out.printf(\"\\n\"); }} // Function to print the pattern of 'W'static void printW(){ int i, j, counter = height / 2; for (i = 0; i < height; i++) { System.out.printf(\"*\"); for (j = 0; j <= height; j++) { if (j == height) System.out.printf(\"*\"); else if ((i >= height / 2) && (j == counter || j == height - counter - 1)) System.out.printf(\"*\"); else System.out.printf(\" \"); } if (i >= height / 2) { counter++; } System.out.printf(\"\\n\"); }} // Function to print the pattern of 'X'static void printX(){ int i, j, counter = 0; for (i = 0; i <= height; i++) { for (j = 0; j <= height; j++) { if (j == counter || j == height - counter) System.out.printf(\"*\"); else System.out.printf(\" \"); } counter++; System.out.printf(\"\\n\"); }} // Function to print the pattern of 'Y'static void printY(){ int i, j, counter = 0; for (i = 0; i < height; i++) { for (j = 0; j <= height; j++) { if (j == counter || j == height - counter && i <= height / 2) System.out.printf(\"*\"); else System.out.printf(\" \"); } System.out.printf(\"\\n\"); if (i < height / 2) counter++; }} // Function to print the pattern of 'Z'static void printZ(){ int i, j, counter = height - 1; for (i = 0; i < height; i++) { for (j = 0; j < height; j++) { if (i == 0 || i == height - 1 || j == counter) System.out.printf(\"*\"); else System.out.printf(\" \"); } counter--; System.out.printf(\"\\n\"); }} // Function print the pattern of the// alphabets from A to Zstatic void printPattern(char character){ switch (character) { case 'A': printA(); break; case 'B': printB(); break; case 'C': printC(); break; case 'D': printD(); break; case 'E': printE(); break; case 'F': printF(); break; case 'G': printG(); break; case 'H': printH(); break; case 'I': printI(); break; case 'J': printJ(); break; case 'K': printK(); break; case 'L': printL(); break; case 'M': printM(); break; case 'N': printN(); break; case 'O': printO(); break; case 'P': printP(); break; case 'Q': printQ(); break; case 'R': printR(); break; case 'S': printS(); break; case 'T': printT(); break; case 'U': printU(); break; case 'V': printV(); break; case 'W': printW(); break; case 'X': printX(); break; case 'Y': printY(); break; case 'Z': printZ(); break; }} // Driver Codepublic static void main(String[] args){ char character = 'A'; printPattern(character);}} // This code is contributed by PrinciRaj1992", "e": 66005, "s": 51115, "text": null }, { "code": "# Python implementation to print the# pattern of alphabets A to Z using * # Below height and width variable can be used# to create a user-defined sized alphabet's pattern # Number of lines for the alphabet's pattern height = 5 # Number of character width in each line width = (2 * height) - 1 # Function to find the absolute value# of a number D def abs(d): if d < 0: return -1*d else: return d # Function to print the pattern of 'A' def printA(): n = width // 2 for i in range(0, height): for j in range(0, width+1): if (j == n or j == (width - n) or (i == (height // 2) and j > n and j < (width - n))): print(\"*\", end=\"\") else: print(end=\" \") print() n = n-1 # Function to print the pattern of 'B'def printB() : half = height // 2 for i in range(0,height) : print(\"*\",end=\"\") for j in range(0,width) : if ((i == 0 or i == height - 1 or i == half) and j < (width - 2)) : print(\"*\",end=\"\") elif (j == (width - 2) and not(i == 0 or i == height - 1 or i == half)) : print(\"*\",end=\"\") else : print(end=\" \") print() # Function to print the pattern of 'C'def printC() : for i in range(0,height) : print(\"*\",end=\"\") for j in range(0,height - 1) : if (i == 0 or i == height - 1 ) : print(\"*\",end=\"\") else : continue print() # Function to print the pattern of 'D'def printD() : for i in range(0,height) : print(\"*\",end=\"\") for j in range(0,height) : if ( (i == 0 or i == height - 1) and j < height - 1 ): print(\"*\",end=\"\") elif (j == height - 1 and i != 0 and i != height - 1) : print(\"*\",end=\"\") else : print(end=\" \") print() # Function to print the pattern of 'E'def printE() : for i in range(0,height) : print(\"*\",end=\"\") for j in range(0,height) : if ( (i == 0 or i == height - 1) or (i == height // 2 and j <= height // 2) ): print(\"*\",end=\"\") else : continue print() # Function to print the pattern of 'F'def printF() : for i in range(0,height) : print(\"*\",end=\"\") for j in range(0,height) : if ( (i == 0) or (i == height // 2 and j <= height // 2) ): print(\"*\",end=\"\") else : continue print() # Function to print the pattern of 'G'def printG() : for i in range(0,height) : for j in range(0,width-1) : if ((i == 0 or i == height - 1) and (j == 0 or j == width - 2)) : print(end=\" \") elif (j == 0) : print(\"*\",end=\"\") elif (i == 0 and j <= height) : print(\"*\",end=\"\") elif (i == height // 2 and j > height // 2) : print(\"*\",end=\"\") elif (i > height // 2 and j == width - 2) : print(\"*\",end=\"\") elif (i == height - 1 and j < width - 1 ) : print(\"*\",end=\"\") else : print(end=\" \") print() # Function to print the pattern of 'H'def printH() : for i in range(0,height) : print(\"*\",end=\"\") for j in range(0,height) : if ( (j == height - 1) or (i == height // 2) ): print(\"*\",end=\"\") else : print(end=\" \") print() # Function to print the pattern of 'I'def printI() : for i in range(0,height) : for j in range(0,height) : if ( i == 0 or i == height - 1 ): print(\"*\",end=\"\") elif ( j == height // 2 ) : print(\"*\",end=\"\") else : print(end=\" \") print() # Function to print the pattern of 'J'def printJ() : for i in range(0,height) : for j in range(0,height) : if ( i == height - 1 and (j > 0 and j < height - 1) ): print(\"*\",end=\"\") elif ( (j == height - 1 and i != height - 1) or (i > (height // 2) - 1 and j == 0 and i != height - 1) ) : print(\"*\",end=\"\") else : print(end=\" \") print() # Function to print the pattern of 'K'def printK() : half = height // 2 dummy = half for i in range(0,height) : print(\"*\",end=\"\") for j in range(0,half+1) : if ( j == abs(dummy) ): print(\"*\",end=\"\") else : print(end=\" \") print() dummy = dummy -1 # Function to print the pattern of 'L'def printL() : for i in range(0,height) : print(\"*\",end=\"\") for j in range(0,height+1) : if ( i == height - 1 ): print(\"*\",end=\"\") else : print(end=\" \") print() # Function to print the pattern of 'M'def printM() : counter = 0 for i in range(0,height) : print(\"*\",end=\"\") for j in range(0,height+1) : if ( j == height ): print(\"*\",end=\"\") elif ( j == counter or j == height - counter - 1 ) : print(\"*\",end=\"\") else : print(end=\" \") if(counter == height // 2) : counter = -99999 else : counter = counter + 1 print() # Function to print the pattern of 'N'def printN() : counter = 0 for i in range(0,height) : print(\"*\",end=\"\") for j in range(0,height+1) : if ( j == height ): print(\"*\",end=\"\") elif ( j == counter) : print(\"*\",end=\"\") else : print(end=\" \") counter = counter + 1 print() # Function to print the pattern of 'O'def printO() : space = height // 3 width = height // 2 + height // 5 + space + space for i in range(0,height) : for j in range(0,width + 1) : if ( j == width - abs(space) or j == abs(space)): print(\"*\",end=\"\") elif( (i == 0 or i == height - 1) and j > abs(space) and j < width - abs(space) ) : print(\"*\",end=\"\") else : print(end=\" \") if( space != 0 and i < height // 2) : space = space -1 elif ( i >= (height // 2 + height // 5) ) : space = space -1 print() # Function to print the pattern of 'P'def printP() : for i in range(0,height) : print(\"*\",end=\"\") for j in range(0,height) : if ( (i == 0 or i == height // 2) and j < height - 1 ): print(\"*\",end=\"\") elif ( i < height // 2 and j == height - 1 and i != 0 ) : print(\"*\",end=\"\") else : print(end=\" \") print() # Function to print the pattern of 'Q'def printQ() : printO() d = height for i in range(0,height//2) : for j in range(0,d+1) : if ( j == d ): print(\"*\",end=\"\") else : print(end=\" \") print() d = d+1 # Function to print the pattern of 'R'def printR() : half = (height // 2) for i in range(0,height) : print(\"*\",end=\"\") for j in range(0,width) : if ( (i == 0 or i == half) and j < (width - 2) ): print(\"*\",end=\"\") elif ( j == (width - 2) and not(i == 0 or i == half) ) : print(\"*\",end=\"\") else : print(end=\" \") print() # Function to print the pattern of 'S'def printS() : for i in range(0,height) : for j in range(0,height) : if ( (i == 0 or i == height // 2 or i == height - 1) ): print(\"*\",end=\"\") elif ( i < height // 2 and j == 0 ) : print(\"*\",end=\"\") elif ( i > height // 2 and j == height - 1 ) : print(\"*\",end=\"\") else : print(end=\" \") print() # Function to print the pattern of 'T'def printT() : for i in range(0,height) : for j in range(0,height) : if ( i == 0 ): print(\"*\",end=\"\") elif ( j == height // 2 ) : print(\"*\",end=\"\") else : print(end=\" \") print() # Function to print the pattern of 'U'def printU() : for i in range(0,height) : if (i != 0 and i != height - 1) : print(\"*\",end=\"\") else : print(end = \" \") for j in range(0,height) : if ( ((i == height - 1) and j >= 0 and j < height - 1) ): print(\"*\",end=\"\") elif ( j == height - 1 and i != 0 and i != height - 1 ) : print(\"*\",end=\"\") else : print(end=\" \") print() # Function to print the pattern of 'V'def printV() : counter = 0 for i in range(0,height) : for j in range(0,width+1) : if ( j == counter or j == width - counter - 1 ): print(\"*\",end=\"\") else : print(end=\" \") counter = counter + 1 print() # Function to print the pattern of 'W'def printW() : counter = height // 2 for i in range(0,height) : print(\"*\",end=\"\") for j in range(0,height+1) : if ( j == height ): print(\"*\",end=\"\") elif ( (i >= height // 2) and (j == counter or j == height - counter - 1) ) : print(\"*\",end=\"\") else : print(end=\" \") if( i >= height // 2) : counter = counter + 1 print() # Function to print the pattern of 'X'def printX() : counter = 0 for i in range(0,height+1) : for j in range(0,height+1) : if ( j == counter or j == height - counter ): print(\"*\",end=\"\") else : print(end=\" \") counter = counter + 1 print() # Function to print the pattern of 'Y'def printY() : counter = 0 for i in range(0,height) : for j in range(0,height+1) : if ( j == counter or j == height - counter and i <= height // 2 ): print(\"*\",end=\"\") else : print(end=\" \") print() if (i < height // 2) : counter = counter + 1 # Function to print the pattern of 'Z'def printZ() : counter = height - 1 for i in range(0,height) : for j in range(0,height) : if ( i == 0 or i == height - 1 or j == counter ): print(\"*\",end=\"\") else : print(end=\" \") counter = counter - 1 print() # Function print the pattern of the# alphabets from A to Z def printPattern(character) : if character == 'A' : return printA() elif character == 'B': return printB() elif character == 'C': return printC() elif character == 'D': return printD() elif character == 'E': return printE(), elif character == 'F': return printF(), elif character == 'G': return printG(), elif character == 'H': return printH(), elif character == 'I': return printI(), elif character == 'J': return printJ(), elif character == 'K': return printK(), elif character == 'L': return printL(), elif character == 'M': return printM(), elif character == 'N': return printN(), elif character == 'O': return printO(), elif character == 'P': return printP(), elif character == 'Q': return printQ(), elif character == 'R': return printR(), elif character == 'S': return printS(), elif character == 'T': return printT(), elif character == 'U': return printU(), elif character == 'V': return printV(), elif character == 'W': return printW(), elif character == 'X': return printX(), elif character == 'Y': return printY() else : printZ() # Driver Codeif __name__ == \"__main__\": character = 'A' printPattern(character) # This code is contributed by rakeshsahni", "e": 77947, "s": 66005, "text": null }, { "code": "// C# implementation to print the// pattern of alphabets A to Z using *using System; class GFG{ // Below height and width variable can be used// to create a user-defined sized alphabet's pattern // Number of lines for the alphabet's patternstatic int height = 5; // Number of character width in each linestatic int width = (2 * height) - 1; // Function to find the absolute value// of a number Dstatic int abs(int d){ return d < 0 ? -1 * d : d;} // Function to print the pattern of 'A'static void printA(){ int n = width / 2, i, j; for (i = 0; i < height; i++) { for (j = 0; j <= width; j++) { if (j == n || j == (width - n) || (i == height / 2 && j > n && j < (width - n))) Console.Write(\"*\"); else Console.Write(\" \"); } Console.Write(\"\\n\"); n--; }} // Function to print the pattern of 'B'static void printB(){ int i, j, half = (height / 2); for (i = 0; i < height; i++) { Console.Write(\"*\"); for (j = 0; j < width; j++) { if ((i == 0 || i == height - 1 || i == half) && j < (width - 2)) Console.Write(\"*\"); else if (j == (width - 2) && !(i == 0 || i == height - 1 || i == half)) Console.Write(\"*\"); else Console.Write(\" \"); } Console.Write(\"\\n\"); }} // Function to print the pattern of 'C'static void printC(){ int i, j; for (i = 0; i < height; i++) { Console.Write(\"*\"); for (j = 0; j < (height - 1); j++) { if (i == 0 || i == height - 1) Console.Write(\"*\"); else continue; } Console.Write(\"\\n\"); }} // Function to print the pattern of 'D'static void printD(){ int i, j; for (i = 0; i < height; i++) { Console.Write(\"*\"); for (j = 0; j < height; j++) { if ((i == 0 || i == height - 1) && j < height - 1) Console.Write(\"*\"); else if (j == height - 1 && i != 0 && i != height - 1) Console.Write(\"*\"); else Console.Write(\" \"); } Console.Write(\"\\n\"); }} // Function to print the pattern of 'E'static void printE(){ int i, j; for (i = 0; i < height; i++) { Console.Write(\"*\"); for (j = 0; j < height; j++) { if ((i == 0 || i == height - 1) || (i == height / 2 && j <= height / 2)) Console.Write(\"*\"); else continue; } Console.Write(\"\\n\"); }} // Function to print the pattern of 'F'static void printF(){ int i, j; for (i = 0; i < height; i++) { Console.Write(\"*\"); for (j = 0; j < height; j++) { if ((i == 0) || (i == height / 2 && j <= height / 2)) Console.Write(\"*\"); else continue; } Console.Write(\"\\n\"); }} // Function to print the pattern of 'G'static void printG(){ int i, j; width--; for (i = 0; i < height; i++) { for (j = 0; j < width; j++) { if ((i == 0 || i == height - 1) && (j == 0 || j == width - 1)) Console.Write(\" \"); else if (j == 0) Console.Write(\"*\"); else if (i == 0 && j <= height) Console.Write(\"*\"); else if (i == height / 2 && j > height / 2) Console.Write(\"*\"); else if (i > height / 2 && j == width - 1) Console.Write(\"*\"); else if (i == height - 1 && j < width) Console.Write(\"*\"); else Console.Write(\" \"); } Console.Write(\"\\n\"); }} // Function to print the pattern of 'H'static void printH(){ int i, j; for (i = 0; i < height; i++) { Console.Write(\"*\"); for (j = 0; j < height; j++) { if ((j == height - 1) || (i == height / 2)) Console.Write(\"*\"); else Console.Write(\" \"); } Console.Write(\"\\n\"); }} // Function to print the pattern of 'I'static void printI(){ int i, j; for (i = 0; i < height; i++) { for (j = 0; j < height; j++) { if (i == 0 || i == height - 1) Console.Write(\"*\"); else if (j == height / 2) Console.Write(\"*\"); else Console.Write(\" \"); } Console.Write(\"\\n\"); }} // Function to print the pattern of 'J'static void printJ(){ int i, j; for (i = 0; i < height; i++) { for (j = 0; j < height; j++) { if (i == height - 1 && (j > 0 && j < height - 1)) Console.Write(\"*\"); else if ((j == height - 1 && i != height - 1) || (i > (height / 2) - 1 && j == 0 && i != height - 1)) Console.Write(\"*\"); else Console.Write(\" \"); } Console.Write(\"\\n\"); }} // Function to print the pattern of 'K'static void printK(){ int i, j, half = height / 2, dummy = half; for (i = 0; i < height; i++) { Console.Write(\"*\"); for (j = 0; j <= half; j++) { if (j == abs(dummy)) Console.Write(\"*\"); else Console.Write(\" \"); } Console.Write(\"\\n\"); dummy--; }} // Function to print the pattern of 'L'static void printL(){ int i, j; for (i = 0; i < height; i++) { Console.Write(\"*\"); for (j = 0; j <= height; j++) { if (i == height - 1) Console.Write(\"*\"); else Console.Write(\" \"); } Console.Write(\"\\n\"); }} // Function to print the pattern of 'M'static void printM(){ int i, j, counter = 0; for (i = 0; i < height; i++) { Console.Write(\"*\"); for (j = 0; j <= height; j++) { if (j == height) Console.Write(\"*\"); else if (j == counter || j == height - counter - 1) Console.Write(\"*\"); else Console.Write(\" \"); } if (counter == height / 2) { counter = -99999; } else counter++; Console.Write(\"\\n\"); }} // Function to print the pattern of 'N'static void printN(){ int i, j, counter = 0; for (i = 0; i < height; i++) { Console.Write(\"*\"); for (j = 0; j <= height; j++) { if (j == height) Console.Write(\"*\"); else if (j == counter) Console.Write(\"*\"); else Console.Write(\" \"); } counter++; Console.Write(\"\\n\"); }} // Function to print the pattern of 'O'static void printO(){ int i, j, space = (height / 3); int width = height / 2 + height / 5 + space + space; for (i = 0; i < height; i++) { for (j = 0; j <= width; j++) { if (j == width - abs(space) || j == abs(space)) Console.Write(\"*\"); else if ((i == 0 || i == height - 1) && j > abs(space) && j < width - abs(space)) Console.Write(\"*\"); else Console.Write(\" \"); } if (space != 0 && i < height / 2) { space--; } else if (i >= (height / 2 + height / 5)) space--; Console.Write(\"\\n\"); }} // Function to print the pattern of 'P'static void printP(){ int i, j; for (i = 0; i < height; i++) { Console.Write(\"*\"); for (j = 0; j < height; j++) { if ((i == 0 || i == height / 2) && j < height - 1) Console.Write(\"*\"); else if (i < height / 2 && j == height - 1 && i != 0) Console.Write(\"*\"); else Console.Write(\" \"); } Console.Write(\"\\n\"); }} // Function to print the pattern of 'Q'static void printQ(){ printO(); int i, j, d = height; for (i = 0; i < height / 2; i++) { for (j = 0; j <= d; j++) { if (j == d) Console.Write(\"*\"); else Console.Write(\" \"); } Console.Write(\"\\n\"); d++; }} // Function to print the pattern of 'R'static void printR(){ int i, j, half = (height / 2); for (i = 0; i < height; i++) { Console.Write(\"*\"); for (j = 0; j < width; j++) { if ((i == 0 || i == half) && j < (width - 2)) Console.Write(\"*\"); else if (j == (width - 2) && !(i == 0 || i == half)) Console.Write(\"*\"); else Console.Write(\" \"); } Console.Write(\"\\n\"); }} // Function to print the pattern of 'S'static void printS(){ int i, j; for (i = 0; i < height; i++) { for (j = 0; j < height; j++) { if ((i == 0 || i == height / 2 || i == height - 1)) Console.Write(\"*\"); else if (i < height / 2 && j == 0) Console.Write(\"*\"); else if (i > height / 2 && j == height - 1) Console.Write(\"*\"); else Console.Write(\" \"); } Console.Write(\"\\n\"); }} // Function to print the pattern of 'T'static void printT(){ int i, j; for (i = 0; i < height; i++) { for (j = 0; j < height; j++) { if (i == 0) Console.Write(\"*\"); else if (j == height / 2) Console.Write(\"*\"); else Console.Write(\" \"); } Console.Write(\"\\n\"); }} // Function to print the pattern of 'U'static void printU(){ int i, j; for (i = 0; i < height; i++) { if (i != 0 && i != height - 1) Console.Write(\"*\"); else Console.Write(\" \"); for (j = 0; j < height; j++) { if (((i == height - 1) && j >= 0 && j < height - 1)) Console.Write(\"*\"); else if (j == height - 1 && i != 0 && i != height - 1) Console.Write(\"*\"); else Console.Write(\" \"); } Console.Write(\"\\n\"); }} // Function to print the pattern of 'V'static void printV(){ int i, j, counter = 0; for (i = 0; i < height; i++) { for (j = 0; j <= width; j++) { if (j == counter || j == width - counter - 1) Console.Write(\"*\"); else Console.Write(\" \"); } counter++; Console.Write(\"\\n\"); }} // Function to print the pattern of 'W'static void printW(){ int i, j, counter = height / 2; for (i = 0; i < height; i++) { Console.Write(\"*\"); for (j = 0; j <= height; j++) { if (j == height) Console.Write(\"*\"); else if ((i >= height / 2) && (j == counter || j == height - counter - 1)) Console.Write(\"*\"); else Console.Write(\" \"); } if (i >= height / 2) { counter++; } Console.Write(\"\\n\"); }} // Function to print the pattern of 'X'static void printX(){ int i, j, counter = 0; for (i = 0; i <= height; i++) { for (j = 0; j <= height; j++) { if (j == counter || j == height - counter) Console.Write(\"*\"); else Console.Write(\" \"); } counter++; Console.Write(\"\\n\"); }} // Function to print the pattern of 'Y'static void printY(){ int i, j, counter = 0; for (i = 0; i < height; i++) { for (j = 0; j <= height; j++) { if (j == counter || j == height - counter && i <= height / 2) Console.Write(\"*\"); else Console.Write(\" \"); } Console.Write(\"\\n\"); if (i < height / 2) counter++; }} // Function to print the pattern of 'Z'static void printZ(){ int i, j, counter = height - 1; for (i = 0; i < height; i++) { for (j = 0; j < height; j++) { if (i == 0 || i == height - 1 || j == counter) Console.Write(\"*\"); else Console.Write(\" \"); } counter--; Console.Write(\"\\n\"); }} // Function print the pattern of the// alphabets from A to Zstatic void printPattern(char character){ switch (character) { case 'A': printA(); break; case 'B': printB(); break; case 'C': printC(); break; case 'D': printD(); break; case 'E': printE(); break; case 'F': printF(); break; case 'G': printG(); break; case 'H': printH(); break; case 'I': printI(); break; case 'J': printJ(); break; case 'K': printK(); break; case 'L': printL(); break; case 'M': printM(); break; case 'N': printN(); break; case 'O': printO(); break; case 'P': printP(); break; case 'Q': printQ(); break; case 'R': printR(); break; case 'S': printS(); break; case 'T': printT(); break; case 'U': printU(); break; case 'V': printV(); break; case 'W': printW(); break; case 'X': printX(); break; case 'Y': printY(); break; case 'Z': printZ(); break; }} // Driver Codepublic static void Main(String[] args){ char character = 'A'; printPattern(character);}} // This code is contributed by PrinciRaj1992", "e": 92397, "s": 77947, "text": null }, { "code": "<script> // JavaScript implementation to print the // pattern of alphabets A to Z using * // Below height and width variable can be used // to create a user-defined sized alphabet's pattern // Number of lines for the alphabet's pattern let height = 5; // Number of character width in each line let width = (2 * height) - 1; // Function to find the absolute value // of a number D const abs = (d) => { return d < 0 ? -1 * d : d; } // Function to print the pattern of 'A' const printA = () => { let n = parseInt(width / 2), i, j; for (i = 0; i < height; i++) { for (j = 0; j <= width; j++) { if (j == n || j == (width - n) || (i == parseInt(height / 2) && j > n && j < (width - n))) document.write(\"*\"); else document.write(\" \"); } document.write(`<br/>`); n--; } } // Function to print the pattern of 'B' const printB = () => { let i, j, half = parseInt(height / 2); for (i = 0; i < height; i++) { document.write(\"*\"); for (j = 0; j < width; j++) { if ((i == 0 || i == height - 1 || i == half) && j < (width - 2)) document.write(\"*\"); else if (j == (width - 2) && !(i == 0 || i == height - 1 || i == half)) document.write(\"*\"); else document.write(\" \"); } document.write(`<br/>`); } } // Function to print the pattern of 'C' const printC = () => { let i, j; for (i = 0; i < height; i++) { document.write(\"*\"); for (j = 0; j < (height - 1); j++) { if (i == 0 || i == height - 1) document.write(\"*\"); else continue; } document.write(`<br/>`); } } // Function to print the pattern of 'D' const printD = () => { let i, j; for (i = 0; i < height; i++) { document.write(\"*\"); for (j = 0; j < height; j++) { if ((i == 0 || i == height - 1) && j < height - 1) document.write(\"*\"); else if (j == height - 1 && i != 0 && i != height - 1) document.write(\"*\"); else document.write(\" \"); } document.write(`<br/>`); } } // Function to print the pattern of 'E' const printE = () => { let i, j; for (i = 0; i < height; i++) { document.write(\"*\"); for (j = 0; j < height; j++) { if ((i == 0 || i == height - 1) || (i == parseInt(height / 2) && j <= parseInt(height / 2))) document.write(\"*\"); else continue; } document.write(`<br/>`); } } // Function to print the pattern of 'F' const printF = () => { let i, j; for (i = 0; i < height; i++) { document.write(\"*\"); for (j = 0; j < height; j++) { if ((i == 0) || (i == parseInt(height / 2) && j <= parseInt(height / 2))) document.write(\"*\"); else continue; } document.write(`<br/>`); } } // Function to print the pattern of 'G' const printG = () => { let i, j; width--; for (i = 0; i < height; i++) { for (j = 0; j < width; j++) { if ((i == 0 || i == height - 1) && (j == 0 || j == width - 1)) document.write(\" \"); else if (j == 0) document.write(\"*\"); else if (i == 0 && j <= height) document.write(\"*\"); else if (i == parseInt(height / 2) && j > parseInt(height / 2)) document.write(\"*\"); else if (i > parseInt(height / 2) && j == width - 1) document.write(\"*\"); else if (i == height - 1 && j < width) document.write(\"*\"); else document.write(\" \"); } document.write(`<br/>`); } } // Function to print the pattern of 'H' const printH = () => { let i, j; for (i = 0; i < height; i++) { document.write(\"*\"); for (j = 0; j < height; j++) { if ((j == height - 1) || (i == parseInt(height / 2))) document.write(\"*\"); else document.write(\" \"); } document.write(`<br/>`); } } // Function to print the pattern of 'I' const printI = () => { let i, j; for (i = 0; i < height; i++) { for (j = 0; j < height; j++) { if (i == 0 || i == height - 1) document.write(\"*\"); else if (j == parseInt(height / 2)) document.write(\"*\"); else document.write(\" \"); } document.write(`<br/>`); } } // Function to print the pattern of 'J' const printJ = () => { let i, j; for (i = 0; i < height; i++) { for (j = 0; j < height; j++) { if (i == height - 1 && (j > 0 && j < height - 1)) document.write(\"*\"); else if ((j == height - 1 && i != height - 1) || (i > parseInt(height / 2) - 1 && j == 0 && i != height - 1)) document.write(\"*\"); else document.write(\" \"); } document.write(`<br/>`); } } // Function to print the pattern of 'K' const printK = () => { let i, j, half = parseInt(height / 2), dummy = half; for (i = 0; i < height; i++) { document.write(\"*\"); for (j = 0; j <= half; j++) { if (j == abs(dummy)) document.write(\"*\"); else document.write(\" \"); } document.write(`<br/>`); dummy--; } } // Function to print the pattern of 'L' const printL = () => { let i, j; for (i = 0; i < height; i++) { document.write(\"*\"); for (j = 0; j <= height; j++) { if (i == height - 1) document.write(\"*\"); else document.write(\" \"); } document.write(`<br/>`); } } // Function to print the pattern of 'M' const printM = () => { let i, j, counter = 0; for (i = 0; i < height; i++) { document.write(\"*\"); for (j = 0; j <= height; j++) { if (j == height) document.write(\"*\"); else if (j == counter || j == height - counter - 1) document.write(\"*\"); else document.write(\" \"); } if (counter == parseInt(height / 2)) { counter = -99999; } else counter++; document.write(`<br/>`); } } // Function to print the pattern of 'N' const printN = () => { let i, j, counter = 0; for (i = 0; i < height; i++) { document.write(\"*\"); for (j = 0; j <= height; j++) { if (j == height) document.write(\"*\"); else if (j == counter) document.write(\"*\"); else document.write(\" \"); } counter++; document.write(`<br/>`); } } // Function to print the pattern of 'O' const printO = () => { let i, j, space = parseInt(height / 3); let width = parseInt(height / 2) + parseInt(height / 5) + space + space; for (i = 0; i < height; i++) { for (j = 0; j <= width; j++) { if (j == width - abs(space) || j == abs(space)) document.write(\"*\"); else if ((i == 0 || i == height - 1) && j > abs(space) && j < width - abs(space)) document.write(\"*\"); else document.write(\" \"); } if (space != 0 && i < parseInt(height / 2)) { space--; } else if (i >= (parseInt(height / 2) + parseInt(height / 5))) space--; document.write(`<br/>`); } } // Function to print the pattern of 'P' const printP = () => { let i, j; for (i = 0; i < height; i++) { document.write(\"*\"); for (j = 0; j < height; j++) { if ((i == 0 || i == parseInt(height / 2)) && j < height - 1) document.write(\"*\"); else if (i < parseInt(height / 2) && j == height - 1 && i != 0) document.write(\"*\"); else document.write(\" \"); } document.write(`<br/>`); } } // Function to print the pattern of 'Q' const printQ = () => { printO(); let i, j, d = height; for (i = 0; i < parseInt(height / 2); i++) { for (j = 0; j <= d; j++) { if (j == d) document.write(\"*\"); else document.write(\" \"); } document.write(`<br/>`); d++; } } // Function to print the pattern of 'R' const printR = () => { let i, j, half = parseInt(height / 2); for (i = 0; i < height; i++) { document.write(\"*\"); for (j = 0; j < width; j++) { if ((i == 0 || i == half) && j < (width - 2)) document.write(\"*\"); else if (j == (width - 2) && !(i == 0 || i == half)) document.write(\"*\"); else document.write(\" \"); } document.write(`<br/>`); } } // Function to print the pattern of 'S' const printS = () => { let i, j; for (i = 0; i < height; i++) { for (j = 0; j < height; j++) { if ((i == 0 || i == parseInt(height / 2) || i == height - 1)) document.write(\"*\"); else if (i < parseInt(height / 2) && j == 0) document.write(\"*\"); else if (i > parseInt(height / 2) && j == height - 1) document.write(\"*\"); else document.write(\" \"); } document.write(`<br/>`); } } // Function to print the pattern of 'T' const printT = () => { let i, j; for (i = 0; i < height; i++) { for (j = 0; j < height; j++) { if (i == 0) document.write(\"*\"); else if (j == parseInt(height / 2)) document.write(\"*\"); else document.write(\" \"); } document.write(`<br/>`); } } // Function to print the pattern of 'U' const printU = () => { let i, j; for (i = 0; i < height; i++) { if (i != 0 && i != height - 1) document.write(\"*\"); else document.write(\" \"); for (j = 0; j < height; j++) { if (((i == height - 1) && j >= 0 && j < height - 1)) document.write(\"*\"); else if (j == height - 1 && i != 0 && i != height - 1) document.write(\"*\"); else document.write(\" \"); } document.write(`<br/>`); } } // Function to print the pattern of 'V' const printV = () => { let i, j, counter = 0; for (i = 0; i < height; i++) { for (j = 0; j <= width; j++) { if (j == counter || j == width - counter - 1) document.write(\"*\"); else document.write(\" \"); } counter++; document.write(`<br/>`); } } // Function to print the pattern of 'W' const printW = () => { let i, j, counter = parseInt(height / 2); for (i = 0; i < height; i++) { document.write(\"*\"); for (j = 0; j <= height; j++) { if (j == height) document.write(\"*\"); else if ((i >= parseInt(height / 2)) && (j == counter || j == height - counter - 1)) document.write(\"*\"); else document.write(\" \"); } if (i >= parseInt(height / 2)) { counter++; } document.write(`<br/>`); } } // Function to print the pattern of 'X' const printX = () => { let i, j, counter = 0; for (i = 0; i <= height; i++) { for (j = 0; j <= height; j++) { if (j == counter || j == height - counter) document.write(\"*\"); else document.write(\" \"); } counter++; document.write(`<br/>`); } } // Function to print the pattern of 'Y' const printY = () => { let i, j, counter = 0; for (i = 0; i < height; i++) { for (j = 0; j <= height; j++) { if (j == counter || j == height - counter && i <= parseInt(height / 2)) document.write(\"*\"); else document.write(\" \"); } document.write(`<br/>`); if (i < parseInt(height / 2)) counter++; } } // Function to print the pattern of 'Z' const printZ = () => { let i, j, counter = height - 1; for (i = 0; i < height; i++) { for (j = 0; j < height; j++) { if (i == 0 || i == height - 1 || j == counter) document.write(\"*\"); else document.write(\" \"); } counter--; document.write(`<br/>`); } } // Function print the pattern of the // alphabets from A to Z const printPattern = (character) => { switch (character) { case 'A': printA(); break; case 'B': printB(); break; case 'C': printC(); break; case 'D': printD(); break; case 'E': printE(); break; case 'F': printF(); break; case 'G': printG(); break; case 'H': printH(); break; case 'I': printI(); break; case 'J': printJ(); break; case 'K': printK(); break; case 'L': printL(); break; case 'M': printM(); break; case 'N': printN(); break; case 'O': printO(); break; case 'P': printP(); break; case 'Q': printQ(); break; case 'R': printR(); break; case 'S': printS(); break; case 'T': printT(); break; case 'U': printU(); break; case 'V': printV(); break; case 'W': printW(); break; case 'X': printX(); break; case 'Y': printY(); break; case 'Z': printZ(); break; } } // Driver Code let character = 'A'; printPattern(character); // This code is contributed by rakeshsahni </script>", "e": 109550, "s": 92397, "text": null }, { "code": null, "e": 109605, "s": 109550, "text": " ** \n * * \n ****** \n * * \n* *" }, { "code": null, "e": 109621, "s": 109607, "text": "princiraj1992" }, { "code": null, "e": 109633, "s": 109621, "text": "kk773572498" }, { "code": null, "e": 109645, "s": 109633, "text": "rakeshsahni" }, { "code": null, "e": 109664, "s": 109645, "text": "shivanisinghss2110" }, { "code": null, "e": 109681, "s": 109664, "text": "pattern-printing" }, { "code": null, "e": 109705, "s": 109681, "text": "Technical Scripter 2019" }, { "code": null, "e": 109724, "s": 109705, "text": "School Programming" }, { "code": null, "e": 109743, "s": 109724, "text": "Technical Scripter" }, { "code": null, "e": 109760, "s": 109743, "text": "pattern-printing" }, { "code": null, "e": 109858, "s": 109760, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 109867, "s": 109858, "text": "Comments" }, { "code": null, "e": 109880, "s": 109867, "text": "Old Comments" }, { "code": null, "e": 109899, "s": 109880, "text": "Interfaces in Java" }, { "code": null, "e": 109927, "s": 109899, "text": "Operator Overloading in C++" }, { "code": null, "e": 109947, "s": 109927, "text": "Constructors in C++" }, { "code": null, "e": 109971, "s": 109947, "text": "Copy Constructor in C++" }, { "code": null, "e": 109990, "s": 109971, "text": "Overriding in Java" }, { "code": null, "e": 110005, "s": 109990, "text": "C++ Data Types" }, { "code": null, "e": 110038, "s": 110005, "text": "Friend class and function in C++" }, { "code": null, "e": 110065, "s": 110038, "text": "Types of Operating Systems" }, { "code": null, "e": 110111, "s": 110065, "text": "Different ways of Reading a text file in Java" } ]
ColabCode: Deploying Machine Learning Models From Google Colab | by Kaustubh Gupta | Towards Data Science
Google colab is the handiest online IDE for Python and Data Science enthusiasts. Released in 2017 for the public, it was initially an internal project used by the Google research team to collaborate on different AI projects. Since then, it has gained a lot of popularity due to its easy to use interface, Jupyter notebooks similarity, and GPU support gave it a boost. Most of the popular machine learning libraries such as numpy, pandas, seaborn, matplotlib, sklearn, TensorFlow come pre-installed in this cloud environment so you don’t require any explicit prerequisite. You can also install any python package of your choice to run your code. In this article, I will explain to you a simple way to deploy your machine learning model as an API using FastAPI and ngrok. It is a high-performance web framework to build APIs in Python. Traditionally, most of the developers used flask as the first option to build the API but due to some of the limitations but not limited to data validation, authentication, async, and many more, FastAPI gained a lot of popularity. FastAPI offers automatic docs generation functionality, authentication, data validation via pydantic models. To know more about the significant differences between the two frameworks in detail, you can check-out my article on Analytics Vidya here: www.analyticsvidhya.com FastAPI helps in setting up the production-ready server but what if you want to share this with your team before deploying it in an actual cloud platform such as Heroku. The ngrok comes to the rescue by tunneling your localhost and exposing it to the internet. Now, anyone can access your API endpoint via the link provided but what if, all of this could be done on the Google Colab only? The solution to this is ColabCode! It is a Python package that allows you to start a code server right from your Colab notebooks without setting up anything locally on your system. It can be used to start a VS Code environment, Jupyter Lab server, or tunnel the FastAPI server to the web, all in the colab notebook. This can be a great plus point for the enthusiast coders who train their models on the cloud and now want to share their findings with the world in the form of APIs. We will discuss all the functions of ColabCode as we go till the end of this article. The problem statement I would be using for this article is a decision tree classifier to classify between two music genres: Hip-Hop or Rock. I have already done the cleaning of the dataset and it is available on my GitHub repository. Now that I have the dataset, I have simply imported it into the notebook and trained a decision tree model without any preprocessing or EDA stuff as this article is more about deployment. Therefore, this model may return some wrong results! Now, if you are aware of the FastAPI architecture, we will require a data class for the inputs. This data class allows FastAPI to validate the inputs to be sent to the model and if any wrong input is given, it simply raises the error without giving it to the model.Creating a data class is pretty straightforward and requires only the parameters to be accepted along with the data type. To further customize, you can also add a custom example to quickly test out the results. The code for this class is: Now, if you are aware of the FastAPI architecture, we will require a data class for the inputs. This data class allows FastAPI to validate the inputs to be sent to the model and if any wrong input is given, it simply raises the error without giving it to the model. Creating a data class is pretty straightforward and requires only the parameters to be accepted along with the data type. To further customize, you can also add a custom example to quickly test out the results. The code for this class is: 3. Now, we need to create an endpoint where all the requests will be served. The endpoint creation in FastAPI is very similar to the flask and only requires the endpoint function to take in the data class for validation. If you wish to explore some cool projects then check out my GitHub profile: github.com Our FastAPI is ready and now the only thing needed is to run this via the colab environment. Firstly, import this package and initialize the server: from colabcode import ColabCodeserver = ColabCode(port=10000, code=False) The port number can be of your choice and the code parameter should be false. Now, the server is ready to receive the FastAPI object and with the help of ngrok, the local host is tunneled and exposed to the public via a unique URL. server.run_app(app=app) And that’ it! You will get a ngrok URL which you can share with your community, team, or whichever person. The link will expire as soon as you terminate the cell process and if you don’t, Google Colab terminates it after some time. An example GIF of this process is shown below: Here, after clicking on the link, I navigated to the endpoint /docs that the FastAPI generates automatically, and here, we can test out the results. The whole notebook code is available here if you want to run and try this thing. Just open this notebook and run all the cells. ColabCode is not limited to running FastAPI codes on Colab but it can also provide VS code server and Jupyter Lab server! It can help users to have a familiar environment on the cloud-based services. A user with very limited resources can also benefit from these services. It becomes very similar to the newly introduced GitHub Codespaces that provides VS Code environment on the web. To run VS Code server via ColabCodes, do the following: from colabcode import ColabCodeColabCode() You will be prompted with a ngrok URL and after the loading is completed, you will have the VS Code running on your web browser like this: Similarly, if you want to open a Jupyter lab server, pass the lab parameter as true and code false. from colabcode import ColabCodeColabCode(code=False, lab=True) You will get a URL and a token for authentication to the server. Enter the token and hit login to get a screen similar to this: In this article, I explained what the ColabCode offers with a little introduction to FastAPI. Currently, v0.2.0 is released by Abhishek Thakur, the creator of this package. Check out the GitHub repository of this package if you wish to contribute. With this said, it’s the end of this article, I hope you got something new to ponder about and I will pop in your feeds via some other articles! My Linkedin: www.linkedin.com My Other Popular Articles:
[ { "code": null, "e": 539, "s": 171, "text": "Google colab is the handiest online IDE for Python and Data Science enthusiasts. Released in 2017 for the public, it was initially an internal project used by the Google research team to collaborate on different AI projects. Since then, it has gained a lot of popularity due to its easy to use interface, Jupyter notebooks similarity, and GPU support gave it a boost." }, { "code": null, "e": 941, "s": 539, "text": "Most of the popular machine learning libraries such as numpy, pandas, seaborn, matplotlib, sklearn, TensorFlow come pre-installed in this cloud environment so you don’t require any explicit prerequisite. You can also install any python package of your choice to run your code. In this article, I will explain to you a simple way to deploy your machine learning model as an API using FastAPI and ngrok." }, { "code": null, "e": 1484, "s": 941, "text": "It is a high-performance web framework to build APIs in Python. Traditionally, most of the developers used flask as the first option to build the API but due to some of the limitations but not limited to data validation, authentication, async, and many more, FastAPI gained a lot of popularity. FastAPI offers automatic docs generation functionality, authentication, data validation via pydantic models. To know more about the significant differences between the two frameworks in detail, you can check-out my article on Analytics Vidya here:" }, { "code": null, "e": 1508, "s": 1484, "text": "www.analyticsvidhya.com" }, { "code": null, "e": 1932, "s": 1508, "text": "FastAPI helps in setting up the production-ready server but what if you want to share this with your team before deploying it in an actual cloud platform such as Heroku. The ngrok comes to the rescue by tunneling your localhost and exposing it to the internet. Now, anyone can access your API endpoint via the link provided but what if, all of this could be done on the Google Colab only? The solution to this is ColabCode!" }, { "code": null, "e": 2465, "s": 1932, "text": "It is a Python package that allows you to start a code server right from your Colab notebooks without setting up anything locally on your system. It can be used to start a VS Code environment, Jupyter Lab server, or tunnel the FastAPI server to the web, all in the colab notebook. This can be a great plus point for the enthusiast coders who train their models on the cloud and now want to share their findings with the world in the form of APIs. We will discuss all the functions of ColabCode as we go till the end of this article." }, { "code": null, "e": 2940, "s": 2465, "text": "The problem statement I would be using for this article is a decision tree classifier to classify between two music genres: Hip-Hop or Rock. I have already done the cleaning of the dataset and it is available on my GitHub repository. Now that I have the dataset, I have simply imported it into the notebook and trained a decision tree model without any preprocessing or EDA stuff as this article is more about deployment. Therefore, this model may return some wrong results!" }, { "code": null, "e": 3444, "s": 2940, "text": "Now, if you are aware of the FastAPI architecture, we will require a data class for the inputs. This data class allows FastAPI to validate the inputs to be sent to the model and if any wrong input is given, it simply raises the error without giving it to the model.Creating a data class is pretty straightforward and requires only the parameters to be accepted along with the data type. To further customize, you can also add a custom example to quickly test out the results. The code for this class is:" }, { "code": null, "e": 3710, "s": 3444, "text": "Now, if you are aware of the FastAPI architecture, we will require a data class for the inputs. This data class allows FastAPI to validate the inputs to be sent to the model and if any wrong input is given, it simply raises the error without giving it to the model." }, { "code": null, "e": 3949, "s": 3710, "text": "Creating a data class is pretty straightforward and requires only the parameters to be accepted along with the data type. To further customize, you can also add a custom example to quickly test out the results. The code for this class is:" }, { "code": null, "e": 4170, "s": 3949, "text": "3. Now, we need to create an endpoint where all the requests will be served. The endpoint creation in FastAPI is very similar to the flask and only requires the endpoint function to take in the data class for validation." }, { "code": null, "e": 4246, "s": 4170, "text": "If you wish to explore some cool projects then check out my GitHub profile:" }, { "code": null, "e": 4257, "s": 4246, "text": "github.com" }, { "code": null, "e": 4406, "s": 4257, "text": "Our FastAPI is ready and now the only thing needed is to run this via the colab environment. Firstly, import this package and initialize the server:" }, { "code": null, "e": 4480, "s": 4406, "text": "from colabcode import ColabCodeserver = ColabCode(port=10000, code=False)" }, { "code": null, "e": 4712, "s": 4480, "text": "The port number can be of your choice and the code parameter should be false. Now, the server is ready to receive the FastAPI object and with the help of ngrok, the local host is tunneled and exposed to the public via a unique URL." }, { "code": null, "e": 4736, "s": 4712, "text": "server.run_app(app=app)" }, { "code": null, "e": 5015, "s": 4736, "text": "And that’ it! You will get a ngrok URL which you can share with your community, team, or whichever person. The link will expire as soon as you terminate the cell process and if you don’t, Google Colab terminates it after some time. An example GIF of this process is shown below:" }, { "code": null, "e": 5292, "s": 5015, "text": "Here, after clicking on the link, I navigated to the endpoint /docs that the FastAPI generates automatically, and here, we can test out the results. The whole notebook code is available here if you want to run and try this thing. Just open this notebook and run all the cells." }, { "code": null, "e": 5733, "s": 5292, "text": "ColabCode is not limited to running FastAPI codes on Colab but it can also provide VS code server and Jupyter Lab server! It can help users to have a familiar environment on the cloud-based services. A user with very limited resources can also benefit from these services. It becomes very similar to the newly introduced GitHub Codespaces that provides VS Code environment on the web. To run VS Code server via ColabCodes, do the following:" }, { "code": null, "e": 5776, "s": 5733, "text": "from colabcode import ColabCodeColabCode()" }, { "code": null, "e": 5915, "s": 5776, "text": "You will be prompted with a ngrok URL and after the loading is completed, you will have the VS Code running on your web browser like this:" }, { "code": null, "e": 6015, "s": 5915, "text": "Similarly, if you want to open a Jupyter lab server, pass the lab parameter as true and code false." }, { "code": null, "e": 6078, "s": 6015, "text": "from colabcode import ColabCodeColabCode(code=False, lab=True)" }, { "code": null, "e": 6206, "s": 6078, "text": "You will get a URL and a token for authentication to the server. Enter the token and hit login to get a screen similar to this:" }, { "code": null, "e": 6454, "s": 6206, "text": "In this article, I explained what the ColabCode offers with a little introduction to FastAPI. Currently, v0.2.0 is released by Abhishek Thakur, the creator of this package. Check out the GitHub repository of this package if you wish to contribute." }, { "code": null, "e": 6599, "s": 6454, "text": "With this said, it’s the end of this article, I hope you got something new to ponder about and I will pop in your feeds via some other articles!" }, { "code": null, "e": 6612, "s": 6599, "text": "My Linkedin:" }, { "code": null, "e": 6629, "s": 6612, "text": "www.linkedin.com" } ]
Fork() Bomb
22 Jul, 2021 Prerequisite : fork() in CFork Bomb is a program that harms a system by making it run out of memory. It forks processes infinitely to fill memory. The fork bomb is a form of denial-of-service (DoS) attack against a Linux based system.Once a successful fork bomb has been activated in a system it may not be possible to resume normal operation without rebooting the system as the only solution to a fork bomb is to destroy all instances of it. C program for Fork Bomb C // C program Sample for FORK BOMB// It is not recommended to run the program as// it may make a system non-responsive.#include <stdio.h>#include <sys/types.h> int main(){ while(1) fork(); return 0;} Bash Script for Fork Bomb Note : Please do not run this command to ‘test’ it unless you are prepared for a crash and/or force-rebooting your system. Also, it doesn’t need root to run.If you using terminal then bash script for fork() bomb script as below. :(){ :|: & };: Step by Step Explanation of the script: :() means you are defining a function called :{:|: &} means run the function: and send its output to the : function again and run that in the background. : – load another copy of the ‘:’ function into memory| – and pipe its output to: – another copy of ‘:’ function, which has to be loaded into memoryTherefore, ‘:|:’ simply gets two copies of ‘:’ loaded whenever ‘:’ is called& – disown the functions, if the first ‘:’ is killed, all of the functions that it has started should NOT be auto-killed} – end of what to do when we say ‘:’; Command Separator: runs the function first time :() means you are defining a function called : {:|: &} means run the function: and send its output to the : function again and run that in the background. : – load another copy of the ‘:’ function into memory| – and pipe its output to: – another copy of ‘:’ function, which has to be loaded into memoryTherefore, ‘:|:’ simply gets two copies of ‘:’ loaded whenever ‘:’ is called& – disown the functions, if the first ‘:’ is killed, all of the functions that it has started should NOT be auto-killed} – end of what to do when we say ‘:’ : – load another copy of the ‘:’ function into memory | – and pipe its output to : – another copy of ‘:’ function, which has to be loaded into memory Therefore, ‘:|:’ simply gets two copies of ‘:’ loaded whenever ‘:’ is called & – disown the functions, if the first ‘:’ is killed, all of the functions that it has started should NOT be auto-killed } – end of what to do when we say ‘:’ ; Command Separator : runs the function first time Essentially you are creating a function that calls itself twice every call and doesn’t have any way to terminate itself. It will keep doubling up until you run out of system resources. How it Works Fork bombs operate both by consuming CPU time in the process of forking, and by saturating the operating system’s process table. A basic implementation of a fork bomb is an infinite loop that repeatedly launches new copies of itself. To incapacitate a system, they rely on the assumption that the number of programs and processes which may execute simultaneously on a computer. fork() will generate new process but if you put this process in while true loop, then it will create many processes and when the limit is crossed, your system will crash. Way to prevent the fork() Bomb Avoid use of fork in any statement which might end up into an infinite loop. You can limit the process of fork as below:-Just login as root, and edit this file, to add users and configure, their limit. # vi /etc/security/limits.conf Edit the file as: your_user_name hard nproc 10 You can try Running the command in Virtualbox if you want to run it. Direct power off your system just in case you have run it and not finding a way out to proceed. References: Wikipedia Ask ubuntu This article is contributed by Dhavalkumar Prajapati. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. anikakapoor C Language Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Substring in C++ Function Pointer in C Different Methods to Reverse a String in C++ std::string class in C++ Unordered Sets in C++ Standard Template Library Sed Command in Linux/Unix with examples AWK command in Unix/Linux with examples grep command in Unix/Linux cut command in Linux with examples cp command in Linux with examples
[ { "code": null, "e": 53, "s": 25, "text": "\n22 Jul, 2021" }, { "code": null, "e": 496, "s": 53, "text": "Prerequisite : fork() in CFork Bomb is a program that harms a system by making it run out of memory. It forks processes infinitely to fill memory. The fork bomb is a form of denial-of-service (DoS) attack against a Linux based system.Once a successful fork bomb has been activated in a system it may not be possible to resume normal operation without rebooting the system as the only solution to a fork bomb is to destroy all instances of it." }, { "code": null, "e": 520, "s": 496, "text": "C program for Fork Bomb" }, { "code": null, "e": 522, "s": 520, "text": "C" }, { "code": "// C program Sample for FORK BOMB// It is not recommended to run the program as// it may make a system non-responsive.#include <stdio.h>#include <sys/types.h> int main(){ while(1) fork(); return 0;}", "e": 737, "s": 522, "text": null }, { "code": null, "e": 763, "s": 737, "text": "Bash Script for Fork Bomb" }, { "code": null, "e": 992, "s": 763, "text": "Note : Please do not run this command to ‘test’ it unless you are prepared for a crash and/or force-rebooting your system. Also, it doesn’t need root to run.If you using terminal then bash script for fork() bomb script as below." }, { "code": null, "e": 1007, "s": 992, "text": ":(){ :|: & };:" }, { "code": null, "e": 1047, "s": 1007, "text": "Step by Step Explanation of the script:" }, { "code": null, "e": 1631, "s": 1047, "text": ":() means you are defining a function called :{:|: &} means run the function: and send its output to the : function again and run that in the background. : – load another copy of the ‘:’ function into memory| – and pipe its output to: – another copy of ‘:’ function, which has to be loaded into memoryTherefore, ‘:|:’ simply gets two copies of ‘:’ loaded whenever ‘:’ is called& – disown the functions, if the first ‘:’ is killed, all of the functions that it has started should NOT be auto-killed} – end of what to do when we say ‘:’; Command Separator: runs the function first time" }, { "code": null, "e": 1678, "s": 1631, "text": ":() means you are defining a function called :" }, { "code": null, "e": 1786, "s": 1678, "text": "{:|: &} means run the function: and send its output to the : function again and run that in the background." }, { "code": null, "e": 2168, "s": 1786, "text": " : – load another copy of the ‘:’ function into memory| – and pipe its output to: – another copy of ‘:’ function, which has to be loaded into memoryTherefore, ‘:|:’ simply gets two copies of ‘:’ loaded whenever ‘:’ is called& – disown the functions, if the first ‘:’ is killed, all of the functions that it has started should NOT be auto-killed} – end of what to do when we say ‘:’" }, { "code": null, "e": 2222, "s": 2168, "text": ": – load another copy of the ‘:’ function into memory" }, { "code": null, "e": 2249, "s": 2222, "text": "| – and pipe its output to" }, { "code": null, "e": 2318, "s": 2249, "text": ": – another copy of ‘:’ function, which has to be loaded into memory" }, { "code": null, "e": 2395, "s": 2318, "text": "Therefore, ‘:|:’ simply gets two copies of ‘:’ loaded whenever ‘:’ is called" }, { "code": null, "e": 2516, "s": 2395, "text": "& – disown the functions, if the first ‘:’ is killed, all of the functions that it has started should NOT be auto-killed" }, { "code": null, "e": 2554, "s": 2516, "text": "} – end of what to do when we say ‘:’" }, { "code": null, "e": 2574, "s": 2554, "text": "; Command Separator" }, { "code": null, "e": 2605, "s": 2574, "text": ": runs the function first time" }, { "code": null, "e": 2790, "s": 2605, "text": "Essentially you are creating a function that calls itself twice every call and doesn’t have any way to terminate itself. It will keep doubling up until you run out of system resources." }, { "code": null, "e": 2803, "s": 2790, "text": "How it Works" }, { "code": null, "e": 3352, "s": 2803, "text": "Fork bombs operate both by consuming CPU time in the process of forking, and by saturating the operating system’s process table. A basic implementation of a fork bomb is an infinite loop that repeatedly launches new copies of itself. To incapacitate a system, they rely on the assumption that the number of programs and processes which may execute simultaneously on a computer. fork() will generate new process but if you put this process in while true loop, then it will create many processes and when the limit is crossed, your system will crash." }, { "code": null, "e": 3383, "s": 3352, "text": "Way to prevent the fork() Bomb" }, { "code": null, "e": 3460, "s": 3383, "text": "Avoid use of fork in any statement which might end up into an infinite loop." }, { "code": null, "e": 3585, "s": 3460, "text": "You can limit the process of fork as below:-Just login as root, and edit this file, to add users and configure, their limit." }, { "code": null, "e": 3616, "s": 3585, "text": "# vi /etc/security/limits.conf" }, { "code": null, "e": 3634, "s": 3616, "text": "Edit the file as:" }, { "code": null, "e": 3664, "s": 3634, "text": " your_user_name hard nproc 10" }, { "code": null, "e": 3733, "s": 3664, "text": "You can try Running the command in Virtualbox if you want to run it." }, { "code": null, "e": 3829, "s": 3733, "text": "Direct power off your system just in case you have run it and not finding a way out to proceed." }, { "code": null, "e": 3841, "s": 3829, "text": "References:" }, { "code": null, "e": 3851, "s": 3841, "text": "Wikipedia" }, { "code": null, "e": 3862, "s": 3851, "text": "Ask ubuntu" }, { "code": null, "e": 4167, "s": 3862, "text": "This article is contributed by Dhavalkumar Prajapati. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 4293, "s": 4167, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 4305, "s": 4293, "text": "anikakapoor" }, { "code": null, "e": 4316, "s": 4305, "text": "C Language" }, { "code": null, "e": 4327, "s": 4316, "text": "Linux-Unix" }, { "code": null, "e": 4425, "s": 4327, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4442, "s": 4425, "text": "Substring in C++" }, { "code": null, "e": 4464, "s": 4442, "text": "Function Pointer in C" }, { "code": null, "e": 4509, "s": 4464, "text": "Different Methods to Reverse a String in C++" }, { "code": null, "e": 4534, "s": 4509, "text": "std::string class in C++" }, { "code": null, "e": 4582, "s": 4534, "text": "Unordered Sets in C++ Standard Template Library" }, { "code": null, "e": 4622, "s": 4582, "text": "Sed Command in Linux/Unix with examples" }, { "code": null, "e": 4662, "s": 4622, "text": "AWK command in Unix/Linux with examples" }, { "code": null, "e": 4689, "s": 4662, "text": "grep command in Unix/Linux" }, { "code": null, "e": 4724, "s": 4689, "text": "cut command in Linux with examples" } ]
How To Modify MAC address in Windows 10 (Both Wired and Wireless Adapter)?
19 Jan, 2021 Prerequisite – Introduction of MAC Address, and Difference between MAC Address and IP Address A Media Access Control address is unique in nature which is doled out to a Network Interface Card to be utilized as a network address in communications within a network. In the Open Systems Interconnection network model, these addresses are utilized under the data link layer. Network nodes with multiple network interfaces, like routers and multi-layer switches, should have a single MAC address for every NIC. MAC addresses are regularly utilized for different purposes: Static IP Assignment:Routers permit you to allot static IP to your PCs. MAC Address Filtering:Networks can utilize this option, just permitting gadgets with explicit MAC address to have an interface with a system. MAC Authentication:Some Internet specialist co-ops may require validation with a MAC address and just permit a gadget with that MAC address to associate with the Internet. Device Identification:Many air terminal Wi-Fi systems and other open Wi-Fi systems utilize a gadget’s MAC address to recognize it. Device Tracking:Because they’re distinctive in nature, MAC can be utilized to follow you. Note: Use the following steps for ethical purposes only. EASY METHOD: Step 1: Right-Click on the Windows Start button which is located on the bottom-left corner of your screen. Step 2: Select the Device Manager option. Now, foremost we are going to change the Ethernet(Wired Medium) adapter’s MAC address. Step 3: Click on Network adapters. Step 4: Right-Click the Network Adapter(in this case the Ethernet NIC which is ”Realtek PCIe Gbe Family Controller”) you want to change and then, select the Properties option. Step 5: Go through the Advanced Tab and then, select the Locally Administered Address(Network Address). Step 6: Specify the new MAC address and then, Click OK. If the MAC address change fails try setting the second character to 2 or 6 or A or E(Make sure to enter exactly 12 digits in the empty field of value). Step 7.0: Use a command prompt command to verify the MAC address change. Step 7.1: Use the following command in order to verify that the MAC address has been changed or not: getmac Now, we can see that the desired NIC’s MAC Address has been changed. TRICKY METHOD: Step 1: Open a command prompt by typing ‘cmd’ in the search bar and clicking on open. Step 2: Type in the following command in order to find the MAC address and transport name: getmac Step 3: Click Device Manager. Now secondly, we are going to change the wireless medium network adapter’s MAC address. Step 4: Right-click on Network adapters, and select Properties option.(Here, in this case, the NIC is “Intel(R) Wireless-AC 9560 160MHZ”.) Step 5: Now, we can go to the Advanced Tab, and then we can change the MAC address as earlier. But, here, in the case of this NIC, we don’t have any option of network address as in the earlier case, so we have to follow the Value Changing Process in the Registry of Windows 10. This is the hard method and this uses the Windows Registry, so we have to be careful while making the required changes. Step 1: Firstly, go to open a command prompt shell, and then type “getmac” in order to see the Transport Address as well as MAC Address. Step 2: Now, in order to know what is the Wireless NIC’s MAC address, we can navigate to the Network & Internet Settings, and then right-click on the Wifi option, from there select the properties option which will show you the required details. Step 3: Now, firstly click on the Start button and type “Registry Editor” and open it. Step 4.0: Now, we have to navigate into a specific folder which is: "HKEY_LOCAL_MACHINE/SYSTEM/ControlSet001/Control/Class/{4D36E972-E325-11CE-BFC1-08002BE10318}" Step 4.1: Firstly, in order to get into the correct folder, we can easily direct till the Class directory and from there on we can follow the next steps: Step 4.2: Right-click on the class folder and select the find option, and then copy the first part of the transport name which is mention in the Wireless Network MAC address row against the physical address. Step 4.3: Now, paste the highlighted text into the empty search bar in a previously selected find option: Step 4.4: Now, click on the “Find Next” button, and then you will be redirected to the required folder and the sub-directory automatically. Step 4.5: Verify that the “NetCfgInstanceId” (this will be shown on the right-hand side on the window) is the same as the value shown in the “getmac” command. Step 5: Now, Right-click on the white-space on the right-hand side of the window opened and choose to create a string value with the name NetworkAddress. Step 6: Right Click on the NetworkAddress string created and then select the Modify option and then, specify your MAC address. Note: If the MAC address change fails try setting the second character to 2 or 6 or A or E. Step 7: Now, the MAC address has been changed so, in order to verify the changes we have to Wireless Network Adapter option in Control Panel and Disable it by right-clicking on it, then after few seconds we will double click on the same icon in order to re-enable the Wireless NIC. Step 8: Right-click on the same icon in order to go to the properties for verifying the changed MAC Address. Now, we can see that the Physical Address has been changed accordingly. Step 9: Use the ‘getmac’ command to verify that the MAC address has changed. Now, the MAC Address has been changed successfully! Sources: 1.https://en.wikipedia.org/wiki/MAC_address Computer Networks How To Operating Systems Operating Systems Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GSM in Wireless Communication Secure Socket Layer (SSL) Wireless Application Protocol Mobile Internet Protocol (or Mobile IP) Introduction of Mobile Ad hoc Network (MANET) How to Install PIP on Windows ? How to Find the Wi-Fi Password Using CMD in Windows? How to install Jupyter Notebook on Windows? Java Tutorial How to filter object array based on attributes?
[ { "code": null, "e": 28, "s": 0, "text": "\n19 Jan, 2021" }, { "code": null, "e": 122, "s": 28, "text": "Prerequisite – Introduction of MAC Address, and Difference between MAC Address and IP Address" }, { "code": null, "e": 596, "s": 122, "text": "A Media Access Control address is unique in nature which is doled out to a Network Interface Card to be utilized as a network address in communications within a network. In the Open Systems Interconnection network model, these addresses are utilized under the data link layer. Network nodes with multiple network interfaces, like routers and multi-layer switches, should have a single MAC address for every NIC. MAC addresses are regularly utilized for different purposes: " }, { "code": null, "e": 668, "s": 596, "text": "Static IP Assignment:Routers permit you to allot static IP to your PCs." }, { "code": null, "e": 810, "s": 668, "text": "MAC Address Filtering:Networks can utilize this option, just permitting gadgets with explicit MAC address to have an interface with a system." }, { "code": null, "e": 982, "s": 810, "text": "MAC Authentication:Some Internet specialist co-ops may require validation with a MAC address and just permit a gadget with that MAC address to associate with the Internet." }, { "code": null, "e": 1113, "s": 982, "text": "Device Identification:Many air terminal Wi-Fi systems and other open Wi-Fi systems utilize a gadget’s MAC address to recognize it." }, { "code": null, "e": 1203, "s": 1113, "text": "Device Tracking:Because they’re distinctive in nature, MAC can be utilized to follow you." }, { "code": null, "e": 1260, "s": 1203, "text": "Note: Use the following steps for ethical purposes only." }, { "code": null, "e": 1274, "s": 1260, "text": "EASY METHOD: " }, { "code": null, "e": 1381, "s": 1274, "text": "Step 1: Right-Click on the Windows Start button which is located on the bottom-left corner of your screen." }, { "code": null, "e": 1423, "s": 1381, "text": "Step 2: Select the Device Manager option." }, { "code": null, "e": 1510, "s": 1423, "text": "Now, foremost we are going to change the Ethernet(Wired Medium) adapter’s MAC address." }, { "code": null, "e": 1545, "s": 1510, "text": "Step 3: Click on Network adapters." }, { "code": null, "e": 1721, "s": 1545, "text": "Step 4: Right-Click the Network Adapter(in this case the Ethernet NIC which is ”Realtek PCIe Gbe Family Controller”) you want to change and then, select the Properties option." }, { "code": null, "e": 1825, "s": 1721, "text": "Step 5: Go through the Advanced Tab and then, select the Locally Administered Address(Network Address)." }, { "code": null, "e": 2033, "s": 1825, "text": "Step 6: Specify the new MAC address and then, Click OK. If the MAC address change fails try setting the second character to 2 or 6 or A or E(Make sure to enter exactly 12 digits in the empty field of value)." }, { "code": null, "e": 2106, "s": 2033, "text": "Step 7.0: Use a command prompt command to verify the MAC address change." }, { "code": null, "e": 2207, "s": 2106, "text": "Step 7.1: Use the following command in order to verify that the MAC address has been changed or not:" }, { "code": null, "e": 2214, "s": 2207, "text": "getmac" }, { "code": null, "e": 2283, "s": 2214, "text": "Now, we can see that the desired NIC’s MAC Address has been changed." }, { "code": null, "e": 2298, "s": 2283, "text": "TRICKY METHOD:" }, { "code": null, "e": 2384, "s": 2298, "text": "Step 1: Open a command prompt by typing ‘cmd’ in the search bar and clicking on open." }, { "code": null, "e": 2475, "s": 2384, "text": "Step 2: Type in the following command in order to find the MAC address and transport name:" }, { "code": null, "e": 2482, "s": 2475, "text": "getmac" }, { "code": null, "e": 2512, "s": 2482, "text": "Step 3: Click Device Manager." }, { "code": null, "e": 2600, "s": 2512, "text": "Now secondly, we are going to change the wireless medium network adapter’s MAC address." }, { "code": null, "e": 2739, "s": 2600, "text": "Step 4: Right-click on Network adapters, and select Properties option.(Here, in this case, the NIC is “Intel(R) Wireless-AC 9560 160MHZ”.)" }, { "code": null, "e": 2834, "s": 2739, "text": "Step 5: Now, we can go to the Advanced Tab, and then we can change the MAC address as earlier." }, { "code": null, "e": 3017, "s": 2834, "text": "But, here, in the case of this NIC, we don’t have any option of network address as in the earlier case, so we have to follow the Value Changing Process in the Registry of Windows 10." }, { "code": null, "e": 3137, "s": 3017, "text": "This is the hard method and this uses the Windows Registry, so we have to be careful while making the required changes." }, { "code": null, "e": 3274, "s": 3137, "text": "Step 1: Firstly, go to open a command prompt shell, and then type “getmac” in order to see the Transport Address as well as MAC Address." }, { "code": null, "e": 3519, "s": 3274, "text": "Step 2: Now, in order to know what is the Wireless NIC’s MAC address, we can navigate to the Network & Internet Settings, and then right-click on the Wifi option, from there select the properties option which will show you the required details." }, { "code": null, "e": 3606, "s": 3519, "text": "Step 3: Now, firstly click on the Start button and type “Registry Editor” and open it." }, { "code": null, "e": 3674, "s": 3606, "text": "Step 4.0: Now, we have to navigate into a specific folder which is:" }, { "code": null, "e": 3769, "s": 3674, "text": "\"HKEY_LOCAL_MACHINE/SYSTEM/ControlSet001/Control/Class/{4D36E972-E325-11CE-BFC1-08002BE10318}\"" }, { "code": null, "e": 3923, "s": 3769, "text": "Step 4.1: Firstly, in order to get into the correct folder, we can easily direct till the Class directory and from there on we can follow the next steps:" }, { "code": null, "e": 4131, "s": 3923, "text": "Step 4.2: Right-click on the class folder and select the find option, and then copy the first part of the transport name which is mention in the Wireless Network MAC address row against the physical address." }, { "code": null, "e": 4237, "s": 4131, "text": "Step 4.3: Now, paste the highlighted text into the empty search bar in a previously selected find option:" }, { "code": null, "e": 4377, "s": 4237, "text": "Step 4.4: Now, click on the “Find Next” button, and then you will be redirected to the required folder and the sub-directory automatically." }, { "code": null, "e": 4536, "s": 4377, "text": "Step 4.5: Verify that the “NetCfgInstanceId” (this will be shown on the right-hand side on the window) is the same as the value shown in the “getmac” command." }, { "code": null, "e": 4690, "s": 4536, "text": "Step 5: Now, Right-click on the white-space on the right-hand side of the window opened and choose to create a string value with the name NetworkAddress." }, { "code": null, "e": 4817, "s": 4690, "text": "Step 6: Right Click on the NetworkAddress string created and then select the Modify option and then, specify your MAC address." }, { "code": null, "e": 4909, "s": 4817, "text": "Note: If the MAC address change fails try setting the second character to 2 or 6 or A or E." }, { "code": null, "e": 5191, "s": 4909, "text": "Step 7: Now, the MAC address has been changed so, in order to verify the changes we have to Wireless Network Adapter option in Control Panel and Disable it by right-clicking on it, then after few seconds we will double click on the same icon in order to re-enable the Wireless NIC." }, { "code": null, "e": 5300, "s": 5191, "text": "Step 8: Right-click on the same icon in order to go to the properties for verifying the changed MAC Address." }, { "code": null, "e": 5372, "s": 5300, "text": "Now, we can see that the Physical Address has been changed accordingly." }, { "code": null, "e": 5449, "s": 5372, "text": "Step 9: Use the ‘getmac’ command to verify that the MAC address has changed." }, { "code": null, "e": 5501, "s": 5449, "text": "Now, the MAC Address has been changed successfully!" }, { "code": null, "e": 5510, "s": 5501, "text": "Sources:" }, { "code": null, "e": 5554, "s": 5510, "text": "1.https://en.wikipedia.org/wiki/MAC_address" }, { "code": null, "e": 5572, "s": 5554, "text": "Computer Networks" }, { "code": null, "e": 5579, "s": 5572, "text": "How To" }, { "code": null, "e": 5597, "s": 5579, "text": "Operating Systems" }, { "code": null, "e": 5615, "s": 5597, "text": "Operating Systems" }, { "code": null, "e": 5633, "s": 5615, "text": "Computer Networks" }, { "code": null, "e": 5731, "s": 5633, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5761, "s": 5731, "text": "GSM in Wireless Communication" }, { "code": null, "e": 5787, "s": 5761, "text": "Secure Socket Layer (SSL)" }, { "code": null, "e": 5817, "s": 5787, "text": "Wireless Application Protocol" }, { "code": null, "e": 5857, "s": 5817, "text": "Mobile Internet Protocol (or Mobile IP)" }, { "code": null, "e": 5903, "s": 5857, "text": "Introduction of Mobile Ad hoc Network (MANET)" }, { "code": null, "e": 5935, "s": 5903, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 5988, "s": 5935, "text": "How to Find the Wi-Fi Password Using CMD in Windows?" }, { "code": null, "e": 6032, "s": 5988, "text": "How to install Jupyter Notebook on Windows?" }, { "code": null, "e": 6046, "s": 6032, "text": "Java Tutorial" } ]
How to align items at the center of the container using CSS ?
17 Mar, 2021 An easy and common task for CSS is to align text or images into the center of any container. Syntax: .container{ text-align: center; } Example 1: We use the text-align property of CSS to center the item horizontally followed by the vertical-align and display property to align the item to the center of the container vertically. Below examples illustrate the approach: HTML <!DOCTYPE html><html> <head> <style> .container{ text-align: center; height: 200px; width : 200px; display: table-cell; vertical-align: middle; border: 2px solid green; } </style> </head> <body> <div class="container"> <p>Centered Text</p> </div> </body></html> Output : Text is centered in the container Example 2: Another method is to use the text-align property to center the item horizontally with the line-height property to align the items at the center of the container vertically. Below examples illustrate the approach: HTML <!DOCTYPE html><html> <head> <style> .container2{ width: 200px; line-height: 180px; height: 200px; text-align: center; border: 2px solid green; } </style> </head> <body> <div class="container2"> <p>Centered Text</p> </div> </body></html> Output: Text is centered in the container CSS-Properties CSS-Questions Picked CSS 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 Mar, 2021" }, { "code": null, "e": 121, "s": 28, "text": "An easy and common task for CSS is to align text or images into the center of any container." }, { "code": null, "e": 129, "s": 121, "text": "Syntax:" }, { "code": null, "e": 174, "s": 129, "text": ".container{\n text-align: center;\n}\n" }, { "code": null, "e": 408, "s": 174, "text": "Example 1: We use the text-align property of CSS to center the item horizontally followed by the vertical-align and display property to align the item to the center of the container vertically. Below examples illustrate the approach:" }, { "code": null, "e": 413, "s": 408, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <style> .container{ text-align: center; height: 200px; width : 200px; display: table-cell; vertical-align: middle; border: 2px solid green; } </style> </head> <body> <div class=\"container\"> <p>Centered Text</p> </div> </body></html>", "e": 838, "s": 413, "text": null }, { "code": null, "e": 847, "s": 838, "text": "Output :" }, { "code": null, "e": 881, "s": 847, "text": "Text is centered in the container" }, { "code": null, "e": 1105, "s": 881, "text": "Example 2: Another method is to use the text-align property to center the item horizontally with the line-height property to align the items at the center of the container vertically. Below examples illustrate the approach:" }, { "code": null, "e": 1110, "s": 1105, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <style> .container2{ width: 200px; line-height: 180px; height: 200px; text-align: center; border: 2px solid green; } </style> </head> <body> <div class=\"container2\"> <p>Centered Text</p> </div> </body></html>", "e": 1496, "s": 1110, "text": null }, { "code": null, "e": 1504, "s": 1496, "text": "Output:" }, { "code": null, "e": 1538, "s": 1504, "text": "Text is centered in the container" }, { "code": null, "e": 1553, "s": 1538, "text": "CSS-Properties" }, { "code": null, "e": 1567, "s": 1553, "text": "CSS-Questions" }, { "code": null, "e": 1574, "s": 1567, "text": "Picked" }, { "code": null, "e": 1578, "s": 1574, "text": "CSS" }, { "code": null, "e": 1595, "s": 1578, "text": "Web Technologies" } ]
What is Git-Ignore and How to Use it?
10 Jul, 2020 There are various types of files we might want the git to ignore before committing, for example, the files that are to do with our user settings or any utility setting, private files like passwords and API keys. These files are not of any use to anyone else and we do not want to clutter our git. We can do this with the help of “.gitignore” .gitignore is an auto-generated file inside the project folder that ignores/prevents files to get committed to the local and remote repositories. .gitignore can be used in Git with the help of following steps: Step 1: Open your terminal/cmd and change your directory to the folder where your files are located. You can use ” ls -a” command to view its contents. cd directory(or)folder ls -a Here, the project files are saved inside folder named story which is further inside web development. Here, we want git to ignore the secrets.txt file. Step 2: Create .gitignore File inside the project folder. Step 3: Write the name of the files you want to ignore in the .gitignore text file. Each file name should be written in a new line . Step 4: Initialize git in your terminal. Add these files to your git repository and commit all the changes with an appropriate message. git init git add . git commit -m "your message" Step 5: Check the status of the repository. The file(s) added to the .gitignore text file will be ignored by the git every time you make any changes and commit. git status Some common patterns and format for Git-Ignore : Blank Line: A blank line doesn’t refer to any file name, so we can use it to separate two file names for the ease of reading . #: A line beginning with the # symbol refers to a comment .However if # is used as a pattern then use backslash (“\”) before the # symbol so that it is not misunderstood as a comment. /: It is used as a directory separator i.e to include directories, for example webdev/ . *.extension_name: For example *.txt and *.log can be used to match ALL the files that have .txt and .log as their extension respectively. **/any_name: It is used to match any file or directory with the name any_name. any_name/**: It is used to match anything that is inside the directory of the name any_name. for example webdev/** matches all the files inside webdev directory. Examples: # Compiled class file *.class # Log file *.log # Mobile Tools for Java (J2ME) .mtj.tmp/ # Package Files *.jar *.war *.nar *.ear *.zip *.tar.gz *.rar Before using .gitignore to ignore certain files, if you have already committed files you didn’t want to here’s how you can undo it. Use the following command on Git Bash to undo a commit: git rm --cached -r Here, “rm” stands for remove while “r” stands for recursive. Note: Head over to the GitHub and search for gitignore repositories, you will find a list of gitignore repositories contributed by various people. GitHub Git Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n10 Jul, 2020" }, { "code": null, "e": 396, "s": 54, "text": "There are various types of files we might want the git to ignore before committing, for example, the files that are to do with our user settings or any utility setting, private files like passwords and API keys. These files are not of any use to anyone else and we do not want to clutter our git. We can do this with the help of “.gitignore”" }, { "code": null, "e": 542, "s": 396, "text": ".gitignore is an auto-generated file inside the project folder that ignores/prevents files to get committed to the local and remote repositories." }, { "code": null, "e": 606, "s": 542, "text": ".gitignore can be used in Git with the help of following steps:" }, { "code": null, "e": 758, "s": 606, "text": "Step 1: Open your terminal/cmd and change your directory to the folder where your files are located. You can use ” ls -a” command to view its contents." }, { "code": null, "e": 788, "s": 758, "text": "cd directory(or)folder\nls -a\n" }, { "code": null, "e": 939, "s": 788, "text": "Here, the project files are saved inside folder named story which is further inside web development. Here, we want git to ignore the secrets.txt file." }, { "code": null, "e": 997, "s": 939, "text": "Step 2: Create .gitignore File inside the project folder." }, { "code": null, "e": 1130, "s": 997, "text": "Step 3: Write the name of the files you want to ignore in the .gitignore text file. Each file name should be written in a new line ." }, { "code": null, "e": 1266, "s": 1130, "text": "Step 4: Initialize git in your terminal. Add these files to your git repository and commit all the changes with an appropriate message." }, { "code": null, "e": 1315, "s": 1266, "text": "git init\ngit add .\ngit commit -m \"your message\"\n" }, { "code": null, "e": 1476, "s": 1315, "text": "Step 5: Check the status of the repository. The file(s) added to the .gitignore text file will be ignored by the git every time you make any changes and commit." }, { "code": null, "e": 1487, "s": 1476, "text": "git status" }, { "code": null, "e": 1536, "s": 1487, "text": "Some common patterns and format for Git-Ignore :" }, { "code": null, "e": 1663, "s": 1536, "text": "Blank Line: A blank line doesn’t refer to any file name, so we can use it to separate two file names for the ease of reading ." }, { "code": null, "e": 1847, "s": 1663, "text": "#: A line beginning with the # symbol refers to a comment .However if # is used as a pattern then use backslash (“\\”) before the # symbol so that it is not misunderstood as a comment." }, { "code": null, "e": 1937, "s": 1847, "text": "/: It is used as a directory separator i.e to include directories, for example webdev/ ." }, { "code": null, "e": 2075, "s": 1937, "text": "*.extension_name: For example *.txt and *.log can be used to match ALL the files that have .txt and .log as their extension respectively." }, { "code": null, "e": 2154, "s": 2075, "text": "**/any_name: It is used to match any file or directory with the name any_name." }, { "code": null, "e": 2316, "s": 2154, "text": "any_name/**: It is used to match anything that is inside the directory of the name any_name. for example webdev/** matches all the files inside webdev directory." }, { "code": null, "e": 2326, "s": 2316, "text": "Examples:" }, { "code": null, "e": 2486, "s": 2326, "text": "# Compiled class file\n*.class\n\n# Log file\n*.log\n\n# Mobile Tools for Java (J2ME)\n.mtj.tmp/\n\n# Package Files \n*.jar\n\n*.war\n\n*.nar\n\n*.ear\n\n*.zip\n\n*.tar.gz\n\n*.rar\n" }, { "code": null, "e": 2674, "s": 2486, "text": "Before using .gitignore to ignore certain files, if you have already committed files you didn’t want to here’s how you can undo it. Use the following command on Git Bash to undo a commit:" }, { "code": null, "e": 2693, "s": 2674, "text": "git rm --cached -r" }, { "code": null, "e": 2754, "s": 2693, "text": "Here, “rm” stands for remove while “r” stands for recursive." }, { "code": null, "e": 2901, "s": 2754, "text": "Note: Head over to the GitHub and search for gitignore repositories, you will find a list of gitignore repositories contributed by various people." }, { "code": null, "e": 2908, "s": 2901, "text": "GitHub" }, { "code": null, "e": 2912, "s": 2908, "text": "Git" } ]
statsmodels.durbin_watson() in Python
26 Mar, 2020 With the help of statsmodels.durbin_watson() method, we can get the durbin watson test statistics and it is equal to 2*(1-r), where r is autocorrelation between residual. Syntax : statsmodels.durbin_watson(residual)Return : Return a single floating point value of durbin watson. Example #1 :In this example we can see that by using statsmodels.durbin_watson() method, we are able to get the durbin watson test statistical value by using this method. # import numpy and statsmodelsimport numpy as npfrom statsmodels.stats.stattools import durbin_watson g = np.array([1, 2, 3])# Using statsmodels.durbin_watson() methodgfg = durbin_watson(g) print(gfg) Output : 0.14285714285714285 Example #2 : # import numpy and statsmodelsimport numpy as npfrom statsmodels.stats.stattools import durbin_watson g = np.array([1, 2, 3, 4, -3, -2, -1])# Using statsmodels.durbin_watson() methodgfg = durbin_watson(g) print(gfg) Output : 1.2272727272727273 Python-statsmodels Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | datetime.timedelta() function Python | Get unique values from a list
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Mar, 2020" }, { "code": null, "e": 199, "s": 28, "text": "With the help of statsmodels.durbin_watson() method, we can get the durbin watson test statistics and it is equal to 2*(1-r), where r is autocorrelation between residual." }, { "code": null, "e": 307, "s": 199, "text": "Syntax : statsmodels.durbin_watson(residual)Return : Return a single floating point value of durbin watson." }, { "code": null, "e": 478, "s": 307, "text": "Example #1 :In this example we can see that by using statsmodels.durbin_watson() method, we are able to get the durbin watson test statistical value by using this method." }, { "code": "# import numpy and statsmodelsimport numpy as npfrom statsmodels.stats.stattools import durbin_watson g = np.array([1, 2, 3])# Using statsmodels.durbin_watson() methodgfg = durbin_watson(g) print(gfg)", "e": 681, "s": 478, "text": null }, { "code": null, "e": 690, "s": 681, "text": "Output :" }, { "code": null, "e": 710, "s": 690, "text": "0.14285714285714285" }, { "code": null, "e": 723, "s": 710, "text": "Example #2 :" }, { "code": "# import numpy and statsmodelsimport numpy as npfrom statsmodels.stats.stattools import durbin_watson g = np.array([1, 2, 3, 4, -3, -2, -1])# Using statsmodels.durbin_watson() methodgfg = durbin_watson(g) print(gfg)", "e": 941, "s": 723, "text": null }, { "code": null, "e": 950, "s": 941, "text": "Output :" }, { "code": null, "e": 969, "s": 950, "text": "1.2272727272727273" }, { "code": null, "e": 988, "s": 969, "text": "Python-statsmodels" }, { "code": null, "e": 995, "s": 988, "text": "Python" }, { "code": null, "e": 1093, "s": 995, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1125, "s": 1093, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1152, "s": 1125, "text": "Python Classes and Objects" }, { "code": null, "e": 1173, "s": 1152, "text": "Python OOPs Concepts" }, { "code": null, "e": 1196, "s": 1173, "text": "Introduction To PYTHON" }, { "code": null, "e": 1252, "s": 1196, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 1283, "s": 1252, "text": "Python | os.path.join() method" }, { "code": null, "e": 1325, "s": 1283, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 1367, "s": 1325, "text": "Check if element exists in list in Python" }, { "code": null, "e": 1406, "s": 1367, "text": "Python | datetime.timedelta() function" } ]
Estimating a Homography Matrix - Yalda Zadeh, Sukrit Shashi Shankar | Towards Data Science
This short piece describes equations for estimating a 3 × 3 homography matrix. We first discuss the computation from intrinsic and extrinsic camera parameters; and wherever necessary, connect the formulation to the real-world camera specifications. We next present the computation methodology using two tuples of corresponding points, that are co-planar in their respective planes and avoid collinear degenerations. Let's consider a point in the 3D world-view space as a 3-tuple We can then map this 3D point to a point in an arbitrary space, as follows: where C_int is the intrinsic and C_ext is the extrinsic camera matrix respectively. The point (x_a, y_a, z_a) in the arbitrary space, can be mapped to the 2D image space by involving a scale factor as follows: Thus, once we have a point in the arbitrary space, we can simply scale its coordinates to get the 2D coordinates in the (captured) image space. Let us now see the form of C_int. Consider a camera with a focal length f (in mm), with actual sensor size (x_S, y_S) (in mm), and the width and the height of the captured image (effective sensor size) as (w,h) (in pixels).The optical centre (o_x, o_y) of the camera is then (w/2, h/2). We are now in a state to specify C_int as follows: One may thus observe that all entries in C_int are in the units of pixels. The following may be seen as the effective focal lengths in pixels in x and y directions respectively C_ext consists of a rotation matrix R and a translation matrix T as follows: The tuple (T_x, T_y, T_z) indicates the translation of the camera in the world-space coordinates. Typically, we can consider that the camera has no x and y translation (T_x = T_y = 0) and the height of the camera position from the ground (in mm) equates to T_z. If θ, φ, ψ be the orientation of the camera with respect to x, y and z axes respectively (as angles in radians), we may get r_ij ; i, j ∈ {1,2,3} as follows: The homography matrix H to be estimated is a 3 × 3 matrix, and encompasses the parts of both intrinsic and extrinsic camera matrices as follows: The above can be directly established from the fact, that when we are looking for a planar surface in the world-view to compute the homography, Z_w = 0, and thus, Hence, the homography H will map a world-view point in the arbitrary space. This space suffices well, in case we just need to compute the distances between any two given points. However, in reality, the coordinates in the pixel space will be calculated by considering the scale factor as specified in Eq. (2). Homography lets us relate two cameras viewing the same planar surface; Both the cameras and the surface that they view (generate images of) are located in the world-view coordinates. In other words, two 2D images are related by a homography H, if both view the same plane from a different angle. The homography relationship does not depend on the scene being viewed. Consider two such images viewing the same plane in the world-view. Let (x_1, y_1) be a point in the first image, and (xˆ_1, yˆ_1) be the corresponding point in the second image. Then, these points are related by the estimated homography H, as follows: Thus, any point in the first image may be mapped to a corresponding point in the second image through homography, and the operation may be seen as that of an image warp. Let us parametrize the 3 × 3 homography matrix H as follows: Thus, the estimation of H requires the estimation of 9 parameters. In other words, H has 9 degrees of freedom. If we choose two tuples of corresponding points, ☟[co-planar] in their respective planes, as follows: [co-planar] The homography relation is provable only under the co-planarity of the points, since everywhere, we are assuming that the z-coordinate of any point in any image is 1. In practice, for instance, one may thus choose four points on a floor, or a road, which indicate a nearly planar surface in the scene. Then, from Eq. (8, 9, 10), we may solve the following to estimate H: Where (xˆ_i, yˆ_i ) ∈ Tˆ_1 and (x_i, y_i) ∈ T_1 for i, j ∈ {1,2,3,4}. This will then translate to the following system of equations to be solved: We now have 8 equations, which can be used to estimate the 8 degrees of freedom of H (except h_33). For this, we would require that the 8 × 8 matrix above has a full rank (no redundant information), in the sense that none of the rows are linearly dependent. This implies that no three points in either of T_1 or Tˆ_1 should be collinear. We then need to tackle h_33. Note that in Eq. (13), if h_33 is pre-equated to 1, we would simply shift the entire set of h_ij hyperplanes to another reference frame, but their directions would not change. Practically, we would thus, simply see a different z_a value, while mapping a 2D image coordinate according to Eq. (8), which would subsequently get divided out in Eq. (9). Hence, we keep h_33 = 1 in H, and Eq. (13) may then be solved using least-squares estimation. In OpenCV, one can use the function findHomography, which does precisely the same, as delineated above. It accepts two tuples of four corresponding points, and computes the homography H with h_33 always and strictly 1. Any 2D image point will then be mapped to a z_a amplified version of the corresponding point in the other plane. In various applications, such as virtual advertising, absolute distance measurements for smart city planning, one needs to assume the presence of a hypothetical camera C, and compute a homography matrix, which can project any point in the observed scene to the plane of the image captured by C. Imagining C in the bird’s eye (top view) is a☟[popular choice] In such a case, one may choose T_1 with four co-planar points in the observed scene, while the corresponding tuple Tˆ_1 can simply have four points as corners of a hypothetical rectangle, with a Euclidean coordinate system, centered around (0, 0). Any point in the scene can then be mapped to its bird’s eye view, i.e. how may it look from the top. [popular choice] There has been a recent surge of research papers, which exploit the bird's eye view (BEV) for behavioural prediction and planning in autonmous driving. Note here that homography-based mapping is only a warped version of the observed image, and that no new information in the scene is being synthesized. For instance, if we have only observed the frontal view of a person in the scene, its birds-eye view, won’t really start telling as to how the person’s hair is from the top; but it will only warp the frontal-view visible portion of his head in a way that it would roughly look like a top-view. Note that while solving for H, there is no constraint that the projection points in the arbitrary space should be positive, i.e. x_a, y_a and z_a may be negative. Once scaled out by z_a, this would mean that a mapped point (xˆ_i, yˆ_i ) may be negative. This may look intuitively undesirable since the image coordinates are generally taken to be positive. However, this may be seen as only a reference axis shift, and after mapping the entire image, the amount of shift may be appropriately decided. 💡 Remark - The treatment presented here, may not be akin to 3D reconstruction procedures, which may involve estimation of multiple-view homographies', sometimes via a hypothesized view projection. Multi-view homographies, have been shown to possess specific algebraic structures, but 3D reconstruction from 2D scenes largely remains an unsolved problem.
[ { "code": null, "e": 588, "s": 172, "text": "This short piece describes equations for estimating a 3 × 3 homography matrix. We first discuss the computation from intrinsic and extrinsic camera parameters; and wherever necessary, connect the formulation to the real-world camera specifications. We next present the computation methodology using two tuples of corresponding points, that are co-planar in their respective planes and avoid collinear degenerations." }, { "code": null, "e": 651, "s": 588, "text": "Let's consider a point in the 3D world-view space as a 3-tuple" }, { "code": null, "e": 727, "s": 651, "text": "We can then map this 3D point to a point in an arbitrary space, as follows:" }, { "code": null, "e": 937, "s": 727, "text": "where C_int is the intrinsic and C_ext is the extrinsic camera matrix respectively. The point (x_a, y_a, z_a) in the arbitrary space, can be mapped to the 2D image space by involving a scale factor as follows:" }, { "code": null, "e": 1081, "s": 937, "text": "Thus, once we have a point in the arbitrary space, we can simply scale its coordinates to get the 2D coordinates in the (captured) image space." }, { "code": null, "e": 1419, "s": 1081, "text": "Let us now see the form of C_int. Consider a camera with a focal length f (in mm), with actual sensor size (x_S, y_S) (in mm), and the width and the height of the captured image (effective sensor size) as (w,h) (in pixels).The optical centre (o_x, o_y) of the camera is then (w/2, h/2). We are now in a state to specify C_int as follows:" }, { "code": null, "e": 1596, "s": 1419, "text": "One may thus observe that all entries in C_int are in the units of pixels. The following may be seen as the effective focal lengths in pixels in x and y directions respectively" }, { "code": null, "e": 1673, "s": 1596, "text": "C_ext consists of a rotation matrix R and a translation matrix T as follows:" }, { "code": null, "e": 1935, "s": 1673, "text": "The tuple (T_x, T_y, T_z) indicates the translation of the camera in the world-space coordinates. Typically, we can consider that the camera has no x and y translation (T_x = T_y = 0) and the height of the camera position from the ground (in mm) equates to T_z." }, { "code": null, "e": 2093, "s": 1935, "text": "If θ, φ, ψ be the orientation of the camera with respect to x, y and z axes respectively (as angles in radians), we may get r_ij ; i, j ∈ {1,2,3} as follows:" }, { "code": null, "e": 2238, "s": 2093, "text": "The homography matrix H to be estimated is a 3 × 3 matrix, and encompasses the parts of both intrinsic and extrinsic camera matrices as follows:" }, { "code": null, "e": 2401, "s": 2238, "text": "The above can be directly established from the fact, that when we are looking for a planar surface in the world-view to compute the homography, Z_w = 0, and thus," }, { "code": null, "e": 2711, "s": 2401, "text": "Hence, the homography H will map a world-view point in the arbitrary space. This space suffices well, in case we just need to compute the distances between any two given points. However, in reality, the coordinates in the pixel space will be calculated by considering the scale factor as specified in Eq. (2)." }, { "code": null, "e": 3078, "s": 2711, "text": "Homography lets us relate two cameras viewing the same planar surface; Both the cameras and the surface that they view (generate images of) are located in the world-view coordinates. In other words, two 2D images are related by a homography H, if both view the same plane from a different angle. The homography relationship does not depend on the scene being viewed." }, { "code": null, "e": 3330, "s": 3078, "text": "Consider two such images viewing the same plane in the world-view. Let (x_1, y_1) be a point in the first image, and (xˆ_1, yˆ_1) be the corresponding point in the second image. Then, these points are related by the estimated homography H, as follows:" }, { "code": null, "e": 3500, "s": 3330, "text": "Thus, any point in the first image may be mapped to a corresponding point in the second image through homography, and the operation may be seen as that of an image warp." }, { "code": null, "e": 3561, "s": 3500, "text": "Let us parametrize the 3 × 3 homography matrix H as follows:" }, { "code": null, "e": 3774, "s": 3561, "text": "Thus, the estimation of H requires the estimation of 9 parameters. In other words, H has 9 degrees of freedom. If we choose two tuples of corresponding points, ☟[co-planar] in their respective planes, as follows:" }, { "code": null, "e": 4088, "s": 3774, "text": "[co-planar] The homography relation is provable only under the co-planarity of the points, since everywhere, we are assuming that the z-coordinate of any point in any image is 1. In practice, for instance, one may thus choose four points on a floor, or a road, which indicate a nearly planar surface in the scene." }, { "code": null, "e": 4157, "s": 4088, "text": "Then, from Eq. (8, 9, 10), we may solve the following to estimate H:" }, { "code": null, "e": 4303, "s": 4157, "text": "Where (xˆ_i, yˆ_i ) ∈ Tˆ_1 and (x_i, y_i) ∈ T_1 for i, j ∈ {1,2,3,4}. This will then translate to the following system of equations to be solved:" }, { "code": null, "e": 4641, "s": 4303, "text": "We now have 8 equations, which can be used to estimate the 8 degrees of freedom of H (except h_33). For this, we would require that the 8 × 8 matrix above has a full rank (no redundant information), in the sense that none of the rows are linearly dependent. This implies that no three points in either of T_1 or Tˆ_1 should be collinear." }, { "code": null, "e": 5113, "s": 4641, "text": "We then need to tackle h_33. Note that in Eq. (13), if h_33 is pre-equated to 1, we would simply shift the entire set of h_ij hyperplanes to another reference frame, but their directions would not change. Practically, we would thus, simply see a different z_a value, while mapping a 2D image coordinate according to Eq. (8), which would subsequently get divided out in Eq. (9). Hence, we keep h_33 = 1 in H, and Eq. (13) may then be solved using least-squares estimation." }, { "code": null, "e": 5445, "s": 5113, "text": "In OpenCV, one can use the function findHomography, which does precisely the same, as delineated above. It accepts two tuples of four corresponding points, and computes the homography H with h_33 always and strictly 1. Any 2D image point will then be mapped to a z_a amplified version of the corresponding point in the other plane." }, { "code": null, "e": 5740, "s": 5445, "text": "In various applications, such as virtual advertising, absolute distance measurements for smart city planning, one needs to assume the presence of a hypothetical camera C, and compute a homography matrix, which can project any point in the observed scene to the plane of the image captured by C." }, { "code": null, "e": 6152, "s": 5740, "text": "Imagining C in the bird’s eye (top view) is a☟[popular choice] In such a case, one may choose T_1 with four co-planar points in the observed scene, while the corresponding tuple Tˆ_1 can simply have four points as corners of a hypothetical rectangle, with a Euclidean coordinate system, centered around (0, 0). Any point in the scene can then be mapped to its bird’s eye view, i.e. how may it look from the top." }, { "code": null, "e": 6321, "s": 6152, "text": "[popular choice] There has been a recent surge of research papers, which exploit the bird's eye view (BEV) for behavioural prediction and planning in autonmous driving." }, { "code": null, "e": 6766, "s": 6321, "text": "Note here that homography-based mapping is only a warped version of the observed image, and that no new information in the scene is being synthesized. For instance, if we have only observed the frontal view of a person in the scene, its birds-eye view, won’t really start telling as to how the person’s hair is from the top; but it will only warp the frontal-view visible portion of his head in a way that it would roughly look like a top-view." }, { "code": null, "e": 7020, "s": 6766, "text": "Note that while solving for H, there is no constraint that the projection points in the arbitrary space should be positive, i.e. x_a, y_a and z_a may be negative. Once scaled out by z_a, this would mean that a mapped point (xˆ_i, yˆ_i ) may be negative." }, { "code": null, "e": 7266, "s": 7020, "text": "This may look intuitively undesirable since the image coordinates are generally taken to be positive. However, this may be seen as only a reference axis shift, and after mapping the entire image, the amount of shift may be appropriately decided." } ]
TensorFlow or PyTorch? which is the best? | Towards Data Science
A student at UPC Barcelona Tech asked me which is the best framework for programming a neural network? TensorFlow or PyTorch?. My answer was: Don’t worry, you start with either one, it doesn’t matter which one you choose, the important thing is to start, let’s go! The steps to be taken to program a neural network in both environments are common in Machine Learning : Import required libraries, Load and Preprocess the Data, Define the Model, Define the Optimizer and the Loss function, Train the Model and finally Evaluate the Model. And these steps can be implemented very similarly in either framework. For this purpose, in this publication, we will build a neural network model that classifies handwritten digits in both the API PyTorch as with the API Keras of TensorFlow. The entire code can be tested on GitHub and run it as a colab google notebook. In both frameworks we need to import some Python libraries first and define some hyperparameters we will need for training: import numpy as np import matplotlib.pyplot as plt epochs = 10 batch_size=64 In the case of TensorFlow you only need this library: import tensorflow as tf While in the case of PyTorch these two: import torch import torchvision Loading and preparing data with TensorFlow can be done with these two lines of code: (x_trainTF_, y_trainTF_), _ = tf.keras.datasets.mnist.load_data() x_trainTF = x_trainTF_.reshape(60000, 784).astype('float32')/255 y_trainTF = tf.keras.utils.to_categorical(y_trainTF_, num_classes=10) While in PyTorch with these other two: xy_trainPT = torchvision.datasets.MNIST(root='./data', train=True, download=True,transform=torchvision.transforms.Compose([torchvision.transforms.ToTensor()])) xy_trainPT_loader = torch.utils.data.DataLoader(xy_trainPT, batch_size=batch_size) We can verify that both codes have loaded the same data with the library matplotlib.pyplot : print("TensorFlow:")fig = plt.figure(figsize=(25, 4))for idx in np.arange(20): ax = fig.add_subplot(2, 20/2, idx+1, xticks=[], yticks=[]) ax.imshow(x_trainTF_[idx], cmap=plt.cm.binary) ax.set_title(str(y_trainTF_[idx])) print("PyTorch:")fig = plt.figure(figsize=(25, 4)) for idx in np.arange(20): ax = fig.add_subplot(2, 20/2, idx+1, xticks=[], yticks=[]) ax.imshow(torch.squeeze(image, dim = 0).numpy(), cmap=plt.cm.binary) image, label = xy_trainPT [idx] ax.set_title(str(label)) In order to define the model, in both cases, it is done with a rather similar syntax. In the case of TensorFlow it can be done with the following code: modelTF = tf.keras.Sequential([ tf.keras.layers.Dense(10,activation='sigmoid',input_shape=(784,)), tf.keras.layers.Dense(10,activation='softmax') ]) And in PyTorch with this one: modelPT= torch.nn.Sequential( torch.nn.Linear(784,10), torch.nn.Sigmoid(), torch.nn.Linear(10,10), torch.nn.LogSoftmax(dim=1) ) Again, the way to specify the optimizer and the loss function is quite equivalent. With TensorFlow we can do it like this: modelTF.compile( loss="categorical_crossentropy", optimizer=tf.optimizers.SGD(lr=0.01), metrics = ['accuracy'] ) Whereas with PyTorch like this: criterion = torch.nn.NLLLoss() optimizer = torch.optim.SGD(modelPT.parameters(), lr=0.01) When it comes to training, we find the biggest differences. In the case of TensorFlow we could do it with only this line of code: _ = modelTF.fit(x_trainTF, y_trainTF, epochs=epochs, batch_size=batch_size, verbose = 0) While in Pytorch we need something longer like this: for e in range(epochs): for images, labels in xy_trainPT_loader: images = images.view(images.shape[0], -1) loss = criterion(modelPT(images), labels) loss.backward() optimizer.step() optimizer.zero_grad() In PyTorch, there is no a “prefab” data model tuning function as fit() in Keras or Scikit-learn, so the training loop must be specified by the programmer. Well, there is a certain compromise here, between simplicity and practicality, to be able to do more tailor-made things. The same situation happens when we need to evaluate the model, while in TensorFlow you just have to call the method evaluate() with the test data: _, (x_testTF, y_testTF)= tf.keras.datasets.mnist.load_data()x_testTF = x_testTF.reshape(10000, 784).astype('float32')/255y_testTF = tf.keras.utils.to_categorical(y_testTF, num_classes=10)_ , test_accTF = modelTF.evaluate(x_testTF, y_testTF)print('\nAccuracy del model amb TensorFlow =', test_accTF)TensorFlow model Accuracy = 0.8658999800682068 In PyTorch it is required again that the programmer specifies the evaluation loop: xy_testPT = torchvision.datasets.MNIST(root='./data', train=False, download=True, transform=torchvision.transforms.Compose([torchvision.transforms.ToTensor()]))xy_test_loaderPT = torch.utils.data.DataLoader(xy_testPT)correct_count, all_count = 0, 0for images,labels in xy_test_loaderPT: for i in range(len(labels)): img = images[i].view(1, 784) logps = modelPT(img) ps = torch.exp(logps) probab = list(ps.detach().numpy()[0]) pred_label = probab.index(max(probab)) true_label = labels.numpy()[i] if(true_label == pred_label): correct_count += 1 all_count += 1print("\nAccuracy del model amb PyTorch =", (correct_count/all_count))TensorFlow model Accuracy = 0.8657 Well, as shown in this simple example, the way it can be created a neural network in TensorFlow and PyTorch doesn’t really differ, except in some details regarding the way that the programmer has to implement the training and evaluation loop, and some hyperparameters like epochs or batch_size are specified in different steps. In fact, these two frameworks have been constantly converging over the last two years, learning from each other and adopting their best features. For example, in the new version of TensorFlow 2.2 announced a couple of weeks ago, the training step can be done equal to PyTorch, now the programmer can specify a detailed content of the body of the loop by implementing the traint_step(). So do not worry about choosing the “wrong” framework, they will converge! The most important thing is to learn the Deep Learning concepts behind, and all the knowledge you acquire in one of the frameworks will be useful to you in the other. However, it is clear that it is different if what you want is to put into production a solution or do research in neural networks. In this case, the decision of which one to choose is important. TensorFlow is a very powerful and mature Python library with strong visualization features and a variety of options for high performance model development. It has rollout options ready for production and automatic support for web and mobile platforms. PyTorch, on the other hand, is still a young framework but with a very active community especially in the world of research. The portal The Gradient shown in the attached figure the rise and adoption of PyTorch the research community based on the number of research papers published in major conference theme (CVPR, ICRL, ICML, NIPS, ACL, ICCV, etc.). As can be seen in the figure in 2018, the use of the PyTorch framework was minority, compared to 2019 which is overwhelming its use by researchers. Therefore, if you want to create products related to artificial intelligence, TensorFlow is a good choice. I recommend PyTorch if you want to do research. Therefore, if you want to create products related to artificial intelligence, TensorFlow is a good choice. I recommend PyTorch if you want to do research. If you’re not sure, start with TensorFlow’s Keras API. PyTorch’s API has more flexibility and control, but it’s clear that TensorFlow’s Keras API can be easier to get started. And if you are reading this post I can assume that you are starting in the topic of Deep Learning. In addition, you have extra documentation about Keras in other publications that I have prepared for the last two years. (One secret: I plan to have PyTorch equivalent documentation ready in the summer, too). By the way, Keras has several novelties planned for this 2020 that are in the line of “making it easier”. Here’s a list of some of the new features that have been recently added or announced that will be coming soon: Layers and preprocessing APIs So far we have done preprocessing with auxiliary tools written in NumPy and PIL (Python Imaging Library). And this kind of external preprocessing makes models less portable, because every time someone reuses an already trained model, they have to replay the preprocessor pipeline. Therefore, preprocessing can now be part of the model, through “preprocessing layers”. This includes aspects such as text standardization, tokenization, vectorization, image normalization, data augmentation, etc. That is, this will allow models to accept raw text or raw images as input. I personally think this will be very interesting. Keras Tuner It is a framework that allows you to find the best hyperparameters of a model in Keras. As you spend some time working in Deep Learning, you will see that this solves one of the costly problems of model building, such as refining the hyperparameters so that the model is performing best. It is always a very difficult task. AutoKeras This project seeks to find a good ML model for data in a few lines of code, automatically searching the best possible model according to a space of possible models, and using Keras Tuner finding for hyperparameters tuning. For advanced users, AutoKeras also allows a higher level of control over the configuration of the search space and process. Cloud Keras The vision is to make it easier for the programmer to move a code (that works locally on our laptop or Google Colab) to the Cloud, enabling it to execute this code in an optimal and distributed manner in the Cloud, Without having to worry about the cluster or Docker parameters. Integration with TensorFlow Work is underway for more integration with TFX (TensorFlow Extended, a platform for managing ML production applications) and better support for exporting models to TF Lite (an ML execution engine for mobile and embedded devices). Undoubtedly improving the support for the production of the models is essential for the loyalty of programmers in Keras. In a simile, Which do you think is the best language to start programming, C ++ or Java? Well ... it depends on what we want to do with it, and above all depends on what tools are available to us to learn. We may not be able to agree, because we have a preconceived opinion and it would be difficult for us to change our answer to this question (the same happens with “fans” of PyTorch and TensorFlow😉 ). But surely we agree that the important thing is to know how to program. And in fact, whatever we learn from programming in one language, then it will serve us when we use the other one, right? The same thing happens here with the frameworks, the important thing is to know about Deep Learning rather about the syntax details of a framework, and then we will use that knowledge with the framework that is in fashion or to which we have more access at that time. The code of this post can be downloaded from GitHub towardsdatascience.com Originally published in Catalan at https://torres.ai on April 19, 2020.
[ { "code": null, "e": 437, "s": 172, "text": "A student at UPC Barcelona Tech asked me which is the best framework for programming a neural network? TensorFlow or PyTorch?. My answer was: Don’t worry, you start with either one, it doesn’t matter which one you choose, the important thing is to start, let’s go!" }, { "code": null, "e": 541, "s": 437, "text": "The steps to be taken to program a neural network in both environments are common in Machine Learning :" }, { "code": null, "e": 568, "s": 541, "text": "Import required libraries," }, { "code": null, "e": 598, "s": 568, "text": "Load and Preprocess the Data," }, { "code": null, "e": 616, "s": 598, "text": "Define the Model," }, { "code": null, "e": 660, "s": 616, "text": "Define the Optimizer and the Loss function," }, { "code": null, "e": 688, "s": 660, "text": "Train the Model and finally" }, { "code": null, "e": 708, "s": 688, "text": "Evaluate the Model." }, { "code": null, "e": 1030, "s": 708, "text": "And these steps can be implemented very similarly in either framework. For this purpose, in this publication, we will build a neural network model that classifies handwritten digits in both the API PyTorch as with the API Keras of TensorFlow. The entire code can be tested on GitHub and run it as a colab google notebook." }, { "code": null, "e": 1154, "s": 1030, "text": "In both frameworks we need to import some Python libraries first and define some hyperparameters we will need for training:" }, { "code": null, "e": 1231, "s": 1154, "text": "import numpy as np import matplotlib.pyplot as plt epochs = 10 batch_size=64" }, { "code": null, "e": 1285, "s": 1231, "text": "In the case of TensorFlow you only need this library:" }, { "code": null, "e": 1309, "s": 1285, "text": "import tensorflow as tf" }, { "code": null, "e": 1349, "s": 1309, "text": "While in the case of PyTorch these two:" }, { "code": null, "e": 1381, "s": 1349, "text": "import torch import torchvision" }, { "code": null, "e": 1466, "s": 1381, "text": "Loading and preparing data with TensorFlow can be done with these two lines of code:" }, { "code": null, "e": 1679, "s": 1466, "text": "(x_trainTF_, y_trainTF_), _ = tf.keras.datasets.mnist.load_data() x_trainTF = x_trainTF_.reshape(60000, 784).astype('float32')/255 y_trainTF = tf.keras.utils.to_categorical(y_trainTF_, num_classes=10)" }, { "code": null, "e": 1718, "s": 1679, "text": "While in PyTorch with these other two:" }, { "code": null, "e": 1961, "s": 1718, "text": "xy_trainPT = torchvision.datasets.MNIST(root='./data', train=True, download=True,transform=torchvision.transforms.Compose([torchvision.transforms.ToTensor()])) xy_trainPT_loader = torch.utils.data.DataLoader(xy_trainPT, batch_size=batch_size)" }, { "code": null, "e": 2054, "s": 1961, "text": "We can verify that both codes have loaded the same data with the library matplotlib.pyplot :" }, { "code": null, "e": 2280, "s": 2054, "text": "print(\"TensorFlow:\")fig = plt.figure(figsize=(25, 4))for idx in np.arange(20): ax = fig.add_subplot(2, 20/2, idx+1, xticks=[], yticks=[]) ax.imshow(x_trainTF_[idx], cmap=plt.cm.binary) ax.set_title(str(y_trainTF_[idx]))" }, { "code": null, "e": 2563, "s": 2280, "text": "print(\"PyTorch:\")fig = plt.figure(figsize=(25, 4)) for idx in np.arange(20): ax = fig.add_subplot(2, 20/2, idx+1, xticks=[], yticks=[]) ax.imshow(torch.squeeze(image, dim = 0).numpy(), cmap=plt.cm.binary) image, label = xy_trainPT [idx] ax.set_title(str(label))" }, { "code": null, "e": 2715, "s": 2563, "text": "In order to define the model, in both cases, it is done with a rather similar syntax. In the case of TensorFlow it can be done with the following code:" }, { "code": null, "e": 2864, "s": 2715, "text": "modelTF = tf.keras.Sequential([ tf.keras.layers.Dense(10,activation='sigmoid',input_shape=(784,)), tf.keras.layers.Dense(10,activation='softmax') ])" }, { "code": null, "e": 2894, "s": 2864, "text": "And in PyTorch with this one:" }, { "code": null, "e": 3068, "s": 2894, "text": "modelPT= torch.nn.Sequential( torch.nn.Linear(784,10), torch.nn.Sigmoid(), torch.nn.Linear(10,10), torch.nn.LogSoftmax(dim=1) )" }, { "code": null, "e": 3191, "s": 3068, "text": "Again, the way to specify the optimizer and the loss function is quite equivalent. With TensorFlow we can do it like this:" }, { "code": null, "e": 3368, "s": 3191, "text": "modelTF.compile( loss=\"categorical_crossentropy\", optimizer=tf.optimizers.SGD(lr=0.01), metrics = ['accuracy'] )" }, { "code": null, "e": 3400, "s": 3368, "text": "Whereas with PyTorch like this:" }, { "code": null, "e": 3490, "s": 3400, "text": "criterion = torch.nn.NLLLoss() optimizer = torch.optim.SGD(modelPT.parameters(), lr=0.01)" }, { "code": null, "e": 3620, "s": 3490, "text": "When it comes to training, we find the biggest differences. In the case of TensorFlow we could do it with only this line of code:" }, { "code": null, "e": 3725, "s": 3620, "text": "_ = modelTF.fit(x_trainTF, y_trainTF, epochs=epochs, batch_size=batch_size, verbose = 0)" }, { "code": null, "e": 3778, "s": 3725, "text": "While in Pytorch we need something longer like this:" }, { "code": null, "e": 4020, "s": 3778, "text": "for e in range(epochs): for images, labels in xy_trainPT_loader: images = images.view(images.shape[0], -1) loss = criterion(modelPT(images), labels) loss.backward() optimizer.step() optimizer.zero_grad()" }, { "code": null, "e": 4296, "s": 4020, "text": "In PyTorch, there is no a “prefab” data model tuning function as fit() in Keras or Scikit-learn, so the training loop must be specified by the programmer. Well, there is a certain compromise here, between simplicity and practicality, to be able to do more tailor-made things." }, { "code": null, "e": 4443, "s": 4296, "text": "The same situation happens when we need to evaluate the model, while in TensorFlow you just have to call the method evaluate() with the test data:" }, { "code": null, "e": 4788, "s": 4443, "text": "_, (x_testTF, y_testTF)= tf.keras.datasets.mnist.load_data()x_testTF = x_testTF.reshape(10000, 784).astype('float32')/255y_testTF = tf.keras.utils.to_categorical(y_testTF, num_classes=10)_ , test_accTF = modelTF.evaluate(x_testTF, y_testTF)print('\\nAccuracy del model amb TensorFlow =', test_accTF)TensorFlow model Accuracy = 0.8658999800682068" }, { "code": null, "e": 4871, "s": 4788, "text": "In PyTorch it is required again that the programmer specifies the evaluation loop:" }, { "code": null, "e": 5577, "s": 4871, "text": "xy_testPT = torchvision.datasets.MNIST(root='./data', train=False, download=True, transform=torchvision.transforms.Compose([torchvision.transforms.ToTensor()]))xy_test_loaderPT = torch.utils.data.DataLoader(xy_testPT)correct_count, all_count = 0, 0for images,labels in xy_test_loaderPT: for i in range(len(labels)): img = images[i].view(1, 784) logps = modelPT(img) ps = torch.exp(logps) probab = list(ps.detach().numpy()[0]) pred_label = probab.index(max(probab)) true_label = labels.numpy()[i] if(true_label == pred_label): correct_count += 1 all_count += 1print(\"\\nAccuracy del model amb PyTorch =\", (correct_count/all_count))TensorFlow model Accuracy = 0.8657" }, { "code": null, "e": 5905, "s": 5577, "text": "Well, as shown in this simple example, the way it can be created a neural network in TensorFlow and PyTorch doesn’t really differ, except in some details regarding the way that the programmer has to implement the training and evaluation loop, and some hyperparameters like epochs or batch_size are specified in different steps." }, { "code": null, "e": 6532, "s": 5905, "text": "In fact, these two frameworks have been constantly converging over the last two years, learning from each other and adopting their best features. For example, in the new version of TensorFlow 2.2 announced a couple of weeks ago, the training step can be done equal to PyTorch, now the programmer can specify a detailed content of the body of the loop by implementing the traint_step(). So do not worry about choosing the “wrong” framework, they will converge! The most important thing is to learn the Deep Learning concepts behind, and all the knowledge you acquire in one of the frameworks will be useful to you in the other." }, { "code": null, "e": 6727, "s": 6532, "text": "However, it is clear that it is different if what you want is to put into production a solution or do research in neural networks. In this case, the decision of which one to choose is important." }, { "code": null, "e": 6979, "s": 6727, "text": "TensorFlow is a very powerful and mature Python library with strong visualization features and a variety of options for high performance model development. It has rollout options ready for production and automatic support for web and mobile platforms." }, { "code": null, "e": 7331, "s": 6979, "text": "PyTorch, on the other hand, is still a young framework but with a very active community especially in the world of research. The portal The Gradient shown in the attached figure the rise and adoption of PyTorch the research community based on the number of research papers published in major conference theme (CVPR, ICRL, ICML, NIPS, ACL, ICCV, etc.)." }, { "code": null, "e": 7634, "s": 7331, "text": "As can be seen in the figure in 2018, the use of the PyTorch framework was minority, compared to 2019 which is overwhelming its use by researchers. Therefore, if you want to create products related to artificial intelligence, TensorFlow is a good choice. I recommend PyTorch if you want to do research." }, { "code": null, "e": 7789, "s": 7634, "text": "Therefore, if you want to create products related to artificial intelligence, TensorFlow is a good choice. I recommend PyTorch if you want to do research." }, { "code": null, "e": 8064, "s": 7789, "text": "If you’re not sure, start with TensorFlow’s Keras API. PyTorch’s API has more flexibility and control, but it’s clear that TensorFlow’s Keras API can be easier to get started. And if you are reading this post I can assume that you are starting in the topic of Deep Learning." }, { "code": null, "e": 8273, "s": 8064, "text": "In addition, you have extra documentation about Keras in other publications that I have prepared for the last two years. (One secret: I plan to have PyTorch equivalent documentation ready in the summer, too)." }, { "code": null, "e": 8490, "s": 8273, "text": "By the way, Keras has several novelties planned for this 2020 that are in the line of “making it easier”. Here’s a list of some of the new features that have been recently added or announced that will be coming soon:" }, { "code": null, "e": 8520, "s": 8490, "text": "Layers and preprocessing APIs" }, { "code": null, "e": 9139, "s": 8520, "text": "So far we have done preprocessing with auxiliary tools written in NumPy and PIL (Python Imaging Library). And this kind of external preprocessing makes models less portable, because every time someone reuses an already trained model, they have to replay the preprocessor pipeline. Therefore, preprocessing can now be part of the model, through “preprocessing layers”. This includes aspects such as text standardization, tokenization, vectorization, image normalization, data augmentation, etc. That is, this will allow models to accept raw text or raw images as input. I personally think this will be very interesting." }, { "code": null, "e": 9151, "s": 9139, "text": "Keras Tuner" }, { "code": null, "e": 9475, "s": 9151, "text": "It is a framework that allows you to find the best hyperparameters of a model in Keras. As you spend some time working in Deep Learning, you will see that this solves one of the costly problems of model building, such as refining the hyperparameters so that the model is performing best. It is always a very difficult task." }, { "code": null, "e": 9485, "s": 9475, "text": "AutoKeras" }, { "code": null, "e": 9832, "s": 9485, "text": "This project seeks to find a good ML model for data in a few lines of code, automatically searching the best possible model according to a space of possible models, and using Keras Tuner finding for hyperparameters tuning. For advanced users, AutoKeras also allows a higher level of control over the configuration of the search space and process." }, { "code": null, "e": 9844, "s": 9832, "text": "Cloud Keras" }, { "code": null, "e": 10123, "s": 9844, "text": "The vision is to make it easier for the programmer to move a code (that works locally on our laptop or Google Colab) to the Cloud, enabling it to execute this code in an optimal and distributed manner in the Cloud, Without having to worry about the cluster or Docker parameters." }, { "code": null, "e": 10151, "s": 10123, "text": "Integration with TensorFlow" }, { "code": null, "e": 10502, "s": 10151, "text": "Work is underway for more integration with TFX (TensorFlow Extended, a platform for managing ML production applications) and better support for exporting models to TF Lite (an ML execution engine for mobile and embedded devices). Undoubtedly improving the support for the production of the models is essential for the loyalty of programmers in Keras." }, { "code": null, "e": 11368, "s": 10502, "text": "In a simile, Which do you think is the best language to start programming, C ++ or Java? Well ... it depends on what we want to do with it, and above all depends on what tools are available to us to learn. We may not be able to agree, because we have a preconceived opinion and it would be difficult for us to change our answer to this question (the same happens with “fans” of PyTorch and TensorFlow😉 ). But surely we agree that the important thing is to know how to program. And in fact, whatever we learn from programming in one language, then it will serve us when we use the other one, right? The same thing happens here with the frameworks, the important thing is to know about Deep Learning rather about the syntax details of a framework, and then we will use that knowledge with the framework that is in fashion or to which we have more access at that time." }, { "code": null, "e": 11420, "s": 11368, "text": "The code of this post can be downloaded from GitHub" }, { "code": null, "e": 11443, "s": 11420, "text": "towardsdatascience.com" } ]
What does it mean by select 1 from MySQL table?
The statement ‘select 1’ from any table name means that it returns only 1. For example, If any table has 4 records then it will return 1 four times. Let us see an example. Firstly, we will create a table using the CREATE command. mysql> create table StudentTable -> ( -> id int, -> name varchar(100) -> ); Query OK, 0 rows affected (0.51 sec) mysql> insert into StudentTable values(1,'John'),(2,'Carol'),(3,'Smith'),(4,'Bob'); Query OK, 4 rows affected (0.21 sec) Records: 4 Duplicates: 0 Warnings: 0 To display all the records. mysql> select *from StudentTable; Here is the output. +------+-------+ | id | name | +------+-------+ | 1 | John | | 2 | Carol | | 3 | Smith | | 4 | Bob | +------+-------+ 4 rows in set (0.00 sec) The following is the query to implement "select 1". mysql> select 1 from StudentTable; Here is the output. +---+ | 1 | +---+ | 1 | | 1 | | 1 | | 1 | +---+ 4 rows in set (0.00 sec) The above returns 1 four times for 4 records, and if we had 5 records then the above query would have returned 1 five times. Note: It returns 1 N times, if the table has N records.
[ { "code": null, "e": 1211, "s": 1062, "text": "The statement ‘select 1’ from any table name means that it returns only 1. For example, If any table has 4 records then it will return 1 four times." }, { "code": null, "e": 1292, "s": 1211, "text": "Let us see an example. Firstly, we will create a table using the CREATE command." }, { "code": null, "e": 1417, "s": 1292, "text": "mysql> create table StudentTable\n -> (\n -> id int,\n -> name varchar(100)\n -> );\nQuery OK, 0 rows affected (0.51 sec)" }, { "code": null, "e": 1577, "s": 1417, "text": "mysql> insert into StudentTable values(1,'John'),(2,'Carol'),(3,'Smith'),(4,'Bob');\nQuery OK, 4 rows affected (0.21 sec)\nRecords: 4 Duplicates: 0 Warnings: 0" }, { "code": null, "e": 1605, "s": 1577, "text": "To display all the records." }, { "code": null, "e": 1639, "s": 1605, "text": "mysql> select *from StudentTable;" }, { "code": null, "e": 1659, "s": 1639, "text": "Here is the output." }, { "code": null, "e": 1821, "s": 1659, "text": "+------+-------+\n| id | name |\n+------+-------+\n| 1 | John |\n| 2 | Carol |\n| 3 | Smith |\n| 4 | Bob |\n+------+-------+\n4 rows in set (0.00 sec)\n" }, { "code": null, "e": 1873, "s": 1821, "text": "The following is the query to implement \"select 1\"." }, { "code": null, "e": 1908, "s": 1873, "text": "mysql> select 1 from StudentTable;" }, { "code": null, "e": 1928, "s": 1908, "text": "Here is the output." }, { "code": null, "e": 2002, "s": 1928, "text": "+---+\n| 1 |\n+---+\n| 1 |\n| 1 |\n| 1 |\n| 1 |\n+---+\n4 rows in set (0.00 sec)\n" }, { "code": null, "e": 2127, "s": 2002, "text": "The above returns 1 four times for 4 records, and if we had 5 records then the above query would have returned 1 five times." }, { "code": null, "e": 2184, "s": 2127, "text": "Note: It returns 1 N times, if the table has N records.\n" } ]
How to create a pandas DataFrame using a list of lists?
The pandas DataFrame can be created by using the list of lists, to do this we need to pass a python list of lists as a parameter to the pandas.DataFrame() function. Pandas DataFrame will represent the data in a tabular format, like rows and columns. If we create a pandas DataFrame using a list of lists, the inner list will be transformed as a row in the resulting list. # importing the pandas package import pandas as pd # creating a nested list nested_list = [[1,2,3],[10,20,30],[100,200,300]] # creating DataFrame df = pd.DataFrame(nested_list, columns= ['A','B','C']) print(df)# displaying resultant DataFrame In this above Example, nested_list is having 3 sub-lists and each list is having 3 integer elements, by using the DataFrame constructor we create a DataFrame or a table shape of 3X3. The columns parameter is used to customize the default column labels from [0,1,2] to [A,B,C]. The resultant DataFrame can be seen below. A B C 0 1 2 3 1 10 20 30 2 100 200 300 The output DataFrame has 3 rows and 3 columns, with column label representation as A, B, C. # importing the pandas package import pandas as pd # creating a nested list nested_list = [['A','B','C'],['D','E'],['F','G','H']] # creating DataFrame df = pd.DataFrame(nested_list) # displaying resultant DataFrame print(df) In this following example, we have created a pandas DataFrame object using the list of lists with different lengths. The second inner list has only 2 elements and the remaining inner lists have 3 elements, due to this we will get None value in the resultant DataFrame. 0 1 2 0 A B C 1 D E None 2 F G H We can see that there is a none value in the second-row third elements, which is due to the uneven length of inner lists.
[ { "code": null, "e": 1227, "s": 1062, "text": "The pandas DataFrame can be created by using the list of lists, to do this we need to pass a python list of lists as a parameter to the pandas.DataFrame() function." }, { "code": null, "e": 1434, "s": 1227, "text": "Pandas DataFrame will represent the data in a tabular format, like rows and columns. If we create a pandas DataFrame using a list of lists, the inner list will be transformed as a row in the resulting list." }, { "code": null, "e": 1679, "s": 1434, "text": "# importing the pandas package\nimport pandas as pd\n# creating a nested list\nnested_list = [[1,2,3],[10,20,30],[100,200,300]]\n\n# creating DataFrame\ndf = pd.DataFrame(nested_list, columns= ['A','B','C'])\n\nprint(df)# displaying resultant DataFrame" }, { "code": null, "e": 1999, "s": 1679, "text": "In this above Example, nested_list is having 3 sub-lists and each list is having 3 integer elements, by using the DataFrame constructor we create a DataFrame or a table shape of 3X3. The columns parameter is used to customize the default column labels from [0,1,2] to [A,B,C]. The resultant DataFrame can be seen below." }, { "code": null, "e": 2066, "s": 1999, "text": " A B C\n0 1 2 3\n1 10 20 30\n2 100 200 300" }, { "code": null, "e": 2158, "s": 2066, "text": "The output DataFrame has 3 rows and 3 columns, with column label representation as A, B, C." }, { "code": null, "e": 2385, "s": 2158, "text": "# importing the pandas package\nimport pandas as pd\n# creating a nested list\nnested_list = [['A','B','C'],['D','E'],['F','G','H']]\n\n# creating DataFrame\ndf = pd.DataFrame(nested_list)\n\n# displaying resultant DataFrame\nprint(df)" }, { "code": null, "e": 2654, "s": 2385, "text": "In this following example, we have created a pandas DataFrame object using the list of lists with different lengths. The second inner list has only 2 elements and the remaining inner lists have 3 elements, due to this we will get None value in the resultant DataFrame." }, { "code": null, "e": 2718, "s": 2654, "text": " 0 1 2\n0 A B C\n1 D E None\n2 F G H" }, { "code": null, "e": 2840, "s": 2718, "text": "We can see that there is a none value in the second-row third elements, which is due to the uneven length of inner lists." } ]
Hibernate Projection Example | Projection in Hibernate Example
PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC EXCEPTIONS COLLECTIONS SWING JDBC JAVA 8 SPRING SPRING BOOT HIBERNATE PYTHON PHP JQUERY PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws In this tutorial, we are going to see Hibernate Projection with a simple example. As we already discussed in the previous tutorial Hibernate Criteria, If we want to read a partial entity (selected columns) from the database, hibernate has provided us with a Projection interface. Projection is an interface in Hibernate; it is coming from org.hibernate.criterion package. Projection can be applied to the Criteria query. Projection is an Object-Oriented Representation of a query result set. Hibernate Projection is used to read a partial entity from the database. If we want to read more than one property from the database, then we have to add Projection objects to ProjectionList, and then we need to set ProjectionList object to Criteria. The following code is to read the employee name column from the employee table. It will get all the employeNames from the employee table. Criteria criteria = session.createCriteria(Employee.class); Projection projection = Projections.property("employeeName"); criteria.setProjection(projection); List list = criteria.list(); select ename from employee; If we want to read more than 1 column (employeeName, salary) with projections, we should have to use ProjectinList class. We should prepare all projections and bind all projections into a single ProjectionList like below. Criteria criteria = session.createCriteria(Employee.class); Projection projection = Projections.property("salary"); Projection projection2 = Projections.property("departmentId"); Projection projection3 = Projections.property("employeeName"); ProjectionList pList = Projections.projectionList(); pList.add(projection); pList.add(projection2); pList.add(projection3); criteria.setProjection(pList); List list = criteria.list(); On the above example, we will get the salary, departmentId and employeeName from the employee table. select sal,deptid,ename from emp; Since those are multiple projections, first we need to add all projections to ProjectionList object and then add ProjectionList object to criteria object. Create Employee Pojo Class: Employee.class package com.otp.hibernate.pojo; public class Employee { private int employeeId; private String employeeName; private int departmentId; private int salary; public int getEmployeeId() { return employeeId; } public void setEmployeeId(int employeeId) { this.employeeId = employeeId; } public String getEmployeeName() { return employeeName; } public void setEmployeeName(String employeeName) { this.employeeName = employeeName; } public int getDepartmentId() { return departmentId; } public void setDepartmentId(int departmentId) { this.departmentId = departmentId; } public int getSalary() { return salary; } public void setSalary(int salary) { this.salary = salary; } @Override public String toString() { return "Employee [employeeId=" + employeeId + ", employeeName=" + employeeName + ", departmentId=" + departmentId + ", salary=" + salary + "]"; } } Hibernate mapping file : <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="com.otp.hibernate.pojo.Employee" table="employee" schema="onlinetutorialspoint"> <id name="employeeId" column="id"> <generator class="increment" /> </id> <property name="employeeName" column="ename" /> <property name="departmentId" column="deptNo" /> <property name="salary" column="salary" /> </class> </hibernate-mapping> Run the Application : import java.util.Iterator; import java.util.List; import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; import org.hibernate.criterion.Criterion; import org.hibernate.criterion.Projection; import org.hibernate.criterion.ProjectionList; import org.hibernate.criterion.Projections; import org.hibernate.criterion.Restrictions; import com.otp.hibernate.pojo.Employee; public class Main { public static void main(String[] args) { Configuration configuration = new Configuration() .configure("hibernate.cfg.xml"); StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder() .applySettings(configuration.getProperties()); SessionFactory factory = configuration.buildSessionFactory(builder .build()); Session session = factory.openSession(); System.out.println("Reading Partial Entity with One Projection object "); Criteria criteria = session.createCriteria(Employee.class); Projection projection = Projections.property("salary"); criteria.setProjection(projection); List list = criteria.list(); Iterator it = list.iterator(); while (it.hasNext()) { Integer sal = (Integer) it.next(); System.out.println("Employee Salary : " + sal); } System.out.println("Reading Partial Entity with multiple Projection objects "); Criteria crit2 = session.createCriteria(Employee.class); Projection projection1 = Projections.property("salary"); Projection projection2 = Projections.property("departmentId"); Projection projection3 = Projections.property("employeeName"); ProjectionList pList = Projections.projectionList(); pList.add(projection1); pList.add(projection2); pList.add(projection3); crit2.setProjection(pList); List list2 = crit2.list(); Iterator it2 = list2.iterator(); while (it2.hasNext()) { Object[] obj = (Object[]) it2.next(); System.out.println("Salary : " + obj[0]+" DeptId : "+obj[1]+" empName : "+obj[2]); } } } Output : Reading Partial Entity with One Projection object Employee Salary : 6000 Employee Salary : 8000 Employee Salary : 4000 Employee Salary : 5000 Employee Salary : 4000 Employee Salary : 3000 Reading Partial Entity with multiple Projection objects Salary : 6000 DeptId : 101 empName : Chandra Salary : 8000 DeptId : 101 empName : Shekhar Salary : 4000 DeptId : 105 empName : Rahul Salary : 5000 DeptId : 103 empName : Mahesh Salary : 4000 DeptId : 101 empName : Vinay Salary : 3000 DeptId : 105 empName : Vijay The complete example is available for download. Happy Learning 🙂 Hibernate-Projection-Example File size: 13 KB Downloads: 1697 Hibernate Criteria API with Example Hibernate Restrictions with Example Hibernate Native SQL Query Example Hibernate Named Query with Example Hibernate Filter Example Xml Configuration hibernate update query example Hibernate Right Join Example What is Association in Java What is Hibernate Hibernate 4 Example with Annotations Mysql Top 10 Advantages of Hibernate Different types of Object States in Hibernate Difference between update vs merge in Hibernate example Singleton Hibernate SessionFactory Example Hibernate One To Many Example (XML Mapping) Hibernate Criteria API with Example Hibernate Restrictions with Example Hibernate Native SQL Query Example Hibernate Named Query with Example Hibernate Filter Example Xml Configuration hibernate update query example Hibernate Right Join Example What is Association in Java What is Hibernate Hibernate 4 Example with Annotations Mysql Top 10 Advantages of Hibernate Different types of Object States in Hibernate Difference between update vs merge in Hibernate example Singleton Hibernate SessionFactory Example Hibernate One To Many Example (XML Mapping) avulavenkatareddy February 5, 2017 at 12:51 pm - Reply Hiii..... your website giving the information is awesome but please give the more concepts and depth information and other extra concepts. Thank you........................ Ram November 7, 2018 at 3:16 am - Reply Hi .. thank you for for providing the concept , in this I have one question .. Can we apply pagination on Projection queries .. avulavenkatareddy February 5, 2017 at 12:51 pm - Reply Hiii..... your website giving the information is awesome but please give the more concepts and depth information and other extra concepts. Thank you........................ Hiii..... your website giving the information is awesome but please give the more concepts and depth information and other extra concepts. Thank you........................ Ram November 7, 2018 at 3:16 am - Reply Hi .. thank you for for providing the concept , in this I have one question .. Can we apply pagination on Projection queries .. Hi .. thank you for for providing the concept , in this I have one question .. Can we apply pagination on Projection queries .. Δ Hibernate – Introduction Hibernate – Advantages Hibernate – Download and Setup Hibernate – Sql Dialect list Hibernate – Helloworld – XML Hibernate – Install Tools in Eclipse Hibernate – Object States Hibernate – Helloworld – Annotations Hibernate – One to One Mapping – XML Hibernate – One to One Mapping foreign key – XML Hibernate – One To Many -XML Hibernate – One To Many – Annotations Hibernate – Many to Many Mapping – XML Hibernate – Many to One – XML Hibernate – Composite Key Mapping Hibernate – Named Query Hibernate – Native SQL Query Hibernate – load() vs get() Hibernate Criteria API with Example Hibernate – Restrictions Hibernate – Projection Hibernate – Query Language (HQL) Hibernate – Groupby Criteria HQL Hibernate – Orderby Criteria Hibernate – HQLSelect Operation Hibernate – HQL Update, Delete Hibernate – Update Query Hibernate – Update vs Merge Hibernate – Right Join Hibernate – Left Join Hibernate – Pagination Hibernate – Generator Classes Hibernate – Custom Generator Hibernate – Inheritance Mappings Hibernate – Table per Class Hibernate – Table per Sub Class Hibernate – Table per Concrete Class Hibernate – Table per Class Annotations Hibernate – Stored Procedures Hibernate – @Formula Annotation Hibernate – Singleton SessionFactory Hibernate – Interceptor hbm2ddl.auto Example in Hibernate XML Config Hibernate – First Level Cache
[ { "code": null, "e": 158, "s": 123, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 172, "s": 158, "text": "Java Examples" }, { "code": null, "e": 183, "s": 172, "text": "C Examples" }, { "code": null, "e": 195, "s": 183, "text": "C Tutorials" }, { "code": null, "e": 199, "s": 195, "text": "aws" }, { "code": null, "e": 234, "s": 199, "text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC" }, { "code": null, "e": 245, "s": 234, "text": "EXCEPTIONS" }, { "code": null, "e": 257, "s": 245, "text": "COLLECTIONS" }, { "code": null, "e": 263, "s": 257, "text": "SWING" }, { "code": null, "e": 268, "s": 263, "text": "JDBC" }, { "code": null, "e": 275, "s": 268, "text": "JAVA 8" }, { "code": null, "e": 282, "s": 275, "text": "SPRING" }, { "code": null, "e": 294, "s": 282, "text": "SPRING BOOT" }, { "code": null, "e": 304, "s": 294, "text": "HIBERNATE" }, { "code": null, "e": 311, "s": 304, "text": "PYTHON" }, { "code": null, "e": 315, "s": 311, "text": "PHP" }, { "code": null, "e": 322, "s": 315, "text": "JQUERY" }, { "code": null, "e": 357, "s": 322, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 371, "s": 357, "text": "Java Examples" }, { "code": null, "e": 382, "s": 371, "text": "C Examples" }, { "code": null, "e": 394, "s": 382, "text": "C Tutorials" }, { "code": null, "e": 398, "s": 394, "text": "aws" }, { "code": null, "e": 678, "s": 398, "text": "In this tutorial, we are going to see Hibernate Projection with a simple example. As we already discussed in the previous tutorial Hibernate Criteria, If we want to read a partial entity (selected columns) from the database, hibernate has provided us with a Projection interface." }, { "code": null, "e": 770, "s": 678, "text": "Projection is an interface in Hibernate; it is coming from org.hibernate.criterion package." }, { "code": null, "e": 819, "s": 770, "text": "Projection can be applied to the Criteria query." }, { "code": null, "e": 890, "s": 819, "text": "Projection is an Object-Oriented Representation of a query result set." }, { "code": null, "e": 963, "s": 890, "text": "Hibernate Projection is used to read a partial entity from the database." }, { "code": null, "e": 1141, "s": 963, "text": "If we want to read more than one property from the database, then we have to add Projection objects to ProjectionList, and then we need to set ProjectionList object to Criteria." }, { "code": null, "e": 1279, "s": 1141, "text": "The following code is to read the employee name column from the employee table. It will get all the employeNames from the employee table." }, { "code": null, "e": 1469, "s": 1279, "text": "Criteria criteria = session.createCriteria(Employee.class); \nProjection projection = Projections.property(\"employeeName\"); \ncriteria.setProjection(projection); \nList list = criteria.list();" }, { "code": null, "e": 1497, "s": 1469, "text": "select ename from employee;" }, { "code": null, "e": 1719, "s": 1497, "text": "If we want to read more than 1 column (employeeName, salary) with projections, we should have to use ProjectinList class. We should prepare all projections and bind all projections into a single ProjectionList like below." }, { "code": null, "e": 2154, "s": 1719, "text": "Criteria criteria = session.createCriteria(Employee.class); \nProjection projection = Projections.property(\"salary\"); \nProjection projection2 = Projections.property(\"departmentId\"); \nProjection projection3 = Projections.property(\"employeeName\"); \nProjectionList pList = Projections.projectionList(); \npList.add(projection); \npList.add(projection2); \npList.add(projection3); \ncriteria.setProjection(pList); \nList list = criteria.list();" }, { "code": null, "e": 2255, "s": 2154, "text": "On the above example, we will get the salary, departmentId and employeeName from the employee table." }, { "code": null, "e": 2289, "s": 2255, "text": "select sal,deptid,ename from emp;" }, { "code": null, "e": 2444, "s": 2289, "text": "Since those are multiple projections, first we need to add all projections to ProjectionList object and then add ProjectionList object to criteria object." }, { "code": null, "e": 2487, "s": 2444, "text": "Create Employee Pojo Class: Employee.class" }, { "code": null, "e": 3547, "s": 2487, "text": "package com.otp.hibernate.pojo;\n\npublic class Employee {\n private int employeeId;\n private String employeeName;\n private int departmentId;\n private int salary;\n\n public int getEmployeeId() {\n return employeeId;\n }\n\n public void setEmployeeId(int employeeId) {\n this.employeeId = employeeId;\n }\n\n public String getEmployeeName() {\n return employeeName;\n }\n\n public void setEmployeeName(String employeeName) {\n this.employeeName = employeeName;\n }\n\n public int getDepartmentId() {\n return departmentId;\n }\n\n public void setDepartmentId(int departmentId) {\n this.departmentId = departmentId;\n }\n\n public int getSalary() {\n return salary;\n }\n\n public void setSalary(int salary) {\n this.salary = salary;\n }\n\n @Override\n public String toString() {\n return \"Employee [employeeId=\" + employeeId + \", employeeName=\"\n + employeeName + \", departmentId=\" + departmentId + \", salary=\"\n + salary + \"]\";\n } \n\n}" }, { "code": null, "e": 3572, "s": 3547, "text": "Hibernate mapping file :" }, { "code": null, "e": 4148, "s": 3572, "text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE hibernate-mapping PUBLIC\n \"-//Hibernate/Hibernate Mapping DTD 3.0//EN\"\n \"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd\">\n<hibernate-mapping>\n <class name=\"com.otp.hibernate.pojo.Employee\" table=\"employee\"\n schema=\"onlinetutorialspoint\">\n <id name=\"employeeId\" column=\"id\">\n <generator class=\"increment\" />\n </id>\n <property name=\"employeeName\" column=\"ename\" />\n <property name=\"departmentId\" column=\"deptNo\" />\n <property name=\"salary\" column=\"salary\" />\n </class>\n</hibernate-mapping>" }, { "code": null, "e": 4170, "s": 4148, "text": "Run the Application :" }, { "code": null, "e": 6510, "s": 4170, "text": "import java.util.Iterator;\nimport java.util.List;\n\nimport org.hibernate.Criteria;\nimport org.hibernate.Session;\nimport org.hibernate.SessionFactory;\nimport org.hibernate.boot.registry.StandardServiceRegistryBuilder;\nimport org.hibernate.cfg.Configuration;\nimport org.hibernate.criterion.Criterion;\nimport org.hibernate.criterion.Projection;\nimport org.hibernate.criterion.ProjectionList;\nimport org.hibernate.criterion.Projections;\nimport org.hibernate.criterion.Restrictions;\n\nimport com.otp.hibernate.pojo.Employee;\n\npublic class Main {\n\n public static void main(String[] args) {\n Configuration configuration = new Configuration()\n .configure(\"hibernate.cfg.xml\");\n StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()\n .applySettings(configuration.getProperties());\n SessionFactory factory = configuration.buildSessionFactory(builder\n .build());\n\n Session session = factory.openSession();\n\n System.out.println(\"Reading Partial Entity with One Projection object \");\n\n Criteria criteria = session.createCriteria(Employee.class);\n Projection projection = Projections.property(\"salary\");\n criteria.setProjection(projection);\n List list = criteria.list();\n Iterator it = list.iterator();\n\n while (it.hasNext()) {\n Integer sal = (Integer) it.next();\n System.out.println(\"Employee Salary : \" + sal);\n }\n \n System.out.println(\"Reading Partial Entity with multiple Projection objects \");\n \n Criteria crit2 = session.createCriteria(Employee.class);\n Projection projection1 = Projections.property(\"salary\");\n Projection projection2 = Projections.property(\"departmentId\");\n Projection projection3 = Projections.property(\"employeeName\");\n \n ProjectionList pList = Projections.projectionList();\n pList.add(projection1);\n pList.add(projection2);\n pList.add(projection3);\n crit2.setProjection(pList);\n \n List list2 = crit2.list();\n\n Iterator it2 = list2.iterator();\n\n while (it2.hasNext()) {\n Object[] obj = (Object[]) it2.next();\n System.out.println(\"Salary : \" + obj[0]+\" DeptId : \"+obj[1]+\" empName : \"+obj[2]);\n }\n }\n}" }, { "code": null, "e": 6519, "s": 6510, "text": "Output :" }, { "code": null, "e": 7029, "s": 6519, "text": "Reading Partial Entity with One Projection object \nEmployee Salary : 6000 Employee Salary : 8000 Employee Salary : 4000 Employee Salary : 5000 Employee Salary : 4000 Employee Salary : 3000 \nReading Partial Entity with multiple Projection objects \nSalary : 6000 DeptId : 101 empName : Chandra Salary : 8000 DeptId : 101 empName : Shekhar Salary : 4000 DeptId : 105 empName : Rahul Salary : 5000 DeptId : 103 empName : Mahesh Salary : 4000 DeptId : 101 empName : Vinay Salary : 3000 DeptId : 105 empName : Vijay" }, { "code": null, "e": 7077, "s": 7029, "text": "The complete example is available for download." }, { "code": null, "e": 7094, "s": 7077, "text": "Happy Learning 🙂" }, { "code": null, "e": 7160, "s": 7094, "text": "\n\nHibernate-Projection-Example\n\nFile size: 13 KB\nDownloads: 1697\n" }, { "code": null, "e": 7716, "s": 7160, "text": "\nHibernate Criteria API with Example\nHibernate Restrictions with Example\nHibernate Native SQL Query Example\nHibernate Named Query with Example\nHibernate Filter Example Xml Configuration\nhibernate update query example\nHibernate Right Join Example\nWhat is Association in Java\nWhat is Hibernate\nHibernate 4 Example with Annotations Mysql\nTop 10 Advantages of Hibernate\nDifferent types of Object States in Hibernate\nDifference between update vs merge in Hibernate example\nSingleton Hibernate SessionFactory Example\nHibernate One To Many Example (XML Mapping)\n" }, { "code": null, "e": 7752, "s": 7716, "text": "Hibernate Criteria API with Example" }, { "code": null, "e": 7788, "s": 7752, "text": "Hibernate Restrictions with Example" }, { "code": null, "e": 7823, "s": 7788, "text": "Hibernate Native SQL Query Example" }, { "code": null, "e": 7858, "s": 7823, "text": "Hibernate Named Query with Example" }, { "code": null, "e": 7901, "s": 7858, "text": "Hibernate Filter Example Xml Configuration" }, { "code": null, "e": 7932, "s": 7901, "text": "hibernate update query example" }, { "code": null, "e": 7961, "s": 7932, "text": "Hibernate Right Join Example" }, { "code": null, "e": 7989, "s": 7961, "text": "What is Association in Java" }, { "code": null, "e": 8007, "s": 7989, "text": "What is Hibernate" }, { "code": null, "e": 8050, "s": 8007, "text": "Hibernate 4 Example with Annotations Mysql" }, { "code": null, "e": 8081, "s": 8050, "text": "Top 10 Advantages of Hibernate" }, { "code": null, "e": 8127, "s": 8081, "text": "Different types of Object States in Hibernate" }, { "code": null, "e": 8183, "s": 8127, "text": "Difference between update vs merge in Hibernate example" }, { "code": null, "e": 8226, "s": 8183, "text": "Singleton Hibernate SessionFactory Example" }, { "code": null, "e": 8270, "s": 8226, "text": "Hibernate One To Many Example (XML Mapping)" }, { "code": null, "e": 8714, "s": 8270, "text": "\n\n\n\n\n\navulavenkatareddy\nFebruary 5, 2017 at 12:51 pm - Reply \n\nHiii.....\nyour website giving the information is awesome but please give the more concepts and depth information and other extra concepts.\n Thank you........................\n\n\n\n\n\n\n\n\n\nRam\nNovember 7, 2018 at 3:16 am - Reply \n\nHi .. thank you for for providing the concept , in this I have one question .. Can we apply pagination on Projection queries ..\n\n\n\n\n" }, { "code": null, "e": 8976, "s": 8714, "text": "\n\n\n\n\navulavenkatareddy\nFebruary 5, 2017 at 12:51 pm - Reply \n\nHiii.....\nyour website giving the information is awesome but please give the more concepts and depth information and other extra concepts.\n Thank you........................\n\n\n\n" }, { "code": null, "e": 9116, "s": 8976, "text": "Hiii.....\nyour website giving the information is awesome but please give the more concepts and depth information and other extra concepts." }, { "code": null, "e": 9172, "s": 9116, "text": " Thank you........................" }, { "code": null, "e": 9352, "s": 9172, "text": "\n\n\n\n\nRam\nNovember 7, 2018 at 3:16 am - Reply \n\nHi .. thank you for for providing the concept , in this I have one question .. Can we apply pagination on Projection queries ..\n\n\n\n" }, { "code": null, "e": 9481, "s": 9352, "text": "Hi .. thank you for for providing the concept , in this I have one question .. Can we apply pagination on Projection queries .." }, { "code": null, "e": 9487, "s": 9485, "text": "Δ" }, { "code": null, "e": 9513, "s": 9487, "text": " Hibernate – Introduction" }, { "code": null, "e": 9537, "s": 9513, "text": " Hibernate – Advantages" }, { "code": null, "e": 9569, "s": 9537, "text": " Hibernate – Download and Setup" }, { "code": null, "e": 9599, "s": 9569, "text": " Hibernate – Sql Dialect list" }, { "code": null, "e": 9629, "s": 9599, "text": " Hibernate – Helloworld – XML" }, { "code": null, "e": 9667, "s": 9629, "text": " Hibernate – Install Tools in Eclipse" }, { "code": null, "e": 9694, "s": 9667, "text": " Hibernate – Object States" }, { "code": null, "e": 9732, "s": 9694, "text": " Hibernate – Helloworld – Annotations" }, { "code": null, "e": 9770, "s": 9732, "text": " Hibernate – One to One Mapping – XML" }, { "code": null, "e": 9820, "s": 9770, "text": " Hibernate – One to One Mapping foreign key – XML" }, { "code": null, "e": 9850, "s": 9820, "text": " Hibernate – One To Many -XML" }, { "code": null, "e": 9889, "s": 9850, "text": " Hibernate – One To Many – Annotations" }, { "code": null, "e": 9929, "s": 9889, "text": " Hibernate – Many to Many Mapping – XML" }, { "code": null, "e": 9960, "s": 9929, "text": " Hibernate – Many to One – XML" }, { "code": null, "e": 9995, "s": 9960, "text": " Hibernate – Composite Key Mapping" }, { "code": null, "e": 10020, "s": 9995, "text": " Hibernate – Named Query" }, { "code": null, "e": 10050, "s": 10020, "text": " Hibernate – Native SQL Query" }, { "code": null, "e": 10079, "s": 10050, "text": " Hibernate – load() vs get()" }, { "code": null, "e": 10116, "s": 10079, "text": " Hibernate Criteria API with Example" }, { "code": null, "e": 10142, "s": 10116, "text": " Hibernate – Restrictions" }, { "code": null, "e": 10166, "s": 10142, "text": " Hibernate – Projection" }, { "code": null, "e": 10200, "s": 10166, "text": " Hibernate – Query Language (HQL)" }, { "code": null, "e": 10234, "s": 10200, "text": " Hibernate – Groupby Criteria HQL" }, { "code": null, "e": 10264, "s": 10234, "text": " Hibernate – Orderby Criteria" }, { "code": null, "e": 10297, "s": 10264, "text": " Hibernate – HQLSelect Operation" }, { "code": null, "e": 10329, "s": 10297, "text": " Hibernate – HQL Update, Delete" }, { "code": null, "e": 10355, "s": 10329, "text": " Hibernate – Update Query" }, { "code": null, "e": 10384, "s": 10355, "text": " Hibernate – Update vs Merge" }, { "code": null, "e": 10408, "s": 10384, "text": " Hibernate – Right Join" }, { "code": null, "e": 10431, "s": 10408, "text": " Hibernate – Left Join" }, { "code": null, "e": 10455, "s": 10431, "text": " Hibernate – Pagination" }, { "code": null, "e": 10486, "s": 10455, "text": " Hibernate – Generator Classes" }, { "code": null, "e": 10516, "s": 10486, "text": " Hibernate – Custom Generator" }, { "code": null, "e": 10550, "s": 10516, "text": " Hibernate – Inheritance Mappings" }, { "code": null, "e": 10579, "s": 10550, "text": " Hibernate – Table per Class" }, { "code": null, "e": 10612, "s": 10579, "text": " Hibernate – Table per Sub Class" }, { "code": null, "e": 10650, "s": 10612, "text": " Hibernate – Table per Concrete Class" }, { "code": null, "e": 10692, "s": 10650, "text": " Hibernate – Table per Class Annotations" }, { "code": null, "e": 10723, "s": 10692, "text": " Hibernate – Stored Procedures" }, { "code": null, "e": 10756, "s": 10723, "text": " Hibernate – @Formula Annotation" }, { "code": null, "e": 10794, "s": 10756, "text": " Hibernate – Singleton SessionFactory" }, { "code": null, "e": 10819, "s": 10794, "text": " Hibernate – Interceptor" }, { "code": null, "e": 10865, "s": 10819, "text": " hbm2ddl.auto Example in Hibernate XML Config" } ]
How select specific rows in MySQL?
To select specific rows, use FIND_IN_SET() function in MySQL. Let us first create a table − mysql> create table DemoTable ( ListOfValues varchar(200) ); Query OK, 0 rows affected (0.31 sec) Insert some records in the table using insert command − mysql> insert into DemoTable values('112,114,567,Java,345'); Query OK, 1 row affected (0.06 sec) mysql> insert into DemoTable values('222,214,256'); Query OK, 1 row affected (0.06 sec) mysql> insert into DemoTable values('2,567,98,C'); Query OK, 1 row affected (0.06 sec) Display all records from the table using select statement − mysql> select *from DemoTable; This will produce the following output − +----------------------+ | ListOfValues | +----------------------+ | 112,114,567,Java,345 | | 222,214,256 | | 2,567,98,C | +----------------------+ 3 rows in set (0.00 sec) Following is the query to select specific rows in MySQL − mysql> select *from DemoTable where find_in_set('2',ListOfValues) >0; This will produce the following output − +--------------+ | ListOfValues | +--------------+ | 2,567,98,C | +--------------+ 1 row in set (0.03 sec)
[ { "code": null, "e": 1154, "s": 1062, "text": "To select specific rows, use FIND_IN_SET() function in MySQL. Let us first create a table −" }, { "code": null, "e": 1261, "s": 1154, "text": "mysql> create table DemoTable\n (\n ListOfValues varchar(200)\n );\nQuery OK, 0 rows affected (0.31 sec)" }, { "code": null, "e": 1317, "s": 1261, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1591, "s": 1317, "text": "mysql> insert into DemoTable values('112,114,567,Java,345');\nQuery OK, 1 row affected (0.06 sec)\n\nmysql> insert into DemoTable values('222,214,256');\nQuery OK, 1 row affected (0.06 sec)\n\nmysql> insert into DemoTable values('2,567,98,C');\nQuery OK, 1 row affected (0.06 sec)" }, { "code": null, "e": 1651, "s": 1591, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1682, "s": 1651, "text": "mysql> select *from DemoTable;" }, { "code": null, "e": 1723, "s": 1682, "text": "This will produce the following output −" }, { "code": null, "e": 1923, "s": 1723, "text": "+----------------------+\n| ListOfValues |\n+----------------------+\n| 112,114,567,Java,345 |\n| 222,214,256 |\n| 2,567,98,C |\n+----------------------+\n3 rows in set (0.00 sec)" }, { "code": null, "e": 1981, "s": 1923, "text": "Following is the query to select specific rows in MySQL −" }, { "code": null, "e": 2051, "s": 1981, "text": "mysql> select *from DemoTable where find_in_set('2',ListOfValues) >0;" }, { "code": null, "e": 2092, "s": 2051, "text": "This will produce the following output −" }, { "code": null, "e": 2201, "s": 2092, "text": "+--------------+\n| ListOfValues |\n+--------------+\n| 2,567,98,C |\n+--------------+\n1 row in set (0.03 sec)" } ]
Return all dates between two dates in an array in PHP
To return all dates between two dates, the code is as follows − Live Demo <?php function displayDates($date1, $date2, $format = 'd-m-Y' ) { $dates = array(); $current = strtotime($date1); $date2 = strtotime($date2); $stepVal = '+1 day'; while( $current <= $date2 ) { $dates[] = date($format, $current); $current = strtotime($stepVal, $current); } return $dates; } $date = displayDates('2019-11-10', '2019-11-20'); var_dump($date); ?> This will produce the following output− array(11) { [0]=> string(10) "10-11-2019" [1]=> string(10) "11-11-2019" [2]=> string(10) "12-11-2019" [3]=> string(10) "13-11-2019" [4]=> string(10) "14-11-2019" [5]=> string(10) "15-11-2019" [6]=> string(10) "16-11-2019" [7]=> string(10) "17-11-2019" [8]=> string(10) "18-11-2019" [9]=> string(10) "19-11-2019" [10]=> string(10) "20-11-2019" }
[ { "code": null, "e": 1126, "s": 1062, "text": "To return all dates between two dates, the code is as follows −" }, { "code": null, "e": 1137, "s": 1126, "text": " Live Demo" }, { "code": null, "e": 1569, "s": 1137, "text": "<?php\n function displayDates($date1, $date2, $format = 'd-m-Y' ) {\n $dates = array();\n $current = strtotime($date1);\n $date2 = strtotime($date2);\n $stepVal = '+1 day';\n while( $current <= $date2 ) {\n $dates[] = date($format, $current);\n $current = strtotime($stepVal, $current);\n }\n return $dates;\n }\n $date = displayDates('2019-11-10', '2019-11-20');\n var_dump($date);\n?>" }, { "code": null, "e": 1609, "s": 1569, "text": "This will produce the following output−" }, { "code": null, "e": 2021, "s": 1609, "text": "array(11) {\n [0]=>\n string(10) \"10-11-2019\"\n [1]=>\n string(10) \"11-11-2019\"\n [2]=>\n string(10) \"12-11-2019\"\n [3]=>\n string(10) \"13-11-2019\"\n [4]=>\n string(10) \"14-11-2019\"\n [5]=>\n string(10) \"15-11-2019\"\n [6]=>\n string(10) \"16-11-2019\"\n [7]=>\n string(10) \"17-11-2019\"\n [8]=>\n string(10) \"18-11-2019\"\n [9]=>\n string(10) \"19-11-2019\"\n [10]=>\n string(10) \"20-11-2019\" \n}" } ]
Keyword Extraction: from TF-IDF to BERT | Towards Data Science
The keyword extraction is one of the most required text mining tasks: given a document, the extraction algorithm should identify a set of terms that best describe its argument. In this tutorial, we are going to perform keyword extraction with five different approaches: TF-IDF, TextRank, TopicRank, YAKE!, and KeyBERT. Let’s see who performs better! Let’s install the packages required in this tutorial: pip install trafilaturapip install summapip install git+https://github.com/smirnov-am/pytopicrank.git#egg=pytopicrankpip install git+https://github.com/LIAAD/yakepip install keyBERT After having installed the packages above, open a Python session, and download these data from nltk: import nltknltk.download('stopwords')nltk.download('punkt')nltk.download('averaged_perceptron_tagger') Now, your environment is ready to test all six keyword extraction approaches! We are going to test the algorithms by extracting the keywords from five online articles. We report here the links to these articles. en.wikipedia.org en.wikipedia.org en.wikipedia.org en.wikipedia.org en.wikipedia.org As you can see, they regard different topics. We extract the articles' texts from each webpage and perform some basic text cleaning. We take only the first 5000 characters. import trafilaturaarray_links = [ "https://en.wikipedia.org/wiki/Coronavirus_disease_2019", "https://en.wikipedia.org/wiki/Recession", "https://en.wikipedia.org/wiki/Vienna", "https://en.wikipedia.org/wiki/Machine_learning", "https://en.wikipedia.org/wiki/Graph_database"]array_text = []for l in array_links: html = trafilatura.fetch_url(l) text = trafilatura.extract(html) text_clean = text.replace("\n", " ").replace("\'", "") array_text.append(text_clean[0:5000]) At the end of the execution of the code above, we should have a list of cleaned texts (documents). Of course, you can substitute these texts with anything you want to test! Now we are ready to test the keyword extraction algorithms! TF-IDF (term frequency-inverse document frequency) is a weighting statistic that indicates if a word is important in a particular document of a corpus. For instance, the corpus could be the set of all Wikipedia articles while a document is a particular article. Given a particular document, if we consider the word “the”, it is present several times so it has a high TF, but it is present also in almost every article on Wikipedia, hence, IDF is very low. Overall, the word “the” has a low TF-IDF score. We suppose that the keywords of a document should have a high TF-IDF score. Given a document, it is easy to compute the TF score of every word but for the IDF score, we need a huge corpus of similar documents which is not provided most of the time. In this tutorial, we are going to use the IDF scores computed on Wikipedia. You can download them here: zenodo.org We use the file wiki_tfidf_terms.csv inside the zip folder but you could try to use the stems file in order to improve the accuracy for the keyword extractor (don’t forget to perform the stemming in this case!). from itertools import islicefrom tqdm.notebook import tqdmfrom re import subnum_lines = sum(1 for line in open("wiki_tfidf_terms.csv"))with open("wiki_tfidf_terms.csv") as file: dict_idf = {} with tqdm(total=num_lines) as pbar: for i, line in tqdm(islice(enumerate(file), 1, None)): try: cells = line.split(",") idf = float(sub("[^0-9.]", "", cells[3])) dict_idf[cells[0]] = idf except: print("Error on: " + line) finally: pbar.update(1) Then, for each article inside our list, we compute the TF score of its words. from sklearn.feature_extraction.text import CountVectorizerfrom numpy import array, logvectorizer = CountVectorizer()tf = vectorizer.fit_transform([x.lower() for x in array_text])tf = tf.toarray()tf = log(tf + 1) Now, we are ready to multiply TF with IDF. tfidf = tf.copy()words = array(vectorizer.get_feature_names())for k in tqdm(dict_idf.keys()): if k in words: tfidf[:, words == k] = tfidf[:, words == k] * dict_idf[k] pbar.update(1) Let’s print the extracted keywords. for j in range(tfidf.shape[0]): print("Keywords of article", str(j+1), words[tfidf[j, :].argsort()[-5:][::-1]]) Output: Keywords of article 1 ['covid' 'coronavirus' 'symptoms' 'respiratory' 'cov']Keywords of article 2 ['recessions' 'recession' 'nber' 'gdp' 'shaped']Keywords of article 3 ['vienna' 'km2' 'citys' 'sq' 'vedunia']Keywords of article 4 ['learning' 'machine' 'algorithms' 'tasks' 'unsupervised']Keywords of article 5 ['graph' 'databases' 'relational' 'database' 'nosql'] TextRank is an unsupervised method to perform keyword and sentence extraction. It is based on a graph where each node is a word and the edges are constructed by observing the co-occurrence of words inside a moving window of predefined size. Important nodes of the graph, computed with an algorithm similar to PageRank, represent keywords in the text. We are going to use the keywords extractor implemented in summa. from summa import keywordsfor j in range(len(array_text)): print("Keywords of article", str(j+1), "\n", (keywords.keywords(array_text[j], words=5)).split("\n")) Output: Keywords of article 1 ['symptoms', 'include', 'including', 'covid', 'cough', 'coughs', 'respiratory']Keywords of article 2 ['recession', 'recessions', 'economics', 'economic', 'shapes', 'shape', 'governments', 'government', 'policies', 'policy']Keywords of article 3 ['vienna', 'viennas', 'city', 'cities', 'citys', 'rank', 'ranked', 'mi', 'world', 'worlds']Keywords of article 4 ['learn', 'learns', 'machine learning', 'algorithms', 'algorithm', 'data', 'machines', 'tasks', 'task']Keywords of article 5 ['graphs', 'graph database', 'databases', 'model', 'models', 'data', 'relates', 'relational', 'relation'] TopicRank is another unsupervised graph-based keyphrase extractor. Different from TextRank, in this case, the nodes of the graph are topics and each topic is a cluster of similar single and multiword expressions. Let’s try the Python implementation of this keywords extractor. from pytopicrank import TopicRankfor j in range(len(array_text)): tr = TopicRank(array_text[j]) print("Keywords of article", str(j+1), "\n", tr.get_top_n(n=5, extract_strategy='first')) Output: Keywords of article 1 ['cause covid', 'symptoms', 'day', 'infected person', 'spreads']Keywords of article 2 ['onset recession', 'consecutive quarters', 'decline', 'shaped', 'activity economic']Keywords of article 3 ['population citys', 'viˈɛnə vienna', 'heritage worlds', 'austria', 'elevation sq mi']Keywords of article 4 ['machines', 'computer', 'tasks', 'field', 'data']Keywords of article 5 ['relationships database', 'data', 'commercial database graph', 'edge', 'graph'] YAKE! is an unsupervised keyword extraction algorithm based on the features extracted from the documents and it is multilingual: English, Italian, German, Dutch, Spanish, Finnish, French, Polish, Turkish, Portuguese, and Arabic. You can try their demo directly on their website: yake.inesctec.pt Luckily, also in this case, there is already a Python implementation. Let’s try it on our documents. from yake import KeywordExtractorkw_extractor = KeywordExtractor(lan="en", n=1, top=5)for j in range(len(array_text)): keywords = kw_extractor.extract_keywords(text=array_text[j]) keywords = [x for x, y in keywords] print("Keywords of article", str(j+1), "\n", keywords) Output: Keywords of article 1 ['symptoms', 'respiratory', 'acute', 'coronavirus', 'disease']Keywords of article 2 ['economic', 'recession', 'recessions', 'gdp', 'united']Keywords of article 3 ['vienna', 'city', 'capital', 'state', 'german']Keywords of article 4 ['learning', 'machine', 'computer', 'tasks', 'computers']Keywords of article 5 ['graph', 'databases', 'database', 'data', 'relationships'] BERT (Bidirectional Encoder Representations from Transformers) is a transformer-based model for natural language processing. Pretrained models can transform sentences or words in language representation consisting of an array of numbers (embedding). Sentences or words having similar latent representations (embedding) should have similar semantic meanings. An implementation that uses this approach to extract the keywords of a text is KeyBERT. Let’s see how this keyword extractor performs. from keybert import KeyBERTkw_extractor = KeyBERT('distilbert-base-nli-mean-tokens')for j in range(len(array_text)): keywords = kw_extractor.extract_keywords(array_text[j], keyphrase_length=1, stop_words='english') print("Keywords of article", str(j+1), "\n", keywords) Output: Keywords of article 1 ['coronavirus', 'pneumonia', 'vaccines', 'virus', 'viral']Keywords of article 2 ['recessions', 'recession', 'unemployment', 'pandemic', 'worsening']Keywords of article 3 ['austrias', 'austria', 'vienna', 'austrian', 'beethoven']Keywords of article 4 ['algorithms', 'algorithm', 'computational', 'computers', 'mathematical']Keywords of article 5 ['graphs', 'graph', 'databases', 'web', 'database'] In this tutorial, we have seen different approaches to extract keywords from a given text. All of them don’t require any training. This list is far from being complete! Check the most recent review to have a complete overview! We have tested both simple approaches like TF-IDF and advanced models like BERT. Unfortunately, there isn’t a model that performs well on every document. It depends on the type of document, the context, and the corpus used for the model pretraining. A more complete preprocessing with a combination of different keyword extraction approaches should definitely improve the performance! https://scholar.google.it/scholar?q=keyword+extraction+review http://www.tfidf.com/ https://www.aclweb.org/anthology/W04-3252.pdf https://www.aclweb.org/anthology/I13-1062/ http://yake.inesctec.pt/ https://towardsdatascience.com/keyword-extraction-with-bert-724efca412ea Contacts: LinkedIn | Twitter
[ { "code": null, "e": 522, "s": 172, "text": "The keyword extraction is one of the most required text mining tasks: given a document, the extraction algorithm should identify a set of terms that best describe its argument. In this tutorial, we are going to perform keyword extraction with five different approaches: TF-IDF, TextRank, TopicRank, YAKE!, and KeyBERT. Let’s see who performs better!" }, { "code": null, "e": 576, "s": 522, "text": "Let’s install the packages required in this tutorial:" }, { "code": null, "e": 758, "s": 576, "text": "pip install trafilaturapip install summapip install git+https://github.com/smirnov-am/pytopicrank.git#egg=pytopicrankpip install git+https://github.com/LIAAD/yakepip install keyBERT" }, { "code": null, "e": 859, "s": 758, "text": "After having installed the packages above, open a Python session, and download these data from nltk:" }, { "code": null, "e": 962, "s": 859, "text": "import nltknltk.download('stopwords')nltk.download('punkt')nltk.download('averaged_perceptron_tagger')" }, { "code": null, "e": 1040, "s": 962, "text": "Now, your environment is ready to test all six keyword extraction approaches!" }, { "code": null, "e": 1174, "s": 1040, "text": "We are going to test the algorithms by extracting the keywords from five online articles. We report here the links to these articles." }, { "code": null, "e": 1191, "s": 1174, "text": "en.wikipedia.org" }, { "code": null, "e": 1208, "s": 1191, "text": "en.wikipedia.org" }, { "code": null, "e": 1225, "s": 1208, "text": "en.wikipedia.org" }, { "code": null, "e": 1242, "s": 1225, "text": "en.wikipedia.org" }, { "code": null, "e": 1259, "s": 1242, "text": "en.wikipedia.org" }, { "code": null, "e": 1305, "s": 1259, "text": "As you can see, they regard different topics." }, { "code": null, "e": 1432, "s": 1305, "text": "We extract the articles' texts from each webpage and perform some basic text cleaning. We take only the first 5000 characters." }, { "code": null, "e": 1930, "s": 1432, "text": "import trafilaturaarray_links = [ \"https://en.wikipedia.org/wiki/Coronavirus_disease_2019\", \"https://en.wikipedia.org/wiki/Recession\", \"https://en.wikipedia.org/wiki/Vienna\", \"https://en.wikipedia.org/wiki/Machine_learning\", \"https://en.wikipedia.org/wiki/Graph_database\"]array_text = []for l in array_links: html = trafilatura.fetch_url(l) text = trafilatura.extract(html) text_clean = text.replace(\"\\n\", \" \").replace(\"\\'\", \"\") array_text.append(text_clean[0:5000])" }, { "code": null, "e": 2103, "s": 1930, "text": "At the end of the execution of the code above, we should have a list of cleaned texts (documents). Of course, you can substitute these texts with anything you want to test!" }, { "code": null, "e": 2163, "s": 2103, "text": "Now we are ready to test the keyword extraction algorithms!" }, { "code": null, "e": 2743, "s": 2163, "text": "TF-IDF (term frequency-inverse document frequency) is a weighting statistic that indicates if a word is important in a particular document of a corpus. For instance, the corpus could be the set of all Wikipedia articles while a document is a particular article. Given a particular document, if we consider the word “the”, it is present several times so it has a high TF, but it is present also in almost every article on Wikipedia, hence, IDF is very low. Overall, the word “the” has a low TF-IDF score. We suppose that the keywords of a document should have a high TF-IDF score." }, { "code": null, "e": 3020, "s": 2743, "text": "Given a document, it is easy to compute the TF score of every word but for the IDF score, we need a huge corpus of similar documents which is not provided most of the time. In this tutorial, we are going to use the IDF scores computed on Wikipedia. You can download them here:" }, { "code": null, "e": 3031, "s": 3020, "text": "zenodo.org" }, { "code": null, "e": 3243, "s": 3031, "text": "We use the file wiki_tfidf_terms.csv inside the zip folder but you could try to use the stems file in order to improve the accuracy for the keyword extractor (don’t forget to perform the stemming in this case!)." }, { "code": null, "e": 3804, "s": 3243, "text": "from itertools import islicefrom tqdm.notebook import tqdmfrom re import subnum_lines = sum(1 for line in open(\"wiki_tfidf_terms.csv\"))with open(\"wiki_tfidf_terms.csv\") as file: dict_idf = {} with tqdm(total=num_lines) as pbar: for i, line in tqdm(islice(enumerate(file), 1, None)): try: cells = line.split(\",\") idf = float(sub(\"[^0-9.]\", \"\", cells[3])) dict_idf[cells[0]] = idf except: print(\"Error on: \" + line) finally: pbar.update(1)" }, { "code": null, "e": 3882, "s": 3804, "text": "Then, for each article inside our list, we compute the TF score of its words." }, { "code": null, "e": 4095, "s": 3882, "text": "from sklearn.feature_extraction.text import CountVectorizerfrom numpy import array, logvectorizer = CountVectorizer()tf = vectorizer.fit_transform([x.lower() for x in array_text])tf = tf.toarray()tf = log(tf + 1)" }, { "code": null, "e": 4138, "s": 4095, "text": "Now, we are ready to multiply TF with IDF." }, { "code": null, "e": 4333, "s": 4138, "text": "tfidf = tf.copy()words = array(vectorizer.get_feature_names())for k in tqdm(dict_idf.keys()): if k in words: tfidf[:, words == k] = tfidf[:, words == k] * dict_idf[k] pbar.update(1)" }, { "code": null, "e": 4369, "s": 4333, "text": "Let’s print the extracted keywords." }, { "code": null, "e": 4484, "s": 4369, "text": "for j in range(tfidf.shape[0]): print(\"Keywords of article\", str(j+1), words[tfidf[j, :].argsort()[-5:][::-1]])" }, { "code": null, "e": 4492, "s": 4484, "text": "Output:" }, { "code": null, "e": 4860, "s": 4492, "text": "Keywords of article 1 ['covid' 'coronavirus' 'symptoms' 'respiratory' 'cov']Keywords of article 2 ['recessions' 'recession' 'nber' 'gdp' 'shaped']Keywords of article 3 ['vienna' 'km2' 'citys' 'sq' 'vedunia']Keywords of article 4 ['learning' 'machine' 'algorithms' 'tasks' 'unsupervised']Keywords of article 5 ['graph' 'databases' 'relational' 'database' 'nosql']" }, { "code": null, "e": 5211, "s": 4860, "text": "TextRank is an unsupervised method to perform keyword and sentence extraction. It is based on a graph where each node is a word and the edges are constructed by observing the co-occurrence of words inside a moving window of predefined size. Important nodes of the graph, computed with an algorithm similar to PageRank, represent keywords in the text." }, { "code": null, "e": 5276, "s": 5211, "text": "We are going to use the keywords extractor implemented in summa." }, { "code": null, "e": 5440, "s": 5276, "text": "from summa import keywordsfor j in range(len(array_text)): print(\"Keywords of article\", str(j+1), \"\\n\", (keywords.keywords(array_text[j], words=5)).split(\"\\n\"))" }, { "code": null, "e": 5448, "s": 5440, "text": "Output:" }, { "code": null, "e": 6064, "s": 5448, "text": "Keywords of article 1 ['symptoms', 'include', 'including', 'covid', 'cough', 'coughs', 'respiratory']Keywords of article 2 ['recession', 'recessions', 'economics', 'economic', 'shapes', 'shape', 'governments', 'government', 'policies', 'policy']Keywords of article 3 ['vienna', 'viennas', 'city', 'cities', 'citys', 'rank', 'ranked', 'mi', 'world', 'worlds']Keywords of article 4 ['learn', 'learns', 'machine learning', 'algorithms', 'algorithm', 'data', 'machines', 'tasks', 'task']Keywords of article 5 ['graphs', 'graph database', 'databases', 'model', 'models', 'data', 'relates', 'relational', 'relation']" }, { "code": null, "e": 6277, "s": 6064, "text": "TopicRank is another unsupervised graph-based keyphrase extractor. Different from TextRank, in this case, the nodes of the graph are topics and each topic is a cluster of similar single and multiword expressions." }, { "code": null, "e": 6341, "s": 6277, "text": "Let’s try the Python implementation of this keywords extractor." }, { "code": null, "e": 6533, "s": 6341, "text": "from pytopicrank import TopicRankfor j in range(len(array_text)): tr = TopicRank(array_text[j]) print(\"Keywords of article\", str(j+1), \"\\n\", tr.get_top_n(n=5, extract_strategy='first'))" }, { "code": null, "e": 6541, "s": 6533, "text": "Output:" }, { "code": null, "e": 7022, "s": 6541, "text": "Keywords of article 1 ['cause covid', 'symptoms', 'day', 'infected person', 'spreads']Keywords of article 2 ['onset recession', 'consecutive quarters', 'decline', 'shaped', 'activity economic']Keywords of article 3 ['population citys', 'viˈɛnə vienna', 'heritage worlds', 'austria', 'elevation sq mi']Keywords of article 4 ['machines', 'computer', 'tasks', 'field', 'data']Keywords of article 5 ['relationships database', 'data', 'commercial database graph', 'edge', 'graph']" }, { "code": null, "e": 7251, "s": 7022, "text": "YAKE! is an unsupervised keyword extraction algorithm based on the features extracted from the documents and it is multilingual: English, Italian, German, Dutch, Spanish, Finnish, French, Polish, Turkish, Portuguese, and Arabic." }, { "code": null, "e": 7301, "s": 7251, "text": "You can try their demo directly on their website:" }, { "code": null, "e": 7318, "s": 7301, "text": "yake.inesctec.pt" }, { "code": null, "e": 7419, "s": 7318, "text": "Luckily, also in this case, there is already a Python implementation. Let’s try it on our documents." }, { "code": null, "e": 7699, "s": 7419, "text": "from yake import KeywordExtractorkw_extractor = KeywordExtractor(lan=\"en\", n=1, top=5)for j in range(len(array_text)): keywords = kw_extractor.extract_keywords(text=array_text[j]) keywords = [x for x, y in keywords] print(\"Keywords of article\", str(j+1), \"\\n\", keywords)" }, { "code": null, "e": 7707, "s": 7699, "text": "Output:" }, { "code": null, "e": 8105, "s": 7707, "text": "Keywords of article 1 ['symptoms', 'respiratory', 'acute', 'coronavirus', 'disease']Keywords of article 2 ['economic', 'recession', 'recessions', 'gdp', 'united']Keywords of article 3 ['vienna', 'city', 'capital', 'state', 'german']Keywords of article 4 ['learning', 'machine', 'computer', 'tasks', 'computers']Keywords of article 5 ['graph', 'databases', 'database', 'data', 'relationships']" }, { "code": null, "e": 8551, "s": 8105, "text": "BERT (Bidirectional Encoder Representations from Transformers) is a transformer-based model for natural language processing. Pretrained models can transform sentences or words in language representation consisting of an array of numbers (embedding). Sentences or words having similar latent representations (embedding) should have similar semantic meanings. An implementation that uses this approach to extract the keywords of a text is KeyBERT." }, { "code": null, "e": 8598, "s": 8551, "text": "Let’s see how this keyword extractor performs." }, { "code": null, "e": 8874, "s": 8598, "text": "from keybert import KeyBERTkw_extractor = KeyBERT('distilbert-base-nli-mean-tokens')for j in range(len(array_text)): keywords = kw_extractor.extract_keywords(array_text[j], keyphrase_length=1, stop_words='english') print(\"Keywords of article\", str(j+1), \"\\n\", keywords)" }, { "code": null, "e": 8882, "s": 8874, "text": "Output:" }, { "code": null, "e": 9306, "s": 8882, "text": "Keywords of article 1 ['coronavirus', 'pneumonia', 'vaccines', 'virus', 'viral']Keywords of article 2 ['recessions', 'recession', 'unemployment', 'pandemic', 'worsening']Keywords of article 3 ['austrias', 'austria', 'vienna', 'austrian', 'beethoven']Keywords of article 4 ['algorithms', 'algorithm', 'computational', 'computers', 'mathematical']Keywords of article 5 ['graphs', 'graph', 'databases', 'web', 'database']" }, { "code": null, "e": 9533, "s": 9306, "text": "In this tutorial, we have seen different approaches to extract keywords from a given text. All of them don’t require any training. This list is far from being complete! Check the most recent review to have a complete overview!" }, { "code": null, "e": 9918, "s": 9533, "text": "We have tested both simple approaches like TF-IDF and advanced models like BERT. Unfortunately, there isn’t a model that performs well on every document. It depends on the type of document, the context, and the corpus used for the model pretraining. A more complete preprocessing with a combination of different keyword extraction approaches should definitely improve the performance!" }, { "code": null, "e": 9980, "s": 9918, "text": "https://scholar.google.it/scholar?q=keyword+extraction+review" }, { "code": null, "e": 10002, "s": 9980, "text": "http://www.tfidf.com/" }, { "code": null, "e": 10048, "s": 10002, "text": "https://www.aclweb.org/anthology/W04-3252.pdf" }, { "code": null, "e": 10091, "s": 10048, "text": "https://www.aclweb.org/anthology/I13-1062/" }, { "code": null, "e": 10116, "s": 10091, "text": "http://yake.inesctec.pt/" }, { "code": null, "e": 10189, "s": 10116, "text": "https://towardsdatascience.com/keyword-extraction-with-bert-724efca412ea" } ]
Text Generation Using N-Gram Model | by Oleg Borisov | Towards Data Science
My interest in Artificial Intelligence and in particular in Natural Language Processing (NLP) has sparked exactly when I have learned that machines are capable of generating the new text by using some simple statistical and probabilistic techniques. In this article I wanted to share this extremely simple and intuitive method of creating Text Generation Model. As we all know, language has a sequential nature, hence the order in which words appear in the text matters a lot. This feature allows us to understand the context of a sentence even if there are some words missing (or in case if stumble across a word which meaning is unknown). Consider example below: “Mary was scared because of the terrifying noise emitted by Chupacabra.” Without some previous context we have no idea what “Chupacabra” indeed is, but we probably can say that we would be not happy to encounter this creature in real life. This dependency of words inside the sentence can give us some clues about the nature of the missing word and sometimes we do not even need to know the whole context. In the example above, by looking only at “noise emitted by” we on the intuitive level can say that the following word should be a noun and not some other part of speech. This brings us up to the idea behind the N-Grams, where the formal definition is “a contiguous sequence of n items from a given sample of text”. The main idea is that given any text, we can split it into a list of unigrams (1-gram), bigrams (2-gram), trigrams (3-gram) etc. For example: Text: “I went running” Unigrams: [(I), (went), (running)] Bigrams: [(I, went), (went, running)] As you can notice word “went” appeared in 2 bigrams: (I, went) and (went, running). The other, more visual, way to look at it The main idea of generating text using N-Grams is to assume that the last word (x^{n} ) of the n-gram can be inferred from the other words that appear in the same n-gram (x^{n-1}, x^{n-2}, ... x1), which I call context. So the main simplification of the model is that we do not need to keep track of the whole sentence in order to predict the next word, we just need to look back for n-1 tokens. Meaning that the main assumption is: Great! And the most beautiful thing is that in order to calculate the probability above we just need to apply simple conditional probability rule For example: using trigram model (n=3) Text: “Mary was scared because of ___” Since, we use a trigram model we drop the beginning of the sentence: “Mary was scared”, and we would need to only calculate only the possible continuation from “because of”. Assume from the dataset that we know that there are following possible continuations: “me”, “noise”. Therefore, we would need to compute: P(noise | because of) and P(me| because of) After the probabilities are computed, there exist multiple ways of selecting the final word given all candidates. One way would be to produce the word which had the highest conditional probability (this option might be not the best one as it tends to get stuck in a loop if n is small). The other (and better) option would be to output the word ‘semi-randomly’ with regards to its conditional probability. So that the words that have a higher probability will have higher chances of being produced, while still other words with lower probability have a chance of being generated. Enough of a theory, let’s get to the implementation part. Source code is available on my github. First of all, we need some source text, from which we are going to train our Language Model. Ideally we would like to have some large book (or even multiple books), because we not only want to have large vocabulary but also we are interested to see as many different permutations or words as possible. Here I will use Frankenstein book written by Mary Shelley, but you can use any other book of your choice (for convenience you can use Project Gutenberg link). I want to keep the code as simple as possible, so that there is no need to install any external package. In addition to that I have also made some code optimization in order to reduce computation time and to make efficient inference procedure. Before we implement the N-gram language model let’s implement some helper functions: one to perform tokenization (splitting words of a sentence), another one to merge consequent tokens into the N-Grams. For tokenization it would be better to use some external library like NLTK or spaCy, but for our purposes custom tokenizer would be sufficient. Now let’s take a look at the get_ngrams function. As we mentioned before, to predict token at position n, we would have to look at all previous n-1 tokens of our N-gram. So the way we are going to represent our N-gram is a tuple of type ((context), current_word): The problem arises when we need to generate one of the first token(-s) of a sentence, as there is no preceding context available. To address this issue, we can introduce some leading tags like <START> which will be making sure that at any point of inference we always working with correct N-Grams. For example if we want to get all 3-grams from the text “I bought a red car”: [((‘<START>’, ‘<START>’), ‘I’), ((‘<START>’, ‘I’), ‘bought’), ((‘I’, ‘bought’), ‘a’), ((‘bought’, ‘a’), ‘red’), ((‘a’, ‘red’), ‘car’), Great, now let’s create our N-gram model: In the initialization we must specify, what is our n value for n-grams, in addition to that I also create context and ngram_counter dictionaries. Context dictionary as keys it has context, and as values stores the list of possible continuations given a context. For example: >> self.context>> {(red, car): [names, wallpapers, game, paint ...], (weather, in): [London, Bern, Paris, ...]} So in a way this context dictionary immediately shows us what candidate words we can use in order to generate relatively random text that is going to make some sense (still better than blindly producing bunch of words). Ngram_counter dictionary just counts how many times we have seen a particular N-gram in our training set before. To update our Language Model we will supply each individual sentence from the book, and will update the dictionaries with information corresponding to our N-grams. As was mentioned in theoretical part of this article, to compute probability of the next word given the context, we just need to apply simple conditional probability rule. Now let’s move to the text generation part. Before we can start text generation, we first of all must provide our system with some context which in our case will be starting token <START> repeated n–1 times. After that we can generate our first random_token by using our “semi-random” approach. Then we repeat our procedure until a certain number of tokens has been generated (specified by token_count variable). Note: when we reached the full stop . in generation, the system would be not aware of how to proceed, because of the way how we were updating our Language Model. Therefore, we would need to reinitialize the contextual queue context_queue every time our model generates a full stop. Great! Everything is set up, so let’s run our model and see what sentences we can produce! Some of the results are presented below: n=1, “care I of . its destined , in , from . . for the Felix an not which measure excited” n=2, “I compassionated him , how heavily ; but I had arrived , but they averred , my unhallowed damps and” n=3, “I continued their single offspring . At length I gathered from a man who , born in freedom , spurned” n=4, “I continued walking in this manner , during which I enjoyed the feeling of happiness . Still thou canst listen” n=5, “I continued walking in this manner for some time , and I feared the effects of the dæmon’s disappointment .” It is quite cool to see how the generated text improves as we increase n, however this is not surprising, because with the increase the size of the N-gram model, we start copying the original text from the training set, book in our case. Indeed, for n>5 generated text remains the same as “I continued walking in this manner for some time , endeavouring by bodily exercise to ease the load that weighed”. What I still find quite impressing is that our over-simplified Language Model which uses N-grams and simple probability rules is still capable of producing some new text that can make some sense for a reader. Of course such naive model is not going to be able to write some human-like articles or perform like GPT-3 as it has many drawbacks. Such system can get stuck in a loop, or is not capable of keeping track of longterm contextual relationships. But it is a nice first possible introduction to Natural Language Processing and to Language Modelling as it emphasise on the importance of the context in a sentence. Stay tuned for more articles about Artificial Intelligence and Natural Language Processing.
[ { "code": null, "e": 534, "s": 172, "text": "My interest in Artificial Intelligence and in particular in Natural Language Processing (NLP) has sparked exactly when I have learned that machines are capable of generating the new text by using some simple statistical and probabilistic techniques. In this article I wanted to share this extremely simple and intuitive method of creating Text Generation Model." }, { "code": null, "e": 837, "s": 534, "text": "As we all know, language has a sequential nature, hence the order in which words appear in the text matters a lot. This feature allows us to understand the context of a sentence even if there are some words missing (or in case if stumble across a word which meaning is unknown). Consider example below:" }, { "code": null, "e": 910, "s": 837, "text": "“Mary was scared because of the terrifying noise emitted by Chupacabra.”" }, { "code": null, "e": 1077, "s": 910, "text": "Without some previous context we have no idea what “Chupacabra” indeed is, but we probably can say that we would be not happy to encounter this creature in real life." }, { "code": null, "e": 1413, "s": 1077, "text": "This dependency of words inside the sentence can give us some clues about the nature of the missing word and sometimes we do not even need to know the whole context. In the example above, by looking only at “noise emitted by” we on the intuitive level can say that the following word should be a noun and not some other part of speech." }, { "code": null, "e": 1687, "s": 1413, "text": "This brings us up to the idea behind the N-Grams, where the formal definition is “a contiguous sequence of n items from a given sample of text”. The main idea is that given any text, we can split it into a list of unigrams (1-gram), bigrams (2-gram), trigrams (3-gram) etc." }, { "code": null, "e": 1700, "s": 1687, "text": "For example:" }, { "code": null, "e": 1723, "s": 1700, "text": "Text: “I went running”" }, { "code": null, "e": 1758, "s": 1723, "text": "Unigrams: [(I), (went), (running)]" }, { "code": null, "e": 1796, "s": 1758, "text": "Bigrams: [(I, went), (went, running)]" }, { "code": null, "e": 1880, "s": 1796, "text": "As you can notice word “went” appeared in 2 bigrams: (I, went) and (went, running)." }, { "code": null, "e": 1922, "s": 1880, "text": "The other, more visual, way to look at it" }, { "code": null, "e": 2142, "s": 1922, "text": "The main idea of generating text using N-Grams is to assume that the last word (x^{n} ) of the n-gram can be inferred from the other words that appear in the same n-gram (x^{n-1}, x^{n-2}, ... x1), which I call context." }, { "code": null, "e": 2355, "s": 2142, "text": "So the main simplification of the model is that we do not need to keep track of the whole sentence in order to predict the next word, we just need to look back for n-1 tokens. Meaning that the main assumption is:" }, { "code": null, "e": 2501, "s": 2355, "text": "Great! And the most beautiful thing is that in order to calculate the probability above we just need to apply simple conditional probability rule" }, { "code": null, "e": 2540, "s": 2501, "text": "For example: using trigram model (n=3)" }, { "code": null, "e": 2579, "s": 2540, "text": "Text: “Mary was scared because of ___”" }, { "code": null, "e": 2891, "s": 2579, "text": "Since, we use a trigram model we drop the beginning of the sentence: “Mary was scared”, and we would need to only calculate only the possible continuation from “because of”. Assume from the dataset that we know that there are following possible continuations: “me”, “noise”. Therefore, we would need to compute:" }, { "code": null, "e": 2935, "s": 2891, "text": "P(noise | because of) and P(me| because of)" }, { "code": null, "e": 3222, "s": 2935, "text": "After the probabilities are computed, there exist multiple ways of selecting the final word given all candidates. One way would be to produce the word which had the highest conditional probability (this option might be not the best one as it tends to get stuck in a loop if n is small)." }, { "code": null, "e": 3515, "s": 3222, "text": "The other (and better) option would be to output the word ‘semi-randomly’ with regards to its conditional probability. So that the words that have a higher probability will have higher chances of being produced, while still other words with lower probability have a chance of being generated." }, { "code": null, "e": 3612, "s": 3515, "text": "Enough of a theory, let’s get to the implementation part. Source code is available on my github." }, { "code": null, "e": 4073, "s": 3612, "text": "First of all, we need some source text, from which we are going to train our Language Model. Ideally we would like to have some large book (or even multiple books), because we not only want to have large vocabulary but also we are interested to see as many different permutations or words as possible. Here I will use Frankenstein book written by Mary Shelley, but you can use any other book of your choice (for convenience you can use Project Gutenberg link)." }, { "code": null, "e": 4317, "s": 4073, "text": "I want to keep the code as simple as possible, so that there is no need to install any external package. In addition to that I have also made some code optimization in order to reduce computation time and to make efficient inference procedure." }, { "code": null, "e": 4520, "s": 4317, "text": "Before we implement the N-gram language model let’s implement some helper functions: one to perform tokenization (splitting words of a sentence), another one to merge consequent tokens into the N-Grams." }, { "code": null, "e": 4664, "s": 4520, "text": "For tokenization it would be better to use some external library like NLTK or spaCy, but for our purposes custom tokenizer would be sufficient." }, { "code": null, "e": 4714, "s": 4664, "text": "Now let’s take a look at the get_ngrams function." }, { "code": null, "e": 4928, "s": 4714, "text": "As we mentioned before, to predict token at position n, we would have to look at all previous n-1 tokens of our N-gram. So the way we are going to represent our N-gram is a tuple of type ((context), current_word):" }, { "code": null, "e": 5304, "s": 4928, "text": "The problem arises when we need to generate one of the first token(-s) of a sentence, as there is no preceding context available. To address this issue, we can introduce some leading tags like <START> which will be making sure that at any point of inference we always working with correct N-Grams. For example if we want to get all 3-grams from the text “I bought a red car”:" }, { "code": null, "e": 5336, "s": 5304, "text": "[((‘<START>’, ‘<START>’), ‘I’)," }, { "code": null, "e": 5366, "s": 5336, "text": "((‘<START>’, ‘I’), ‘bought’)," }, { "code": null, "e": 5390, "s": 5366, "text": "((‘I’, ‘bought’), ‘a’)," }, { "code": null, "e": 5416, "s": 5390, "text": "((‘bought’, ‘a’), ‘red’)," }, { "code": null, "e": 5439, "s": 5416, "text": "((‘a’, ‘red’), ‘car’)," }, { "code": null, "e": 5481, "s": 5439, "text": "Great, now let’s create our N-gram model:" }, { "code": null, "e": 5756, "s": 5481, "text": "In the initialization we must specify, what is our n value for n-grams, in addition to that I also create context and ngram_counter dictionaries. Context dictionary as keys it has context, and as values stores the list of possible continuations given a context. For example:" }, { "code": null, "e": 5871, "s": 5756, "text": ">> self.context>> {(red, car): [names, wallpapers, game, paint ...], (weather, in): [London, Bern, Paris, ...]}" }, { "code": null, "e": 6091, "s": 5871, "text": "So in a way this context dictionary immediately shows us what candidate words we can use in order to generate relatively random text that is going to make some sense (still better than blindly producing bunch of words)." }, { "code": null, "e": 6204, "s": 6091, "text": "Ngram_counter dictionary just counts how many times we have seen a particular N-gram in our training set before." }, { "code": null, "e": 6368, "s": 6204, "text": "To update our Language Model we will supply each individual sentence from the book, and will update the dictionaries with information corresponding to our N-grams." }, { "code": null, "e": 6540, "s": 6368, "text": "As was mentioned in theoretical part of this article, to compute probability of the next word given the context, we just need to apply simple conditional probability rule." }, { "code": null, "e": 6584, "s": 6540, "text": "Now let’s move to the text generation part." }, { "code": null, "e": 6748, "s": 6584, "text": "Before we can start text generation, we first of all must provide our system with some context which in our case will be starting token <START> repeated n–1 times." }, { "code": null, "e": 6953, "s": 6748, "text": "After that we can generate our first random_token by using our “semi-random” approach. Then we repeat our procedure until a certain number of tokens has been generated (specified by token_count variable)." }, { "code": null, "e": 7235, "s": 6953, "text": "Note: when we reached the full stop . in generation, the system would be not aware of how to proceed, because of the way how we were updating our Language Model. Therefore, we would need to reinitialize the contextual queue context_queue every time our model generates a full stop." }, { "code": null, "e": 7326, "s": 7235, "text": "Great! Everything is set up, so let’s run our model and see what sentences we can produce!" }, { "code": null, "e": 7367, "s": 7326, "text": "Some of the results are presented below:" }, { "code": null, "e": 7458, "s": 7367, "text": "n=1, “care I of . its destined , in , from . . for the Felix an not which measure excited”" }, { "code": null, "e": 7565, "s": 7458, "text": "n=2, “I compassionated him , how heavily ; but I had arrived , but they averred , my unhallowed damps and”" }, { "code": null, "e": 7673, "s": 7565, "text": "n=3, “I continued their single offspring . At length I gathered from a man who , born in freedom , spurned”" }, { "code": null, "e": 7791, "s": 7673, "text": "n=4, “I continued walking in this manner , during which I enjoyed the feeling of happiness . Still thou canst listen”" }, { "code": null, "e": 7906, "s": 7791, "text": "n=5, “I continued walking in this manner for some time , and I feared the effects of the dæmon’s disappointment .”" }, { "code": null, "e": 8144, "s": 7906, "text": "It is quite cool to see how the generated text improves as we increase n, however this is not surprising, because with the increase the size of the N-gram model, we start copying the original text from the training set, book in our case." }, { "code": null, "e": 8311, "s": 8144, "text": "Indeed, for n>5 generated text remains the same as “I continued walking in this manner for some time , endeavouring by bodily exercise to ease the load that weighed”." }, { "code": null, "e": 8520, "s": 8311, "text": "What I still find quite impressing is that our over-simplified Language Model which uses N-grams and simple probability rules is still capable of producing some new text that can make some sense for a reader." }, { "code": null, "e": 8929, "s": 8520, "text": "Of course such naive model is not going to be able to write some human-like articles or perform like GPT-3 as it has many drawbacks. Such system can get stuck in a loop, or is not capable of keeping track of longterm contextual relationships. But it is a nice first possible introduction to Natural Language Processing and to Language Modelling as it emphasise on the importance of the context in a sentence." } ]
Find All Duplicate Characters from a String using Python
One String is given. Our task is to find those characters whose frequency is more than one in the given string. As an example, we can see that the string “Hello World. Let’s learn Python” so the algorithm will find those letters which are occurring multiple times. In this case, the output will look like this - e : 3 l : 4 o , 3) <space> : 4 r : 2 t : 2 n : 2 To implement this problem we are using Python Collections. From the collection, we can get the Counter() method. The Counter() method is used to count the hashtable objects. In this case, it separates the characters from the text and makes each character as a key of the dictionary, and the character count is the value of those keys. Step 1: Find the key-value pair from the string, where each character is key and character counts are the values. Step 2: For each key, check whether the value is greater than one or not. Step 3: If it is greater than one then, it is duplicate, so mark it. Otherwise, ignore the character from collections import Counter defcalc_char_freq(string): freq_count = Counter(string) # get dictionary with letters as key and frequency as value for key in freq_count.keys(): if freq_count.get(key) > 1: # for all different keys, list the letters and frequencies print("(" + key + ", " + str(freq_count.get(key)) + ")") myStr = 'Hello World. Let’s learn Python' calc_char_freq(myStr) (e, 3) (l, 4) (o, 3) ( , 4) (r, 2) (t, 2) (n, 2)
[ { "code": null, "e": 1174, "s": 1062, "text": "One String is given. Our task is to find those characters whose frequency is more than one in the given string." }, { "code": null, "e": 1374, "s": 1174, "text": "As an example, we can see that the string “Hello World. Let’s learn Python” so the algorithm will find those letters which are occurring multiple times. In this case, the output will look like this -" }, { "code": null, "e": 1425, "s": 1374, "text": "e : 3\nl : 4\no , 3)\n<space> : 4 \nr : 2\nt : 2\nn : 2\n" }, { "code": null, "e": 1760, "s": 1425, "text": "To implement this problem we are using Python Collections. From the collection, we can get the Counter() method. The Counter() method is used to count the hashtable objects. In this case, it separates the characters from the text and makes each character as a key of the dictionary, and the character count is the value of those keys." }, { "code": null, "e": 2052, "s": 1760, "text": "Step 1: Find the key-value pair from the string, where each character is key and character counts are the values.\nStep 2: For each key, check whether the value is greater than one or not. \nStep 3: If it is greater than one then, it is duplicate, so mark it. Otherwise, ignore the character \n" }, { "code": null, "e": 2475, "s": 2052, "text": "from collections import Counter\ndefcalc_char_freq(string):\n freq_count = Counter(string) # get dictionary with letters as key and frequency as value\n for key in freq_count.keys():\n if freq_count.get(key) > 1: # for all different keys, list the letters and frequencies\n print(\"(\" + key + \", \" + str(freq_count.get(key)) + \")\")\n myStr = 'Hello World. Let’s learn Python' \n calc_char_freq(myStr)" }, { "code": null, "e": 2525, "s": 2475, "text": "(e, 3)\n(l, 4)\n(o, 3)\n( , 4)\n(r, 2)\n(t, 2)\n(n, 2)\n" } ]
Can the main method in Java return a value?
The public static void main(String args[]) is the entry point of a Java program Whenever you execute a program the JVM searches for the main method and starts executing the contents of it. If such method is not found the program gets executed successfully, but when you execute the program it generates an error. As the matter of fact you should declare the main method with public static as modifiers, void return type and String arguments if you change anything, JVM doesn’t considers as the entry point method and prompts an error at run time. Therefore, you cannot change the return type of main method from void, at the same time you cannot return any value from a method with void type. public class Sample{ public static void main(String args[]){ System.out.println("Contents of the main method"); return 20; } } Sample.java:4: error: incompatible types: unexpected return value return 20; ^ 1 error Therefore, you cannot return any value from main.
[ { "code": null, "e": 1375, "s": 1062, "text": "The public static void main(String args[]) is the entry point of a Java program Whenever you execute a program the JVM searches for the main method and starts executing the contents of it. If such method is not found the program gets executed successfully, but when you execute the program it generates an error." }, { "code": null, "e": 1609, "s": 1375, "text": "As the matter of fact you should declare the main method with public static as modifiers, void return type and String arguments if you change anything, JVM doesn’t considers as the entry point method and prompts an error at run time." }, { "code": null, "e": 1755, "s": 1609, "text": "Therefore, you cannot change the return type of main method from void, at the same time you cannot return any value from a method with void type." }, { "code": null, "e": 1900, "s": 1755, "text": "public class Sample{\n public static void main(String args[]){\n System.out.println(\"Contents of the main method\");\n return 20;\n }\n}" }, { "code": null, "e": 2000, "s": 1900, "text": "Sample.java:4: error: incompatible types: unexpected return value\n return 20;\n ^\n1 error" }, { "code": null, "e": 2050, "s": 2000, "text": "Therefore, you cannot return any value from main." } ]
Find Nth number in a sequence which is not a multiple of a given number - GeeksforGeeks
16 Apr, 2021 Given four integers A, N, L and R, the task is to find the N th number in a sequence of consecutive integers from L to R which is not a multiple of A. It is given that the sequence contain at least N numbers which are not divisible by A and the integer A is always greater than 1. Examples: Input: A = 2, N = 3, L = 1, R = 10 Output: 5 Explanation: The sequence is 1, 2, 3, 4, 5, 6, 7, 8, 9 and 10. Here 5 is the third number which is not a multiple of 2 in the sequence. Input: A = 3, N = 6, L = 4, R = 20 Output: 11 Explanation : 11 is the 6th number which is not a multiple of 3 in the sequence. Naive Approach: The naive approach is to iterate over the range [L, R] in a loop to find the Nth number. The steps are: Initialize the count of non-multiple number and current number to 0.Iterate over the range [L, R] until the count of the non-multiple number is not equal to N.Increment the count of the non-multiple number by 1, If the current number is not divisible by A. Initialize the count of non-multiple number and current number to 0. Iterate over the range [L, R] until the count of the non-multiple number is not equal to N. Increment the count of the non-multiple number by 1, If the current number is not divisible by A. 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 Nth number not a// multiple of A in the range [L, R]void count_no (int A, int N, int L, int R){ // To store the count int count = 0; int i = 0; // To check all the nos in range for(i = L; i < R + 1; i++) { if (i % A != 0) count += 1; if (count == N) break; } cout << i;} // Driver codeint main(){ // Given values of A, N, L, R int A = 3, N = 6, L = 4, R = 20; // Function Call count_no (A, N, L, R); return 0;} // This code is contributed by mohit kumar 29 // Java program for the above approachimport java.util.*;import java.io.*; class GFG{ // Function to find Nth number not a// multiple of A in the range [L, R]static void count_no (int A, int N, int L, int R){ // To store the count int count = 0; int i = 0; // To check all the nos in range for(i = L; i < R + 1; i++) { if (i % A != 0) count += 1; if (count == N) break; } System.out.println(i);} // Driver codepublic static void main(String[] args){ // Given values of A, N, L, R int A = 3, N = 6, L = 4, R = 20; // Function call count_no (A, N, L, R);}} // This code is contributed by sanjoy_62 # Python3 program for the above approach # Function to find Nth number not a# multiple of A in the range [L, R]def count_no (A, N, L, R): # To store the count count = 0 # To check all the nos in range for i in range ( L, R + 1 ): if ( i % A != 0 ): count += 1 if ( count == N ): break print ( i ) # Given values of A, N, L, RA, N, L, R = 3, 6, 4, 20 # Function Callcount_no (A, N, L, R) // C# program for the above approachusing System; class GFG{ // Function to find Nth number not a// multiple of A in the range [L, R]static void count_no (int A, int N, int L, int R){ // To store the count int count = 0; int i = 0; // To check all the nos in range for(i = L; i < R + 1; i++) { if (i % A != 0) count += 1; if (count == N) break; } Console.WriteLine(i);} // Driver codepublic static void Main(){ // Given values of A, N, L, R int A = 3, N = 6, L = 4, R = 20; // Function call count_no (A, N, L, R);}} // This code is contributed by sanjoy_62 <script> // Javascript Program to implement// the above approach // Function to find Nth number not a// multiple of A in the range [L, R]function count_no (A, N, L, R){ // To store the count let count = 0; let i = 0; // To check all the nos in range for(i = L; i < R + 1; i++) { if (i % A != 0) count += 1; if (count == N) break; } document.write(i);} // Driver Code // Given values of A, N, L, R let A = 3, N = 6, L = 4, R = 20; // Function call count_no (A, N, L, R); // This code is contributed by chinmoy1997pal.</script> 11 Time Complexity: O(R – L) Auxiliary Space: O(1) Efficient Approach: The key observation is that there are A – 1 numbers that are not divisible by A in the range [1, A – 1]. Similarly, there are A – 1 numbers not divisible by A in range [A + 1, 2 * A – 1], [2 * A + 1, 3 * A – 1] and so on. With the help of this observation, the Nth number which is not divisible by A will be: To find the value in the range [ L, R ], we need to shift the origin from ‘0’ to ‘L – 1’, thus we can say that the Nth number which is not divisible by A in the range will be : However there is an edge case, when the value of ( L – 1 ) + N + floor( ( N – 1 ) / ( A – 1 ) ) itself turns out to be multiple of a ‘A’, in that case Nth number will be : 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 Nth number// not a multiple of A in range [L, R]void countNo(int A, int N, int L, int R){ // Calculate the Nth no int ans = L - 1 + N + floor((N - 1) / (A - 1)); // Check for the edge case if (ans % A == 0) { ans = ans + 1; } cout << ans << endl;} // Driver Codeint main(){ // Input parameters int A = 5, N = 10, L = 4, R = 20; // Function Call countNo(A, N, L, R); return 0;} // This code is contributed by avanitrachhadiya2155 // Java program for the above approachimport java.io.*; class GFG{ // Function to find Nth number // not a multiple of A in range [L, R] static void countNo(int A, int N, int L, int R) { // Calculate the Nth no int ans = L - 1 + N + (int)Math.floor((N - 1) / (A - 1)); // Check for the edge case if (ans % A == 0) { ans = ans + 1; } System.out.println(ans); } // Driver Code public static void main (String[] args) { // Input parameters int A = 5, N = 10, L = 4, R = 20; // Function Call countNo(A, N, L, R); }} // This code is contributed by rag2127 # Python3 program for the above approachimport math # Function to find Nth number# not a multiple of A in range [L, R]def countNo (A, N, L, R): # Calculate the Nth no ans = L - 1 + N \ + math.floor( ( N - 1 ) / ( A - 1 ) ) # Check for the edge case if ans % A == 0: ans = ans + 1; print(ans) # Input parametersA, N, L, R = 5, 10, 4, 20 # Function CallcountNo(A, N, L, R) // C# program for the above approachusing System;class GFG { // Function to find Nth number // not a multiple of A in range [L, R] static void countNo(int A, int N, int L, int R) { // Calculate the Nth no int ans = L - 1 + N + ((N - 1) / (A - 1)); // Check for the edge case if (ans % A == 0) { ans = ans + 1; } Console.WriteLine(ans); } // Driver code static void Main() { // Input parameters int A = 5, N = 10, L = 4, R = 20; // Function Call countNo(A, N, L, R); }} // This code is contributed by divyesh072019. <script> // Javascript program for// the above approach // Function to find Nth number// not a multiple of A in range [L, R]function countNo(A, N, L, R){ // Calculate the Nth no var ans = L - 1 + N + Math.floor((N - 1) / (A - 1)); // Check for the edge case if (ans % A == 0) { ans = ans + 1; } document.write(ans); } // Driver code // Input parametersvar A = 5, N = 10, L = 4, R = 20; // Function CallcountNo(A, N, L, R); // This code is contributed by Khushboogoyal499 </script> 16 Time Complexity: O(1) Auxiliary Space: O(1) mohit kumar 29 sanjoy_62 nidhi_biet avanitrachhadiya2155 khushboogoyal499 rag2127 divyesh072019 chinmoy1997pal Analysis Competitive Programming Data Structures Mathematical Pattern Searching Data Structures Mathematical Pattern Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete Difference between Deterministic and Non-deterministic Algorithms Proof that Dominant Set of a Graph is NP-Complete 3-coloring is NP Complete Set partition is NP complete Practice for cracking any coding interview Arrow operator -> in C/C++ with Examples Competitive Programming - A Complete Guide Prefix Sum Array - Implementation and Applications in Competitive Programming Modulo 10^9+7 (1000000007)
[ { "code": null, "e": 24655, "s": 24627, "text": "\n16 Apr, 2021" }, { "code": null, "e": 24936, "s": 24655, "text": "Given four integers A, N, L and R, the task is to find the N th number in a sequence of consecutive integers from L to R which is not a multiple of A. It is given that the sequence contain at least N numbers which are not divisible by A and the integer A is always greater than 1." }, { "code": null, "e": 24948, "s": 24936, "text": "Examples: " }, { "code": null, "e": 25129, "s": 24948, "text": "Input: A = 2, N = 3, L = 1, R = 10 Output: 5 Explanation: The sequence is 1, 2, 3, 4, 5, 6, 7, 8, 9 and 10. Here 5 is the third number which is not a multiple of 2 in the sequence." }, { "code": null, "e": 25257, "s": 25129, "text": "Input: A = 3, N = 6, L = 4, R = 20 Output: 11 Explanation : 11 is the 6th number which is not a multiple of 3 in the sequence. " }, { "code": null, "e": 25379, "s": 25257, "text": "Naive Approach: The naive approach is to iterate over the range [L, R] in a loop to find the Nth number. The steps are: " }, { "code": null, "e": 25636, "s": 25379, "text": "Initialize the count of non-multiple number and current number to 0.Iterate over the range [L, R] until the count of the non-multiple number is not equal to N.Increment the count of the non-multiple number by 1, If the current number is not divisible by A." }, { "code": null, "e": 25705, "s": 25636, "text": "Initialize the count of non-multiple number and current number to 0." }, { "code": null, "e": 25797, "s": 25705, "text": "Iterate over the range [L, R] until the count of the non-multiple number is not equal to N." }, { "code": null, "e": 25895, "s": 25797, "text": "Increment the count of the non-multiple number by 1, If the current number is not divisible by A." }, { "code": null, "e": 25948, "s": 25895, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 25952, "s": 25948, "text": "C++" }, { "code": null, "e": 25957, "s": 25952, "text": "Java" }, { "code": null, "e": 25965, "s": 25957, "text": "Python3" }, { "code": null, "e": 25968, "s": 25965, "text": "C#" }, { "code": null, "e": 25979, "s": 25968, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find Nth number not a// multiple of A in the range [L, R]void count_no (int A, int N, int L, int R){ // To store the count int count = 0; int i = 0; // To check all the nos in range for(i = L; i < R + 1; i++) { if (i % A != 0) count += 1; if (count == N) break; } cout << i;} // Driver codeint main(){ // Given values of A, N, L, R int A = 3, N = 6, L = 4, R = 20; // Function Call count_no (A, N, L, R); return 0;} // This code is contributed by mohit kumar 29", "e": 26622, "s": 25979, "text": null }, { "code": "// Java program for the above approachimport java.util.*;import java.io.*; class GFG{ // Function to find Nth number not a// multiple of A in the range [L, R]static void count_no (int A, int N, int L, int R){ // To store the count int count = 0; int i = 0; // To check all the nos in range for(i = L; i < R + 1; i++) { if (i % A != 0) count += 1; if (count == N) break; } System.out.println(i);} // Driver codepublic static void main(String[] args){ // Given values of A, N, L, R int A = 3, N = 6, L = 4, R = 20; // Function call count_no (A, N, L, R);}} // This code is contributed by sanjoy_62", "e": 27328, "s": 26622, "text": null }, { "code": "# Python3 program for the above approach # Function to find Nth number not a# multiple of A in the range [L, R]def count_no (A, N, L, R): # To store the count count = 0 # To check all the nos in range for i in range ( L, R + 1 ): if ( i % A != 0 ): count += 1 if ( count == N ): break print ( i ) # Given values of A, N, L, RA, N, L, R = 3, 6, 4, 20 # Function Callcount_no (A, N, L, R)", "e": 27773, "s": 27328, "text": null }, { "code": "// C# program for the above approachusing System; class GFG{ // Function to find Nth number not a// multiple of A in the range [L, R]static void count_no (int A, int N, int L, int R){ // To store the count int count = 0; int i = 0; // To check all the nos in range for(i = L; i < R + 1; i++) { if (i % A != 0) count += 1; if (count == N) break; } Console.WriteLine(i);} // Driver codepublic static void Main(){ // Given values of A, N, L, R int A = 3, N = 6, L = 4, R = 20; // Function call count_no (A, N, L, R);}} // This code is contributed by sanjoy_62", "e": 28444, "s": 27773, "text": null }, { "code": "<script> // Javascript Program to implement// the above approach // Function to find Nth number not a// multiple of A in the range [L, R]function count_no (A, N, L, R){ // To store the count let count = 0; let i = 0; // To check all the nos in range for(i = L; i < R + 1; i++) { if (i % A != 0) count += 1; if (count == N) break; } document.write(i);} // Driver Code // Given values of A, N, L, R let A = 3, N = 6, L = 4, R = 20; // Function call count_no (A, N, L, R); // This code is contributed by chinmoy1997pal.</script>", "e": 29062, "s": 28444, "text": null }, { "code": null, "e": 29065, "s": 29062, "text": "11" }, { "code": null, "e": 29116, "s": 29067, "text": "Time Complexity: O(R – L) Auxiliary Space: O(1) " }, { "code": null, "e": 29446, "s": 29116, "text": "Efficient Approach: The key observation is that there are A – 1 numbers that are not divisible by A in the range [1, A – 1]. Similarly, there are A – 1 numbers not divisible by A in range [A + 1, 2 * A – 1], [2 * A + 1, 3 * A – 1] and so on. With the help of this observation, the Nth number which is not divisible by A will be: " }, { "code": null, "e": 29624, "s": 29446, "text": "To find the value in the range [ L, R ], we need to shift the origin from ‘0’ to ‘L – 1’, thus we can say that the Nth number which is not divisible by A in the range will be : " }, { "code": null, "e": 29797, "s": 29624, "text": "However there is an edge case, when the value of ( L – 1 ) + N + floor( ( N – 1 ) / ( A – 1 ) ) itself turns out to be multiple of a ‘A’, in that case Nth number will be : " }, { "code": null, "e": 29849, "s": 29797, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 29853, "s": 29849, "text": "C++" }, { "code": null, "e": 29858, "s": 29853, "text": "Java" }, { "code": null, "e": 29866, "s": 29858, "text": "Python3" }, { "code": null, "e": 29869, "s": 29866, "text": "C#" }, { "code": null, "e": 29880, "s": 29869, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find Nth number// not a multiple of A in range [L, R]void countNo(int A, int N, int L, int R){ // Calculate the Nth no int ans = L - 1 + N + floor((N - 1) / (A - 1)); // Check for the edge case if (ans % A == 0) { ans = ans + 1; } cout << ans << endl;} // Driver Codeint main(){ // Input parameters int A = 5, N = 10, L = 4, R = 20; // Function Call countNo(A, N, L, R); return 0;} // This code is contributed by avanitrachhadiya2155", "e": 30510, "s": 29880, "text": null }, { "code": "// Java program for the above approachimport java.io.*; class GFG{ // Function to find Nth number // not a multiple of A in range [L, R] static void countNo(int A, int N, int L, int R) { // Calculate the Nth no int ans = L - 1 + N + (int)Math.floor((N - 1) / (A - 1)); // Check for the edge case if (ans % A == 0) { ans = ans + 1; } System.out.println(ans); } // Driver Code public static void main (String[] args) { // Input parameters int A = 5, N = 10, L = 4, R = 20; // Function Call countNo(A, N, L, R); }} // This code is contributed by rag2127", "e": 31121, "s": 30510, "text": null }, { "code": "# Python3 program for the above approachimport math # Function to find Nth number# not a multiple of A in range [L, R]def countNo (A, N, L, R): # Calculate the Nth no ans = L - 1 + N \\ + math.floor( ( N - 1 ) / ( A - 1 ) ) # Check for the edge case if ans % A == 0: ans = ans + 1; print(ans) # Input parametersA, N, L, R = 5, 10, 4, 20 # Function CallcountNo(A, N, L, R)", "e": 31529, "s": 31121, "text": null }, { "code": "// C# program for the above approachusing System;class GFG { // Function to find Nth number // not a multiple of A in range [L, R] static void countNo(int A, int N, int L, int R) { // Calculate the Nth no int ans = L - 1 + N + ((N - 1) / (A - 1)); // Check for the edge case if (ans % A == 0) { ans = ans + 1; } Console.WriteLine(ans); } // Driver code static void Main() { // Input parameters int A = 5, N = 10, L = 4, R = 20; // Function Call countNo(A, N, L, R); }} // This code is contributed by divyesh072019.", "e": 32097, "s": 31529, "text": null }, { "code": "<script> // Javascript program for// the above approach // Function to find Nth number// not a multiple of A in range [L, R]function countNo(A, N, L, R){ // Calculate the Nth no var ans = L - 1 + N + Math.floor((N - 1) / (A - 1)); // Check for the edge case if (ans % A == 0) { ans = ans + 1; } document.write(ans); } // Driver code // Input parametersvar A = 5, N = 10, L = 4, R = 20; // Function CallcountNo(A, N, L, R); // This code is contributed by Khushboogoyal499 </script>", "e": 32623, "s": 32097, "text": null }, { "code": null, "e": 32626, "s": 32623, "text": "16" }, { "code": null, "e": 32673, "s": 32628, "text": "Time Complexity: O(1) Auxiliary Space: O(1) " }, { "code": null, "e": 32688, "s": 32673, "text": "mohit kumar 29" }, { "code": null, "e": 32698, "s": 32688, "text": "sanjoy_62" }, { "code": null, "e": 32709, "s": 32698, "text": "nidhi_biet" }, { "code": null, "e": 32730, "s": 32709, "text": "avanitrachhadiya2155" }, { "code": null, "e": 32747, "s": 32730, "text": "khushboogoyal499" }, { "code": null, "e": 32755, "s": 32747, "text": "rag2127" }, { "code": null, "e": 32769, "s": 32755, "text": "divyesh072019" }, { "code": null, "e": 32784, "s": 32769, "text": "chinmoy1997pal" }, { "code": null, "e": 32793, "s": 32784, "text": "Analysis" }, { "code": null, "e": 32817, "s": 32793, "text": "Competitive Programming" }, { "code": null, "e": 32833, "s": 32817, "text": "Data Structures" }, { "code": null, "e": 32846, "s": 32833, "text": "Mathematical" }, { "code": null, "e": 32864, "s": 32846, "text": "Pattern Searching" }, { "code": null, "e": 32880, "s": 32864, "text": "Data Structures" }, { "code": null, "e": 32893, "s": 32880, "text": "Mathematical" }, { "code": null, "e": 32911, "s": 32893, "text": "Pattern Searching" }, { "code": null, "e": 33009, "s": 32911, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33018, "s": 33009, "text": "Comments" }, { "code": null, "e": 33031, "s": 33018, "text": "Old Comments" }, { "code": null, "e": 33098, "s": 33031, "text": "Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete" }, { "code": null, "e": 33164, "s": 33098, "text": "Difference between Deterministic and Non-deterministic Algorithms" }, { "code": null, "e": 33214, "s": 33164, "text": "Proof that Dominant Set of a Graph is NP-Complete" }, { "code": null, "e": 33240, "s": 33214, "text": "3-coloring is NP Complete" }, { "code": null, "e": 33269, "s": 33240, "text": "Set partition is NP complete" }, { "code": null, "e": 33312, "s": 33269, "text": "Practice for cracking any coding interview" }, { "code": null, "e": 33353, "s": 33312, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 33396, "s": 33353, "text": "Competitive Programming - A Complete Guide" }, { "code": null, "e": 33474, "s": 33396, "text": "Prefix Sum Array - Implementation and Applications in Competitive Programming" } ]
A Quantum-Enhanced LSTM Layer. Using the PennyLane Quantum Machine... | by Riccardo Di Sipio | Towards Data Science
In recent years, Toronto-based startup company Xanadu has introduced a python framework called PennyLane which allows users to create hybrid Quantum Machine Learning (QML) models. While it’s still too early to claim that quantum computing has taken over, there are some areas where it can give an advantage as for example in drug discovery or finance. One field that so far has been poorly explored in QML is Natural Language Processing (NLP), the sub-field of Artificial Intelligence that gives computers the ability to read, write and to some extent comprehend written text. As documents are usually presented as sequences of words, historically one of the most successful techniques to manipulate this kind of data has been the Recurrent Neural Network architecture, and in particular a variant called Long Short-Term Memory (LSTM). The “trick” that makes these networks so popular in the analysis of sequential data is a combination of “memory” and “statefulness” that help with identifying which components of the input are relevant to compute the output. While the mathematics is quite thick as we’ll see later on, suffices to say for now that LSTMs allowed machines to perform translations, classification and intent detection with state-of-the-art accuracy until the advent of Transformer networks. Still, it’s interesting at least from an educational point of view to dig into LSTMs to see what good quantum computing may bring to the field. For a more thorough discussion, please refer to “Quantum Long Short-Term Memory” by Chen, Yoo and Fang (arXiv:2009.01783) and “Recurrent Quantum Neural Networks” by J. Bausch (arXiv:2006.14619). On the same subject, see also my other posts Toward a Quantum Transformer, Classifying Scientific Documents with Quantum-Enhanced Transfer Learning and Spooky Computers at CERN. To begin with, let’s review the inner workings of a LSTM. We assume that the input x is composed of a sequence of t time-steps (e.g. words), each represented by a N-dimensional feature vector (in practical applications N can be large, e.g. 512). Also, the network stores a hidden array of vectors h and a state vector c that are updated for each element of the input sequence. For example, if we are only interested in a summary of the sequence (e.g. in a sentiment analysis), the last element of the array h will be returned. Instead, if we are interested in a representation of each element (e.g. to assign to each word a part-of-speech tag such as noun, verb, etc...), we want to have access to every element of h. The calculation can be summarized in the formulas below: where v_t is a concatenation of the input element at step t and the hidden state at step t-1, i.e. v_t = [h_(t-1), x_t]. In the machine learning parlance, borrowed from electric circuit analysis, f_t is called forget gate, i_t is the input gate, C_t is the update gate and o_t is the output gate. The matrices W_f, W_i, W_C and W_o and the bias vectors b_f, b_i, b_C and b_o are the parameters that have be learned during the supervised training and implement the part of the calculation called linear dense layer that we want to replace with the quantum equivalent. As often the case, a non-linearity is introduced by the application of Sigmoid and Hyperbolic Tangent (tanh) functions to the output of these four dense layers, which effect is to determine whether a part of the input has to be considered (values close to 1) or ignored (values close to 0). A key concept in Quantum Machine Learning is that information is stored in units of information called qubits that are a so-called superposition of the states 0 and 1. Physically, they may represent for example the orientation of the spin of a particle with respect to the axis of a magnetic field, or the circulation of electric current in a superconductor. For practical purposes, these details can safely be ignored. What’s important is to remember that the calculation is carried by first putting the input qubits into the initial state (e.g. a string such as 010010), then they are entangled between each other, rotated by an arbitrary angles, and finally observed (“measured”). The goal of the training is to find the rotation angles mentioned above that optimize some cost function such as the mean squared error (MSE) between the output and some pre-determined labels. This kind of quantum circuit is known as Variational Quantum Circuit. Using the PennyLane library, one can easily define a VQC as a series of AngleEmbedding and StronglyEntanglingLayers objects. One problem that may not be obvious at the onset is that while bits are cheap, qubits are expensive: it’s hard to keep real qubits in superposition state, it’s also hard to simulate them. So forget about designing a circuit with 12 qubits. Good news is, thanks to their own nature, fewer qubits are probably needed to perform the calculation. To cut a long story short, what we’ll do here is to introduce a “dressed quantum circuit”, i.e. we sandwich the quantum layer between two classical linear layers to match the dimensionality. For example, if the feature dimension is 8 and the hidden dimension is 6, but we can only afford 4 qubits, what we need is a sequence like this: x_in = torch.randn(8)x = nn.Linear(8, 4)(x_in)x_q = VQC(x)x_out = Linear(4, 6)(x_q) We need one classical layer to “squeeze” the input to match the number of qubits, and one classical layer to “bloat” the output of f_t, i_t, C_t and o_t. to match the dimension of the hidden vectors. Thus, overall we still have a number of classical parameters that have to be learned during the training. Putting all together, the core of the calculation looks like this: Does it work? To test if all the above makes sense, an intuitive but not trivial example is needed. In this case, I decided to adapt the part-of-speech (POS) tagging example from PyTorch to the case under consideration. The idea is pretty simple: we have a set of two sentences (“The dog ate the apple” and “Everybody read that book”) whose words have been annotated with POS tags. For example, the first sentence is thus [“DET”, “NN”, “V”, “DET”, “NN”]. The idea is to pass the two sequences through the LSTM, which will output the hidden array of vectors [h_0, h_1, h_2, h_3, h_4], one for each word. A dense layer “head” is attached to the LSTM’s outputs to calculate the probability that each word may be a determinant, noun or verb (for the curious, that is a softmax layer with dimension 3). Following the example from the PyTorch website, we train the two networks (classical and quantum LSTM) for 300 epochs. This is just a toy example and has to be taken as such, but still, the results are encouraging. The loss function decreases as a function of the training epoch, and after 300 epochs both networks are able to tag correctly the first sentence. Due to the complexity of the simulation of the quantum circuit, it took approximatively 15 minutes to finish the training, to be compared to a mere 8 seconds for the classical case. Also, looking at the plots, it seems that the quantum LSTM needed to be trained for longer, but that’s enough for our purpose. Sentence: ['The', 'dog', 'ate', 'the', 'apple']Labels: ['DET', 'NN', 'V', 'DET', 'NN']Predicted: ['DET', 'NN', 'V', 'DET', 'NN']Classical loss at 300 epochs: 0.029Quantum loss at 300 epochs: 0.250 To conclude, libraries such as PennyLane or TensorFlow Quantum offer a high-level of abstraction to define quantum/digital hybrid models for Quantum Machine Learning. This is a field that is rapidly expanding and more and more applications are being explored as one can happily see by attending topical conferences such as QTML 2020. Give me the code! https://github.com/rdisipio/qlstm
[ { "code": null, "e": 749, "s": 172, "text": "In recent years, Toronto-based startup company Xanadu has introduced a python framework called PennyLane which allows users to create hybrid Quantum Machine Learning (QML) models. While it’s still too early to claim that quantum computing has taken over, there are some areas where it can give an advantage as for example in drug discovery or finance. One field that so far has been poorly explored in QML is Natural Language Processing (NLP), the sub-field of Artificial Intelligence that gives computers the ability to read, write and to some extent comprehend written text." }, { "code": null, "e": 1996, "s": 749, "text": "As documents are usually presented as sequences of words, historically one of the most successful techniques to manipulate this kind of data has been the Recurrent Neural Network architecture, and in particular a variant called Long Short-Term Memory (LSTM). The “trick” that makes these networks so popular in the analysis of sequential data is a combination of “memory” and “statefulness” that help with identifying which components of the input are relevant to compute the output. While the mathematics is quite thick as we’ll see later on, suffices to say for now that LSTMs allowed machines to perform translations, classification and intent detection with state-of-the-art accuracy until the advent of Transformer networks. Still, it’s interesting at least from an educational point of view to dig into LSTMs to see what good quantum computing may bring to the field. For a more thorough discussion, please refer to “Quantum Long Short-Term Memory” by Chen, Yoo and Fang (arXiv:2009.01783) and “Recurrent Quantum Neural Networks” by J. Bausch (arXiv:2006.14619). On the same subject, see also my other posts Toward a Quantum Transformer, Classifying Scientific Documents with Quantum-Enhanced Transfer Learning and Spooky Computers at CERN." }, { "code": null, "e": 2714, "s": 1996, "text": "To begin with, let’s review the inner workings of a LSTM. We assume that the input x is composed of a sequence of t time-steps (e.g. words), each represented by a N-dimensional feature vector (in practical applications N can be large, e.g. 512). Also, the network stores a hidden array of vectors h and a state vector c that are updated for each element of the input sequence. For example, if we are only interested in a summary of the sequence (e.g. in a sentiment analysis), the last element of the array h will be returned. Instead, if we are interested in a representation of each element (e.g. to assign to each word a part-of-speech tag such as noun, verb, etc...), we want to have access to every element of h." }, { "code": null, "e": 2771, "s": 2714, "text": "The calculation can be summarized in the formulas below:" }, { "code": null, "e": 3629, "s": 2771, "text": "where v_t is a concatenation of the input element at step t and the hidden state at step t-1, i.e. v_t = [h_(t-1), x_t]. In the machine learning parlance, borrowed from electric circuit analysis, f_t is called forget gate, i_t is the input gate, C_t is the update gate and o_t is the output gate. The matrices W_f, W_i, W_C and W_o and the bias vectors b_f, b_i, b_C and b_o are the parameters that have be learned during the supervised training and implement the part of the calculation called linear dense layer that we want to replace with the quantum equivalent. As often the case, a non-linearity is introduced by the application of Sigmoid and Hyperbolic Tangent (tanh) functions to the output of these four dense layers, which effect is to determine whether a part of the input has to be considered (values close to 1) or ignored (values close to 0)." }, { "code": null, "e": 4701, "s": 3629, "text": "A key concept in Quantum Machine Learning is that information is stored in units of information called qubits that are a so-called superposition of the states 0 and 1. Physically, they may represent for example the orientation of the spin of a particle with respect to the axis of a magnetic field, or the circulation of electric current in a superconductor. For practical purposes, these details can safely be ignored. What’s important is to remember that the calculation is carried by first putting the input qubits into the initial state (e.g. a string such as 010010), then they are entangled between each other, rotated by an arbitrary angles, and finally observed (“measured”). The goal of the training is to find the rotation angles mentioned above that optimize some cost function such as the mean squared error (MSE) between the output and some pre-determined labels. This kind of quantum circuit is known as Variational Quantum Circuit. Using the PennyLane library, one can easily define a VQC as a series of AngleEmbedding and StronglyEntanglingLayers objects." }, { "code": null, "e": 5380, "s": 4701, "text": "One problem that may not be obvious at the onset is that while bits are cheap, qubits are expensive: it’s hard to keep real qubits in superposition state, it’s also hard to simulate them. So forget about designing a circuit with 12 qubits. Good news is, thanks to their own nature, fewer qubits are probably needed to perform the calculation. To cut a long story short, what we’ll do here is to introduce a “dressed quantum circuit”, i.e. we sandwich the quantum layer between two classical linear layers to match the dimensionality. For example, if the feature dimension is 8 and the hidden dimension is 6, but we can only afford 4 qubits, what we need is a sequence like this:" }, { "code": null, "e": 5464, "s": 5380, "text": "x_in = torch.randn(8)x = nn.Linear(8, 4)(x_in)x_q = VQC(x)x_out = Linear(4, 6)(x_q)" }, { "code": null, "e": 5837, "s": 5464, "text": "We need one classical layer to “squeeze” the input to match the number of qubits, and one classical layer to “bloat” the output of f_t, i_t, C_t and o_t. to match the dimension of the hidden vectors. Thus, overall we still have a number of classical parameters that have to be learned during the training. Putting all together, the core of the calculation looks like this:" }, { "code": null, "e": 6635, "s": 5837, "text": "Does it work? To test if all the above makes sense, an intuitive but not trivial example is needed. In this case, I decided to adapt the part-of-speech (POS) tagging example from PyTorch to the case under consideration. The idea is pretty simple: we have a set of two sentences (“The dog ate the apple” and “Everybody read that book”) whose words have been annotated with POS tags. For example, the first sentence is thus [“DET”, “NN”, “V”, “DET”, “NN”]. The idea is to pass the two sequences through the LSTM, which will output the hidden array of vectors [h_0, h_1, h_2, h_3, h_4], one for each word. A dense layer “head” is attached to the LSTM’s outputs to calculate the probability that each word may be a determinant, noun or verb (for the curious, that is a softmax layer with dimension 3)." }, { "code": null, "e": 7305, "s": 6635, "text": "Following the example from the PyTorch website, we train the two networks (classical and quantum LSTM) for 300 epochs. This is just a toy example and has to be taken as such, but still, the results are encouraging. The loss function decreases as a function of the training epoch, and after 300 epochs both networks are able to tag correctly the first sentence. Due to the complexity of the simulation of the quantum circuit, it took approximatively 15 minutes to finish the training, to be compared to a mere 8 seconds for the classical case. Also, looking at the plots, it seems that the quantum LSTM needed to be trained for longer, but that’s enough for our purpose." }, { "code": null, "e": 7508, "s": 7305, "text": "Sentence: ['The', 'dog', 'ate', 'the', 'apple']Labels: ['DET', 'NN', 'V', 'DET', 'NN']Predicted: ['DET', 'NN', 'V', 'DET', 'NN']Classical loss at 300 epochs: 0.029Quantum loss at 300 epochs: 0.250" }, { "code": null, "e": 7842, "s": 7508, "text": "To conclude, libraries such as PennyLane or TensorFlow Quantum offer a high-level of abstraction to define quantum/digital hybrid models for Quantum Machine Learning. This is a field that is rapidly expanding and more and more applications are being explored as one can happily see by attending topical conferences such as QTML 2020." } ]
How to remove empty string/lines from PowerShell?
In many instances, you need to remove empty lines or strings from the PowerShell string array or the files. In this article instead of removing empty string, we will get the result or filter the output from lines that are not empty. In this way, we can get the output without empty lines. Consider the example below, we have a file called EmptryString.txt and we need to remove empty lines from the content. The content of the text file is as below. PS C:\Windows\System32> Get-Content D:\Temp\EmptyString.txt This is example of empty string PowerShell PowerShell DSC String Array Hello You just need to apply the condition where the line is not empty. See the code below. Get-Content D:\Temp\EmptyString.txt | where{$_ -ne ""} This is example of empty string PowerShell PowerShell DSC String Array Hello Similarly, you can use the above command to remove empty lines from the string array. For example, $str = "Dog","","Cat","","Camel","","Tiger" $str PS C:\Windows\System32> $str Cat Camel TigerDog Now apply the same logic to remove the empty lines. $str | where{$_ -ne ""} PS C:\Windows\System32> $str | where{$_ ne ""} Dog Cat Camel Tiger
[ { "code": null, "e": 1351, "s": 1062, "text": "In many instances, you need to remove empty lines or strings from the PowerShell string array or the files. In this article instead of removing empty string, we will get the result or filter the output from lines that are not empty. In this way, we can get the output without empty lines." }, { "code": null, "e": 1470, "s": 1351, "text": "Consider the example below, we have a file called EmptryString.txt and we need to remove empty lines from the content." }, { "code": null, "e": 1512, "s": 1470, "text": "The content of the text file is as below." }, { "code": null, "e": 1649, "s": 1512, "text": "PS C:\\Windows\\System32> Get-Content D:\\Temp\\EmptyString.txt\nThis is example of empty string\nPowerShell\nPowerShell DSC\nString Array\nHello" }, { "code": null, "e": 1735, "s": 1649, "text": "You just need to apply the condition where the line is not empty. See the code below." }, { "code": null, "e": 1790, "s": 1735, "text": "Get-Content D:\\Temp\\EmptyString.txt | where{$_ -ne \"\"}" }, { "code": null, "e": 1867, "s": 1790, "text": "This is example of empty string\nPowerShell\nPowerShell DSC\nString Array\nHello" }, { "code": null, "e": 1966, "s": 1867, "text": "Similarly, you can use the above command to remove empty lines from the string array. For example," }, { "code": null, "e": 2063, "s": 1966, "text": "$str = \"Dog\",\"\",\"Cat\",\"\",\"Camel\",\"\",\"Tiger\"\n$str\nPS C:\\Windows\\System32>\n$str\nCat\nCamel\nTigerDog" }, { "code": null, "e": 2115, "s": 2063, "text": "Now apply the same logic to remove the empty lines." }, { "code": null, "e": 2139, "s": 2115, "text": "$str | where{$_ -ne \"\"}" }, { "code": null, "e": 2206, "s": 2139, "text": "PS C:\\Windows\\System32> $str | where{$_ ne \"\"}\nDog\nCat\nCamel\nTiger" } ]
How to show minor tick labels on a log-scale with Matplotlib?
To show minor tick labels on a log-scale with Matplotlib, we can take the following steps − Set the figure size and adjust the padding between and around the subplots. Create x and y data points using numpy. Plot x and y data points using plot() method Get the current axis using gca() method. Set the yscale with log class by name. Change the appearance of ticks and tick label using ick_params() method. Set the minor axis formatter with format strings to format the tick. To display the figure, use show() method. import numpy as np import matplotlib.pyplot as plt from matplotlib.ticker import FormatStrFormatter plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True x = np.linspace(-2, 2, 10) y = np.exp(x) plt.plot(x, y) ax = plt.gca() ax.set_yscale('log') plt.tick_params(axis='y', which='minor') ax.yaxis.set_minor_formatter(FormatStrFormatter("%.1f")) plt.show()
[ { "code": null, "e": 1154, "s": 1062, "text": "To show minor tick labels on a log-scale with Matplotlib, we can take the following steps −" }, { "code": null, "e": 1230, "s": 1154, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1270, "s": 1230, "text": "Create x and y data points using numpy." }, { "code": null, "e": 1315, "s": 1270, "text": "Plot x and y data points using plot() method" }, { "code": null, "e": 1356, "s": 1315, "text": "Get the current axis using gca() method." }, { "code": null, "e": 1395, "s": 1356, "text": "Set the yscale with log class by name." }, { "code": null, "e": 1468, "s": 1395, "text": "Change the appearance of ticks and tick label using ick_params() method." }, { "code": null, "e": 1537, "s": 1468, "text": "Set the minor axis formatter with format strings to format the tick." }, { "code": null, "e": 1579, "s": 1537, "text": "To display the figure, use show() method." }, { "code": null, "e": 1973, "s": 1579, "text": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.ticker import FormatStrFormatter\n\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\nx = np.linspace(-2, 2, 10)\ny = np.exp(x)\n\nplt.plot(x, y)\n\nax = plt.gca()\nax.set_yscale('log')\n\nplt.tick_params(axis='y', which='minor')\nax.yaxis.set_minor_formatter(FormatStrFormatter(\"%.1f\"))\n\nplt.show()" } ]
Python – Get Most recent previous business day
18 Jul, 2021 Given a date, the task is to write a Python program to get the most recent previous business day from the given date. Example: Input : test_date = datetime(2020, 1, 31) Output : 2020-01-30 00:00:00 Explanation : 31 Jan 2020, being a Friday, last business day is thursday, i.e 30 January. Input : test_date = datetime(2020, 2, 3) Output : 2020-01-31 00:00:00 Explanation : 3 Feb 2020, being a Monday, last business day is friday, i.e 31 January. Method 1: Using timedelta() + weekday() In this, we perform the task of subtracting 3 in the case of Monday, 2 in the case of Sunday, and 1 on all other days. The timedelta() performs the task of subtraction, and conditional statements check for a weekday. Python3 # Python3 code to demonstrate working of# Last business day# using timedelta() + conditional statements + weekday()from datetime import datetime, timedelta # initializing datestest_date = datetime(2020, 1, 31) # printing original dateprint("The original date is : " + str(test_date)) # getting differencediff = 1if test_date.weekday() == 0: diff = 3elif test_date.weekday() == 6: diff = 2else : diff = 1 # subtracting diff res = test_date - timedelta(days=diff) # printing resultprint("Last business day : " + str(res)) Output: The original date is : 2020-01-31 00:00:00 Last business day : 2020-01-30 00:00:00 Method 2: Using max() + % operator + timedelta() Perform tasks in similar way, only difference being method to compute difference changes to get max() and % operator. Python3 # Python3 code to demonstrate working of# Last business day# using max() + % operator + timedelta() from datetime import datetime, timedelta # initializing datestest_date = datetime(2020, 1, 31) # printing original dateprint("The original date is : " + str(test_date)) # getting difference# using max() to get differences diff = max(1, (test_date.weekday() + 6) % 7 - 3) # subtracting diff res = test_date - timedelta(days=diff) # printing resultprint("Last business day : " + str(res)) Output: The original date is : 2020-01-31 00:00:00 Last business day : 2020-01-30 00:00:00 Method 3 : Using pd.tseries.offsets.BusinessDay(n) In this, we create a Business day offset of 1 day, and subtract from the date initialized. This returns the previous business day as desired. Python3 # Python3 code to demonstrate working of# Last business day# using pd.tseries.offsets.BusinessDay(n)import pandas as pdfrom datetime import datetime # initializing datestest_date = datetime(2020, 2, 3) # printing original dateprint("The original date is : " + str(test_date)) # Creating Timestampts = pd.Timestamp(str(test_date)) # Create an offset of 1 Business daysoffset = pd.tseries.offsets.BusinessDay(n=1) # getting result by subtracting offsetres = test_date - offset # printing resultprint("Last business day : " + str(res)) Output : The original date is : 2020-02-03 00:00:00 Last business day : 2020-01-31 00:00:00 Python datetime-program Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() Python program to convert a list to string Python | Get dictionary keys as a list Python | Convert a list to dictionary Python Program for Fibonacci numbers Python | Split string into list of characters
[ { "code": null, "e": 28, "s": 0, "text": "\n18 Jul, 2021" }, { "code": null, "e": 146, "s": 28, "text": "Given a date, the task is to write a Python program to get the most recent previous business day from the given date." }, { "code": null, "e": 155, "s": 146, "text": "Example:" }, { "code": null, "e": 197, "s": 155, "text": "Input : test_date = datetime(2020, 1, 31)" }, { "code": null, "e": 226, "s": 197, "text": "Output : 2020-01-30 00:00:00" }, { "code": null, "e": 316, "s": 226, "text": "Explanation : 31 Jan 2020, being a Friday, last business day is thursday, i.e 30 January." }, { "code": null, "e": 357, "s": 316, "text": "Input : test_date = datetime(2020, 2, 3)" }, { "code": null, "e": 386, "s": 357, "text": "Output : 2020-01-31 00:00:00" }, { "code": null, "e": 473, "s": 386, "text": "Explanation : 3 Feb 2020, being a Monday, last business day is friday, i.e 31 January." }, { "code": null, "e": 513, "s": 473, "text": "Method 1: Using timedelta() + weekday()" }, { "code": null, "e": 730, "s": 513, "text": "In this, we perform the task of subtracting 3 in the case of Monday, 2 in the case of Sunday, and 1 on all other days. The timedelta() performs the task of subtraction, and conditional statements check for a weekday." }, { "code": null, "e": 738, "s": 730, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Last business day# using timedelta() + conditional statements + weekday()from datetime import datetime, timedelta # initializing datestest_date = datetime(2020, 1, 31) # printing original dateprint(\"The original date is : \" + str(test_date)) # getting differencediff = 1if test_date.weekday() == 0: diff = 3elif test_date.weekday() == 6: diff = 2else : diff = 1 # subtracting diff res = test_date - timedelta(days=diff) # printing resultprint(\"Last business day : \" + str(res))", "e": 1289, "s": 738, "text": null }, { "code": null, "e": 1297, "s": 1289, "text": "Output:" }, { "code": null, "e": 1380, "s": 1297, "text": "The original date is : 2020-01-31 00:00:00\nLast business day : 2020-01-30 00:00:00" }, { "code": null, "e": 1430, "s": 1380, "text": "Method 2: Using max() + % operator + timedelta() " }, { "code": null, "e": 1549, "s": 1430, "text": "Perform tasks in similar way, only difference being method to compute difference changes to get max() and % operator. " }, { "code": null, "e": 1557, "s": 1549, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Last business day# using max() + % operator + timedelta() from datetime import datetime, timedelta # initializing datestest_date = datetime(2020, 1, 31) # printing original dateprint(\"The original date is : \" + str(test_date)) # getting difference# using max() to get differences diff = max(1, (test_date.weekday() + 6) % 7 - 3) # subtracting diff res = test_date - timedelta(days=diff) # printing resultprint(\"Last business day : \" + str(res))", "e": 2066, "s": 1557, "text": null }, { "code": null, "e": 2074, "s": 2066, "text": "Output:" }, { "code": null, "e": 2157, "s": 2074, "text": "The original date is : 2020-01-31 00:00:00\nLast business day : 2020-01-30 00:00:00" }, { "code": null, "e": 2209, "s": 2157, "text": "Method 3 : Using pd.tseries.offsets.BusinessDay(n) " }, { "code": null, "e": 2351, "s": 2209, "text": "In this, we create a Business day offset of 1 day, and subtract from the date initialized. This returns the previous business day as desired." }, { "code": null, "e": 2359, "s": 2351, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Last business day# using pd.tseries.offsets.BusinessDay(n)import pandas as pdfrom datetime import datetime # initializing datestest_date = datetime(2020, 2, 3) # printing original dateprint(\"The original date is : \" + str(test_date)) # Creating Timestampts = pd.Timestamp(str(test_date)) # Create an offset of 1 Business daysoffset = pd.tseries.offsets.BusinessDay(n=1) # getting result by subtracting offsetres = test_date - offset # printing resultprint(\"Last business day : \" + str(res))", "e": 2898, "s": 2359, "text": null }, { "code": null, "e": 2908, "s": 2898, "text": "Output : " }, { "code": null, "e": 2991, "s": 2908, "text": "The original date is : 2020-02-03 00:00:00\nLast business day : 2020-01-31 00:00:00" }, { "code": null, "e": 3015, "s": 2991, "text": "Python datetime-program" }, { "code": null, "e": 3022, "s": 3015, "text": "Python" }, { "code": null, "e": 3038, "s": 3022, "text": "Python Programs" }, { "code": null, "e": 3136, "s": 3038, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3154, "s": 3136, "text": "Python Dictionary" }, { "code": null, "e": 3196, "s": 3154, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 3218, "s": 3196, "text": "Enumerate() in Python" }, { "code": null, "e": 3253, "s": 3218, "text": "Read a file line by line in Python" }, { "code": null, "e": 3279, "s": 3253, "text": "Python String | replace()" }, { "code": null, "e": 3322, "s": 3279, "text": "Python program to convert a list to string" }, { "code": null, "e": 3361, "s": 3322, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 3399, "s": 3361, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 3436, "s": 3399, "text": "Python Program for Fibonacci numbers" } ]
Find the roots of the polynomials using NumPy
05 Sep, 2020 In this article, let’s discuss how to find the roots of a polynomial of a NumPy array. It can be found using various methods, let’s see them in detail. Method 1: Using np.roots() This function returns the roots of a polynomial with coefficients given in p. The coefficients of the polynomial are to be put in an array in the respective order. For example, if the polynomial is x2 +3x + 1, then the array will be [1, 3, 1] Syntax : numpy.roots(p) Parameters :p : [array_like] Rank-1 array of polynomial coefficients. Return : [ndarray] An array containing the roots of the polynomial. Let’s see some examples: Example 1: Find the roots of polynomial x2 +2x + 1 Python3 # import numpy libraryimport numpy as np # Enter the coefficients of the poly in the arraycoeff = [1, 2, 1]print(np.roots(coeff)) Output: [-1. -1.] Example 2: Find the roots of the polynomial x3 +3 x2 + 2x +1 Python3 # import numpy libraryimport numpy as np # Enter the coefficients of the poly # in the arraycoeff = [1, 3, 2, 1]print(np.roots(coeff)) Output: [-2.32471796+0.j -0.33764102+0.56227951j -0.33764102-0.56227951j] Method 2: Using np.poly1D() This function helps to define a polynomial function. It makes it easy to apply “natural operations” on polynomials. The coefficients of the polynomial are to be put in an array in the respective order. For example, for the polynomial x2 +3x + 1, the array will be [1, 3, 1] Approach: Apply function np.poly1D() on the array and store it in a variable. Find the roots by multiplying the variable by roots or r(in-built keyword) and print the result to get the roots of the given polynomial Syntax: numpy.poly1d(arr, root, var): Let’s see some examples: Example 1: Find the roots of polynomial x2 +2x + 1 Python3 # import numpy libraryimport numpy as np # enter the coefficients of poly # in the arrayp = np.poly1d([1, 2, 1]) # multiplying by r(or roots) to # get the rootsroot_of_poly = p.rprint(root_of_poly) Output: [-1. -1.] Example 2: Find the roots of the polynomial x3 +3 x2 + 2x +1 Python3 # import numpy libraryimport numpy as np # enter the coefficients of poly# in the arrayp = np.poly1d([1, 3, 2, 1]) # multiplying by r(or roots) to get # the rootsroot_of_poly = p.rprint(root_of_poly) Output: [-2.32471796+0.j -0.33764102+0.56227951j -0.33764102-0.56227951j] Python numpy-polynomials 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 ? Python Classes and Objects Python | os.path.join() method Python OOPs Concepts How to drop one or multiple columns in Pandas Dataframe Introduction To PYTHON How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | datetime.timedelta() function Python | Get unique values from a list
[ { "code": null, "e": 52, "s": 24, "text": "\n05 Sep, 2020" }, { "code": null, "e": 204, "s": 52, "text": "In this article, let’s discuss how to find the roots of a polynomial of a NumPy array. It can be found using various methods, let’s see them in detail." }, { "code": null, "e": 231, "s": 204, "text": "Method 1: Using np.roots()" }, { "code": null, "e": 396, "s": 231, "text": "This function returns the roots of a polynomial with coefficients given in p. The coefficients of the polynomial are to be put in an array in the respective order. " }, { "code": null, "e": 475, "s": 396, "text": "For example, if the polynomial is x2 +3x + 1, then the array will be [1, 3, 1]" }, { "code": null, "e": 499, "s": 475, "text": "Syntax : numpy.roots(p)" }, { "code": null, "e": 569, "s": 499, "text": "Parameters :p : [array_like] Rank-1 array of polynomial coefficients." }, { "code": null, "e": 637, "s": 569, "text": "Return : [ndarray] An array containing the roots of the polynomial." }, { "code": null, "e": 662, "s": 637, "text": "Let’s see some examples:" }, { "code": null, "e": 713, "s": 662, "text": "Example 1: Find the roots of polynomial x2 +2x + 1" }, { "code": null, "e": 721, "s": 713, "text": "Python3" }, { "code": "# import numpy libraryimport numpy as np # Enter the coefficients of the poly in the arraycoeff = [1, 2, 1]print(np.roots(coeff))", "e": 854, "s": 721, "text": null }, { "code": null, "e": 862, "s": 854, "text": "Output:" }, { "code": null, "e": 872, "s": 862, "text": "[-1. -1.]" }, { "code": null, "e": 935, "s": 872, "text": "Example 2: Find the roots of the polynomial x3 +3 x2 + 2x +1" }, { "code": null, "e": 943, "s": 935, "text": "Python3" }, { "code": "# import numpy libraryimport numpy as np # Enter the coefficients of the poly # in the arraycoeff = [1, 3, 2, 1]print(np.roots(coeff))", "e": 1081, "s": 943, "text": null }, { "code": null, "e": 1089, "s": 1081, "text": "Output:" }, { "code": null, "e": 1163, "s": 1089, "text": "[-2.32471796+0.j -0.33764102+0.56227951j -0.33764102-0.56227951j]" }, { "code": null, "e": 1191, "s": 1163, "text": "Method 2: Using np.poly1D()" }, { "code": null, "e": 1393, "s": 1191, "text": "This function helps to define a polynomial function. It makes it easy to apply “natural operations” on polynomials. The coefficients of the polynomial are to be put in an array in the respective order." }, { "code": null, "e": 1465, "s": 1393, "text": "For example, for the polynomial x2 +3x + 1, the array will be [1, 3, 1]" }, { "code": null, "e": 1475, "s": 1465, "text": "Approach:" }, { "code": null, "e": 1543, "s": 1475, "text": "Apply function np.poly1D() on the array and store it in a variable." }, { "code": null, "e": 1680, "s": 1543, "text": "Find the roots by multiplying the variable by roots or r(in-built keyword) and print the result to get the roots of the given polynomial" }, { "code": null, "e": 1718, "s": 1680, "text": "Syntax: numpy.poly1d(arr, root, var):" }, { "code": null, "e": 1743, "s": 1718, "text": "Let’s see some examples:" }, { "code": null, "e": 1794, "s": 1743, "text": "Example 1: Find the roots of polynomial x2 +2x + 1" }, { "code": null, "e": 1802, "s": 1794, "text": "Python3" }, { "code": "# import numpy libraryimport numpy as np # enter the coefficients of poly # in the arrayp = np.poly1d([1, 2, 1]) # multiplying by r(or roots) to # get the rootsroot_of_poly = p.rprint(root_of_poly)", "e": 2004, "s": 1802, "text": null }, { "code": null, "e": 2012, "s": 2004, "text": "Output:" }, { "code": null, "e": 2022, "s": 2012, "text": "[-1. -1.]" }, { "code": null, "e": 2085, "s": 2022, "text": "Example 2: Find the roots of the polynomial x3 +3 x2 + 2x +1" }, { "code": null, "e": 2093, "s": 2085, "text": "Python3" }, { "code": "# import numpy libraryimport numpy as np # enter the coefficients of poly# in the arrayp = np.poly1d([1, 3, 2, 1]) # multiplying by r(or roots) to get # the rootsroot_of_poly = p.rprint(root_of_poly)", "e": 2297, "s": 2093, "text": null }, { "code": null, "e": 2305, "s": 2297, "text": "Output:" }, { "code": null, "e": 2379, "s": 2305, "text": "[-2.32471796+0.j -0.33764102+0.56227951j -0.33764102-0.56227951j]" }, { "code": null, "e": 2404, "s": 2379, "text": "Python numpy-polynomials" }, { "code": null, "e": 2417, "s": 2404, "text": "Python-numpy" }, { "code": null, "e": 2424, "s": 2417, "text": "Python" }, { "code": null, "e": 2522, "s": 2424, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2554, "s": 2522, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2581, "s": 2554, "text": "Python Classes and Objects" }, { "code": null, "e": 2612, "s": 2581, "text": "Python | os.path.join() method" }, { "code": null, "e": 2633, "s": 2612, "text": "Python OOPs Concepts" }, { "code": null, "e": 2689, "s": 2633, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2712, "s": 2689, "text": "Introduction To PYTHON" }, { "code": null, "e": 2754, "s": 2712, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2796, "s": 2754, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2835, "s": 2796, "text": "Python | datetime.timedelta() function" } ]
How to get LocalDateTime object from java.sql.Date using JDBC?
The java.time package of Java8 provides a class named LocalDateTime is used to get the current value of local date and time. Using this in addition to date and time values you can also get other date and time fields, such as day-of-year, day-of-week and week-of-year. The java.sql.TimeStamp class provides a method with name toLocalDateTime() this method converts the current timestamp object to a LocalDateTime object and returns it. To convert date to LocalDateTime object. Create a Timestamp object from Date object using the getTime() method as − Date date = rs.getDate("DispatchDate"); //Converting Date to Timestamp Timestamp timestamp = new Timestamp(date.getTime()); Now, convert the Timestamp object to LocalDateTime object using the toLocalDateTime() method. Time time = rs.getTime("DeliveryTime"); //Converting time to Timestamp Timestamp timestamp = new Timestamp(time.getTime()); //Time stamp to LocalDateTime timestamp.toLocalDateTime(); Let us create a table with name dispatches in MySQL database using CREATE statement as follows − CREATE TABLE dispatches( ProductName VARCHAR(255), CustomerName VARCHAR(255), DispatchDate date, DeliveryTime time, Price INT, Location VARCHAR(255) ); Now, we will insert 2 records in dispatches table using INSERT statements − insert into dispatches values('Key-Board', 'Raja', DATE('2019-09-01'), TIME('11:00:00'), 7000, 'Hyderabad'); insert into dispatches values('Earphones', 'Roja', DATE('2019-05-01'), TIME('11:00:00'), 2000, 'Vishakhapatnam'); Following JDBC program establishes connection with the database and retrieves the contents of the dispatches_data table and, converts the Date value (Dispatch_Date column) of the first record to LocalDateTime object and displays it along with its contents. import java.sql.Connection; import java.sql.Date; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.Timestamp; public class LocalDateTimeExample { public static void main(String args[]) throws SQLException { //Registering the Driver DriverManager.registerDriver(new com.mysql.jdbc.Driver()); //Getting the connection String mysqlUrl = "jdbc:mysql://localhost/mydatabase"; Connection con = DriverManager.getConnection(mysqlUrl, "root", "password"); System.out.println("Connection established......"); //Retrieving values Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("select * from dispatches"); rs.next(); //Retrieving the Date from the table Date date = rs.getDate("DispatchDate"); //Converting Date to Timestamp Timestamp timestamp = new Timestamp(date.getTime()); System.out.println("LocalDateTime value from date: "+timestamp.toLocalDateTime()); System.out.println(""); System.out.println("Contents of the first record: "); System.out.println("Product Name: "+rs.getString("ProductName")); System.out.println("Customer Name: "+rs.getString("CustomerName")); System.out.println("Dispatch Date: "+rs.getDate("DispatchDate")); System.out.println("Delivery Time: "+ rs.getTime("DeliveryTime")); System.out.println("Location: "+rs.getString("Location")); System.out.println(); } } Connection established...... LocalDateTime value from date: 2019-09-01T00:00 Contents of the first record: Product Name: Key-Board Customer Name: Raja Dispatch Date: 2019-09-01 Delivery Time: 11:00:00 Location: Hyderabad
[ { "code": null, "e": 1455, "s": 1187, "text": "The java.time package of Java8 provides a class named LocalDateTime is used to get the current value of local date and time. Using this in addition to date and time values you can also get other date and time fields, such as day-of-year, day-of-week and week-of-year." }, { "code": null, "e": 1622, "s": 1455, "text": "The java.sql.TimeStamp class provides a method with name toLocalDateTime() this method converts the current timestamp object to a LocalDateTime object and returns it." }, { "code": null, "e": 1663, "s": 1622, "text": "To convert date to LocalDateTime object." }, { "code": null, "e": 1738, "s": 1663, "text": "Create a Timestamp object from Date object using the getTime() method as −" }, { "code": null, "e": 1862, "s": 1738, "text": "Date date = rs.getDate(\"DispatchDate\");\n//Converting Date to Timestamp\nTimestamp timestamp = new Timestamp(date.getTime());" }, { "code": null, "e": 1956, "s": 1862, "text": "Now, convert the Timestamp object to LocalDateTime object using the toLocalDateTime() method." }, { "code": null, "e": 2139, "s": 1956, "text": "Time time = rs.getTime(\"DeliveryTime\");\n//Converting time to Timestamp\nTimestamp timestamp = new Timestamp(time.getTime());\n//Time stamp to LocalDateTime\ntimestamp.toLocalDateTime();" }, { "code": null, "e": 2236, "s": 2139, "text": "Let us create a table with name dispatches in MySQL database using CREATE statement as follows −" }, { "code": null, "e": 2406, "s": 2236, "text": "CREATE TABLE dispatches(\n ProductName VARCHAR(255),\n CustomerName VARCHAR(255),\n DispatchDate date,\n DeliveryTime time,\n Price INT,\n Location VARCHAR(255)\n);" }, { "code": null, "e": 2482, "s": 2406, "text": "Now, we will insert 2 records in dispatches table using INSERT statements −" }, { "code": null, "e": 2705, "s": 2482, "text": "insert into dispatches values('Key-Board', 'Raja', DATE('2019-09-01'), TIME('11:00:00'), 7000, 'Hyderabad');\ninsert into dispatches values('Earphones', 'Roja', DATE('2019-05-01'), TIME('11:00:00'), 2000, 'Vishakhapatnam');" }, { "code": null, "e": 2962, "s": 2705, "text": "Following JDBC program establishes connection with the database and retrieves the contents of the dispatches_data table and, converts the Date value (Dispatch_Date column) of the first record to LocalDateTime object and displays it along with its contents." }, { "code": null, "e": 4494, "s": 2962, "text": "import java.sql.Connection;\nimport java.sql.Date;\nimport java.sql.DriverManager;\nimport java.sql.ResultSet;\nimport java.sql.SQLException;\nimport java.sql.Statement;\nimport java.sql.Timestamp;\npublic class LocalDateTimeExample {\n public static void main(String args[]) throws SQLException {\n //Registering the Driver\n DriverManager.registerDriver(new com.mysql.jdbc.Driver());\n //Getting the connection\n String mysqlUrl = \"jdbc:mysql://localhost/mydatabase\";\n Connection con = DriverManager.getConnection(mysqlUrl, \"root\", \"password\");\n System.out.println(\"Connection established......\");\n //Retrieving values\n Statement stmt = con.createStatement();\n ResultSet rs = stmt.executeQuery(\"select * from dispatches\");\n rs.next();\n //Retrieving the Date from the table\n Date date = rs.getDate(\"DispatchDate\");\n //Converting Date to Timestamp\n Timestamp timestamp = new Timestamp(date.getTime());\n System.out.println(\"LocalDateTime value from date: \"+timestamp.toLocalDateTime());\n System.out.println(\"\");\n System.out.println(\"Contents of the first record: \");\n System.out.println(\"Product Name: \"+rs.getString(\"ProductName\"));\n System.out.println(\"Customer Name: \"+rs.getString(\"CustomerName\"));\n System.out.println(\"Dispatch Date: \"+rs.getDate(\"DispatchDate\"));\n System.out.println(\"Delivery Time: \"+ rs.getTime(\"DeliveryTime\"));\n System.out.println(\"Location: \"+rs.getString(\"Location\"));\n System.out.println();\n }\n}" }, { "code": null, "e": 4715, "s": 4494, "text": "Connection established......\nLocalDateTime value from date: 2019-09-01T00:00\nContents of the first record:\nProduct Name: Key-Board\nCustomer Name: Raja\nDispatch Date: 2019-09-01\nDelivery Time: 11:00:00\nLocation: Hyderabad" } ]
Java while loop with Examples
23 Jun, 2022 Java while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The while loop can be thought of as a repeating if statement. While loop in Java comes into use when we need to repeatedly execute a block of statements. The while loop is considered as a repeating if statement. If the number of iterations is not fixed, it is recommended to use the while loop. Syntax: while (test_expression) { // statements update_expression; } The various parts of the While loop are: 1. Test Expression: In this expression, we have to test the condition. If the condition evaluates to true then we will execute the body of the loop and go to update expression. Otherwise, we will exit from the while loop. Chapters descriptions off, selected captions settings, opens captions settings dialog captions off, selected English default, selected This is a modal window. Beginning of dialog window. Escape will cancel and close the window. End of dialog window. Example: i <= 10 2. Update Expression: After executing the loop body, this expression increments/decrements the loop variable by some value. Example: i++; How Does a While loop execute? Control falls into the while loop.The flow jumps to ConditionCondition is tested. If Condition yields true, the flow goes into the Body.If Condition yields false, the flow goes outside the loopThe statements inside the body of the loop get executed.Updation takes place.Control flows back to Step 2.The while loop has ended and the flow has gone outside. Control falls into the while loop. The flow jumps to Condition Condition is tested. If Condition yields true, the flow goes into the Body.If Condition yields false, the flow goes outside the loop If Condition yields true, the flow goes into the Body. If Condition yields false, the flow goes outside the loop The statements inside the body of the loop get executed. Updation takes place. Control flows back to Step 2. The while loop has ended and the flow has gone outside. Flowchart For while loop (Control Flow): Example 1: This program will try to print “Hello World” 5 times. Java // Java program to illustrate while loop. class whileLoopDemo { public static void main(String args[]) { // initialization expression int i = 1; // test expression while (i < 6) { System.out.println("Hello World"); // update expression i++; } }} Hello World Hello World Hello World Hello World Hello World Time Complexity: O(1) Auxiliary Space : O(1) Dry-Running Example 1: The program will execute in the following manner. 1. Program starts. 2. i is initialized with value 1. 3. Condition is checked. 1 < 6 yields true. 3.a) "Hello World" gets printed 1st time. 3.b) Updation is done. Now i = 2. 4. Condition is checked. 2 < 6 yields true. 4.a) "Hello World" gets printed 2nd time. 4.b) Updation is done. Now i = 3. 5. Condition is checked. 3 < 6 yields true. 5.a) "Hello World" gets printed 3rd time 5.b) Updation is done. Now i = 4. 6. Condition is checked. 4 < 6 yields true. 6.a) "Hello World" gets printed 4th time 6.b) Updation is done. Now i = 5. 7. Condition is checked. 5 < 6 yields true. 7.a) "Hello World" gets printed 5th time 7.b) Updation is done. Now i = 6. 8. Condition is checked. 6 < 6 yields false. 9. Flow goes outside the loop. Program terminates. Example 2: This program will find the summation of numbers from 1 to 10. Java // Java program to illustrate while loop class whileLoopDemo { public static void main(String args[]) { int x = 1, sum = 0; // Exit when x becomes greater than 4 while (x <= 10) { // summing up x sum = sum + x; // Increment the value of x for // next iteration x++; } System.out.println("Summation: " + sum); }} Summation: 55 Time Complexity: O(1) Auxiliary Space : O(1) 3. While Loop in Java (Core Java)| GeeksforGeeks - YouTubeGeeksforGeeks529K subscribers3. While Loop in Java (Core Java)| GeeksforGeeksWatch 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 / 16:07•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=xBJ44A1FCTE" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> Related Articles: Loops in JavaJava For loop with ExamplesJava do-while loop with ExamplesDifference between for and while loop in C, C++, JavaDifference between while and do-while loop in C, C++, Java Loops in Java Java For loop with Examples Java do-while loop with Examples Difference between for and while loop in C, C++, Java Difference between while and do-while loop in C, C++, Java nishkarshgandhi rishavnitro tarunkanade Java School Programming Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Split() String method in Java with examples Arrays.sort() in Java with examples Reverse a string in Java How to iterate any Map in Java Stream In Java Python Dictionary Reverse a string in Java Arrays in C/C++ Introduction To PYTHON Inheritance in C++
[ { "code": null, "e": 52, "s": 24, "text": "\n23 Jun, 2022" }, { "code": null, "e": 470, "s": 52, "text": "Java while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The while loop can be thought of as a repeating if statement. While loop in Java comes into use when we need to repeatedly execute a block of statements. The while loop is considered as a repeating if statement. If the number of iterations is not fixed, it is recommended to use the while loop." }, { "code": null, "e": 478, "s": 470, "text": "Syntax:" }, { "code": null, "e": 546, "s": 478, "text": "while (test_expression)\n{\n // statements\n \n update_expression;\n}" }, { "code": null, "e": 588, "s": 546, "text": "The various parts of the While loop are: " }, { "code": null, "e": 811, "s": 588, "text": "1. Test Expression: In this expression, we have to test the condition. If the condition evaluates to true then we will execute the body of the loop and go to update expression. Otherwise, we will exit from the while loop. " }, { "code": null, "e": 820, "s": 811, "text": "Chapters" }, { "code": null, "e": 847, "s": 820, "text": "descriptions off, selected" }, { "code": null, "e": 897, "s": 847, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 920, "s": 897, "text": "captions off, selected" }, { "code": null, "e": 928, "s": 920, "text": "English" }, { "code": null, "e": 946, "s": 928, "text": "default, selected" }, { "code": null, "e": 970, "s": 946, "text": "This is a modal window." }, { "code": null, "e": 1039, "s": 970, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 1061, "s": 1039, "text": "End of dialog window." }, { "code": null, "e": 1071, "s": 1061, "text": "Example: " }, { "code": null, "e": 1079, "s": 1071, "text": "i <= 10" }, { "code": null, "e": 1204, "s": 1079, "text": "2. Update Expression: After executing the loop body, this expression increments/decrements the loop variable by some value. " }, { "code": null, "e": 1214, "s": 1204, "text": "Example: " }, { "code": null, "e": 1219, "s": 1214, "text": "i++;" }, { "code": null, "e": 1251, "s": 1219, "text": "How Does a While loop execute? " }, { "code": null, "e": 1606, "s": 1251, "text": "Control falls into the while loop.The flow jumps to ConditionCondition is tested. If Condition yields true, the flow goes into the Body.If Condition yields false, the flow goes outside the loopThe statements inside the body of the loop get executed.Updation takes place.Control flows back to Step 2.The while loop has ended and the flow has gone outside." }, { "code": null, "e": 1641, "s": 1606, "text": "Control falls into the while loop." }, { "code": null, "e": 1669, "s": 1641, "text": "The flow jumps to Condition" }, { "code": null, "e": 1802, "s": 1669, "text": "Condition is tested. If Condition yields true, the flow goes into the Body.If Condition yields false, the flow goes outside the loop" }, { "code": null, "e": 1857, "s": 1802, "text": "If Condition yields true, the flow goes into the Body." }, { "code": null, "e": 1915, "s": 1857, "text": "If Condition yields false, the flow goes outside the loop" }, { "code": null, "e": 1972, "s": 1915, "text": "The statements inside the body of the loop get executed." }, { "code": null, "e": 1994, "s": 1972, "text": "Updation takes place." }, { "code": null, "e": 2024, "s": 1994, "text": "Control flows back to Step 2." }, { "code": null, "e": 2080, "s": 2024, "text": "The while loop has ended and the flow has gone outside." }, { "code": null, "e": 2123, "s": 2080, "text": "Flowchart For while loop (Control Flow): " }, { "code": null, "e": 2189, "s": 2123, "text": "Example 1: This program will try to print “Hello World” 5 times. " }, { "code": null, "e": 2194, "s": 2189, "text": "Java" }, { "code": "// Java program to illustrate while loop. class whileLoopDemo { public static void main(String args[]) { // initialization expression int i = 1; // test expression while (i < 6) { System.out.println(\"Hello World\"); // update expression i++; } }}", "e": 2519, "s": 2194, "text": null }, { "code": null, "e": 2582, "s": 2522, "text": "Hello World\nHello World\nHello World\nHello World\nHello World" }, { "code": null, "e": 2604, "s": 2582, "text": "Time Complexity: O(1)" }, { "code": null, "e": 2628, "s": 2604, "text": "Auxiliary Space : O(1) " }, { "code": null, "e": 2702, "s": 2628, "text": "Dry-Running Example 1: The program will execute in the following manner. " }, { "code": null, "e": 3472, "s": 2704, "text": "1. Program starts.\n2. i is initialized with value 1.\n3. Condition is checked. 1 < 6 yields true.\n 3.a) \"Hello World\" gets printed 1st time.\n 3.b) Updation is done. Now i = 2.\n4. Condition is checked. 2 < 6 yields true.\n 4.a) \"Hello World\" gets printed 2nd time.\n 4.b) Updation is done. Now i = 3.\n5. Condition is checked. 3 < 6 yields true.\n 5.a) \"Hello World\" gets printed 3rd time\n 5.b) Updation is done. Now i = 4.\n6. Condition is checked. 4 < 6 yields true.\n 6.a) \"Hello World\" gets printed 4th time\n 6.b) Updation is done. Now i = 5.\n7. Condition is checked. 5 < 6 yields true.\n 7.a) \"Hello World\" gets printed 5th time\n 7.b) Updation is done. Now i = 6.\n8. Condition is checked. 6 < 6 yields false.\n9. Flow goes outside the loop. Program terminates.\n " }, { "code": null, "e": 3546, "s": 3472, "text": "Example 2: This program will find the summation of numbers from 1 to 10. " }, { "code": null, "e": 3551, "s": 3546, "text": "Java" }, { "code": "// Java program to illustrate while loop class whileLoopDemo { public static void main(String args[]) { int x = 1, sum = 0; // Exit when x becomes greater than 4 while (x <= 10) { // summing up x sum = sum + x; // Increment the value of x for // next iteration x++; } System.out.println(\"Summation: \" + sum); }}", "e": 3964, "s": 3551, "text": null }, { "code": null, "e": 3978, "s": 3964, "text": "Summation: 55" }, { "code": null, "e": 4000, "s": 3978, "text": "Time Complexity: O(1)" }, { "code": null, "e": 4024, "s": 4000, "text": "Auxiliary Space : O(1) " }, { "code": null, "e": 4907, "s": 4024, "text": "3. While Loop in Java (Core Java)| GeeksforGeeks - YouTubeGeeksforGeeks529K subscribers3. While Loop in Java (Core Java)| GeeksforGeeksWatch 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 / 16:07•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=xBJ44A1FCTE\" 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": 4928, "s": 4909, "text": "Related Articles: " }, { "code": null, "e": 5114, "s": 4930, "text": "Loops in JavaJava For loop with ExamplesJava do-while loop with ExamplesDifference between for and while loop in C, C++, JavaDifference between while and do-while loop in C, C++, Java" }, { "code": null, "e": 5128, "s": 5114, "text": "Loops in Java" }, { "code": null, "e": 5156, "s": 5128, "text": "Java For loop with Examples" }, { "code": null, "e": 5189, "s": 5156, "text": "Java do-while loop with Examples" }, { "code": null, "e": 5243, "s": 5189, "text": "Difference between for and while loop in C, C++, Java" }, { "code": null, "e": 5302, "s": 5243, "text": "Difference between while and do-while loop in C, C++, Java" }, { "code": null, "e": 5320, "s": 5304, "text": "nishkarshgandhi" }, { "code": null, "e": 5332, "s": 5320, "text": "rishavnitro" }, { "code": null, "e": 5344, "s": 5332, "text": "tarunkanade" }, { "code": null, "e": 5349, "s": 5344, "text": "Java" }, { "code": null, "e": 5368, "s": 5349, "text": "School Programming" }, { "code": null, "e": 5373, "s": 5368, "text": "Java" }, { "code": null, "e": 5471, "s": 5373, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5515, "s": 5471, "text": "Split() String method in Java with examples" }, { "code": null, "e": 5551, "s": 5515, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 5576, "s": 5551, "text": "Reverse a string in Java" }, { "code": null, "e": 5607, "s": 5576, "text": "How to iterate any Map in Java" }, { "code": null, "e": 5622, "s": 5607, "text": "Stream In Java" }, { "code": null, "e": 5640, "s": 5622, "text": "Python Dictionary" }, { "code": null, "e": 5665, "s": 5640, "text": "Reverse a string in Java" }, { "code": null, "e": 5681, "s": 5665, "text": "Arrays in C/C++" }, { "code": null, "e": 5704, "s": 5681, "text": "Introduction To PYTHON" } ]
EditText widget in Android using Java with Examples
24 Sep, 2021 Widget refers to the elements of the UI (User Interface) that helps user interacts with the Android App. Edittext is one of many such widgets which can be used to retrieve text data from user. Edittext refers to the widget that displays an empty textfield in which a user can enter the required text and this text is further used inside our application. Class Syntax: public class EditText extends TextView Class Hierarchy: java.lang.Object ↳android.view.View ↳ android.widget.TextView ↳ android.widget.EditText Syntax: <SomeLayout> . . <Edittext android:SomeAttribute1 = "Value of attribute1" android:SomeAttribute2 = "Value of attribute2" . . android:SomeAttributeN = "Value of attributeN"/> . . </SomeLayout> Here the layout can be any layout like Relative, Linear, etc (Refer this article to learn more about layouts). And the attributes can be many among the table given below in this article. Example: <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" android:gravity="center">> <Edittext android:id="@+id/text_view_id" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="GeeksforGeeks" /> <Button android:id="@+id/button_id" android:layout_width="300dp" android:layout_height="40dp" android:layout_below="@+id/edittext_id" android:layout_marginTop="20dp" android:text="Submit" android:textColor="#fff" android:background="@color/colorPrimary"/> </RelativeLayout> How to include a Edittext in an Android App: First of all, create a new Android app, or take an existing app to edit it. In both the case, there must be an XML layout activity file and a Java class file linked to this activity. Open the Activity file and include a Edittext field in the layout (activity_main.xml) file of the activity and also add a Button in activity_main.xml file too. Now in the Java file, link this layout file with the below code: @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } where activity_main is the name of the layout file to be attached. Now we will add code in MainActivity.java file to make our layout interactive or responsive. Our application will generate a toast on clicking the button with the text “Welcome to GeeksforGeeks [Name as entered by user]“ The complete code of the layout file and the Java file is given below. Below is the implementation of the above approach: Filename: activity_main.xml XML <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" android:gravity="center"> <EditText android:id="@+id/edittext_id" android:layout_width="300dp" android:layout_height="40dp" android:hint="Enter your Name"/> <Button android:id="@+id/button_id" android:layout_width="300dp" android:layout_height="40dp" android:layout_below="@+id/edittext_id" android:layout_marginTop="20dp" android:text="Submit" android:textColor="#fff" android:background="@color/colorPrimary"/> </RelativeLayout> Filename: MainActivity.java Java package com.project.edittext; import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.Toast; public class MainActivity extends AppCompatActivity { private EditText editText; private Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); editText = (EditText)findViewById(R.id.edittext_id); button = (Button)findViewById(R.id.button_id); button.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { String name = editText.getText() .toString(); Toast.makeText(MainActivity.this, "Welcome to GeeksforGeeks " + name, Toast.LENGTH_SHORT) .show(); } }); }} Output: Upon starting of the App and entering the name in EditText. The name in the EditText is then displayed: sagartomar9927 android Android-View Android Java Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Add Views Dynamically and Store Data in Arraylist in Android? Android RecyclerView in Kotlin Broadcast Receiver in Android With Example Android SDK and it's Components Flutter - Custom Bottom Navigation Bar Arrays in Java Split() String method in Java with examples Arrays.sort() in Java with examples Reverse a string in Java Object Oriented Programming (OOPs) Concept in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Sep, 2021" }, { "code": null, "e": 221, "s": 28, "text": "Widget refers to the elements of the UI (User Interface) that helps user interacts with the Android App. Edittext is one of many such widgets which can be used to retrieve text data from user." }, { "code": null, "e": 382, "s": 221, "text": "Edittext refers to the widget that displays an empty textfield in which a user can enter the required text and this text is further used inside our application." }, { "code": null, "e": 397, "s": 382, "text": "Class Syntax: " }, { "code": null, "e": 436, "s": 397, "text": "public class EditText\nextends TextView" }, { "code": null, "e": 454, "s": 436, "text": "Class Hierarchy: " }, { "code": null, "e": 559, "s": 454, "text": "java.lang.Object\n ↳android.view.View\n ↳ android.widget.TextView\n ↳ android.widget.EditText" }, { "code": null, "e": 568, "s": 559, "text": "Syntax: " }, { "code": null, "e": 820, "s": 568, "text": "<SomeLayout>\n .\n .\n <Edittext\n android:SomeAttribute1 = \"Value of attribute1\"\n android:SomeAttribute2 = \"Value of attribute2\"\n .\n .\n android:SomeAttributeN = \"Value of attributeN\"/>\n .\n .\n</SomeLayout>" }, { "code": null, "e": 1007, "s": 820, "text": "Here the layout can be any layout like Relative, Linear, etc (Refer this article to learn more about layouts). And the attributes can be many among the table given below in this article." }, { "code": null, "e": 1017, "s": 1007, "text": "Example: " }, { "code": null, "e": 1781, "s": 1017, "text": " <RelativeLayout\n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\"\n android:gravity=\"center\">>\n\n <Edittext\n android:id=\"@+id/text_view_id\"\n android:layout_height=\"wrap_content\"\n android:layout_width=\"wrap_content\"\n android:text=\"GeeksforGeeks\" />\n\n <Button\n android:id=\"@+id/button_id\"\n android:layout_width=\"300dp\"\n android:layout_height=\"40dp\"\n android:layout_below=\"@+id/edittext_id\"\n android:layout_marginTop=\"20dp\"\n android:text=\"Submit\"\n android:textColor=\"#fff\"\n android:background=\"@color/colorPrimary\"/>\n\n </RelativeLayout>" }, { "code": null, "e": 1827, "s": 1781, "text": "How to include a Edittext in an Android App: " }, { "code": null, "e": 2010, "s": 1827, "text": "First of all, create a new Android app, or take an existing app to edit it. In both the case, there must be an XML layout activity file and a Java class file linked to this activity." }, { "code": null, "e": 2170, "s": 2010, "text": "Open the Activity file and include a Edittext field in the layout (activity_main.xml) file of the activity and also add a Button in activity_main.xml file too." }, { "code": null, "e": 2236, "s": 2170, "text": "Now in the Java file, link this layout file with the below code: " }, { "code": null, "e": 2385, "s": 2236, "text": "@Override\nprotected void onCreate(Bundle savedInstanceState)\n{\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n}" }, { "code": null, "e": 2452, "s": 2385, "text": "where activity_main is the name of the layout file to be attached." }, { "code": null, "e": 2673, "s": 2452, "text": "Now we will add code in MainActivity.java file to make our layout interactive or responsive. Our application will generate a toast on clicking the button with the text “Welcome to GeeksforGeeks [Name as entered by user]“" }, { "code": null, "e": 2744, "s": 2673, "text": "The complete code of the layout file and the Java file is given below." }, { "code": null, "e": 2796, "s": 2744, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 2824, "s": 2796, "text": "Filename: activity_main.xml" }, { "code": null, "e": 2828, "s": 2824, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?> <RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\" android:gravity=\"center\"> <EditText android:id=\"@+id/edittext_id\" android:layout_width=\"300dp\" android:layout_height=\"40dp\" android:hint=\"Enter your Name\"/> <Button android:id=\"@+id/button_id\" android:layout_width=\"300dp\" android:layout_height=\"40dp\" android:layout_below=\"@+id/edittext_id\" android:layout_marginTop=\"20dp\" android:text=\"Submit\" android:textColor=\"#fff\" android:background=\"@color/colorPrimary\"/> </RelativeLayout>", "e": 3688, "s": 2828, "text": null }, { "code": null, "e": 3716, "s": 3688, "text": "Filename: MainActivity.java" }, { "code": null, "e": 3721, "s": 3716, "text": "Java" }, { "code": "package com.project.edittext; import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.Toast; public class MainActivity extends AppCompatActivity { private EditText editText; private Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); editText = (EditText)findViewById(R.id.edittext_id); button = (Button)findViewById(R.id.button_id); button.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { String name = editText.getText() .toString(); Toast.makeText(MainActivity.this, \"Welcome to GeeksforGeeks \" + name, Toast.LENGTH_SHORT) .show(); } }); }}", "e": 4912, "s": 3721, "text": null }, { "code": null, "e": 5025, "s": 4912, "text": "Output: Upon starting of the App and entering the name in EditText. The name in the EditText is then displayed: " }, { "code": null, "e": 5042, "s": 5027, "text": "sagartomar9927" }, { "code": null, "e": 5050, "s": 5042, "text": "android" }, { "code": null, "e": 5063, "s": 5050, "text": "Android-View" }, { "code": null, "e": 5071, "s": 5063, "text": "Android" }, { "code": null, "e": 5076, "s": 5071, "text": "Java" }, { "code": null, "e": 5081, "s": 5076, "text": "Java" }, { "code": null, "e": 5089, "s": 5081, "text": "Android" }, { "code": null, "e": 5187, "s": 5089, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5256, "s": 5187, "text": "How to Add Views Dynamically and Store Data in Arraylist in Android?" }, { "code": null, "e": 5287, "s": 5256, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 5330, "s": 5287, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 5362, "s": 5330, "text": "Android SDK and it's Components" }, { "code": null, "e": 5401, "s": 5362, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 5416, "s": 5401, "text": "Arrays in Java" }, { "code": null, "e": 5460, "s": 5416, "text": "Split() String method in Java with examples" }, { "code": null, "e": 5496, "s": 5460, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 5521, "s": 5496, "text": "Reverse a string in Java" } ]
Transition diagram for Identifiers in Compiler Design
21 Nov, 2019 Transition diagram is a special kind of flowchart for language analysis. In transition diagram the boxes of flowchart are drawn as circle and called as states. States are connected by arrows called as edges. The label or weight on edge indicates the input character that can appear after that state. Transition diagram of identifier is given below: This transition diagram for identifier reading first letter and after that letter or digit until the next input character is delimiter for identifier, means the character that is neither letter nor digit. To turn up the transition diagram into a program we construct the program segment code for each state of transition diagram. Program segment code for each state is given below: State-0: C=GETCHAR(); if LETTER(C) then goto State 1 else FAIL() State-1: C=GETCHAR(); if LETTER(C) OR DIGIT(C) then goto State 1 else if DELIMITER(C) then goto State 2 else FAIL() State-2: RETRACT(); RETURN(ID, INSTALL()) Where,Next character for input buffer we use GETCHAR() which return next character.LETTER(C) is a procedure which returns the true value if and only if C is a letter.FAIL(C) is a routine which RETRACT the look ahead pointer and start up the next transition diagram otherwise call error routine.DIGIT(C) is a procedure which returns the true value if and only if C is a digit.DELIMITER(C) is a procedure which returns the true value if and only if C Is a character that could follow the identifier for example blank symbol, arithmetic, logical operator, left parenthesis, right parenthesis, +, :, ; etc.Because DELIMITER is not part of identifier therefore we must RETRACT the look ahead pointer one character for this purpose we use the RETRACT() procedure .Because identifier has a value so to install the value of identifier in symbol table we use INSTALL() procedure. Compiler Design Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Directed Acyclic graph in Compiler Design (with examples) Type Checking in Compiler Design Data flow analysis in Compiler S - attributed and L - attributed SDTs in Syntax directed translation Runtime Environments in Compiler Design Compiler construction tools Basic Blocks in Compiler Design Token, Patterns, and Lexems Compiler Design - Variants of Syntax Tree Loop Optimization in Compiler Design
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Nov, 2019" }, { "code": null, "e": 328, "s": 28, "text": "Transition diagram is a special kind of flowchart for language analysis. In transition diagram the boxes of flowchart are drawn as circle and called as states. States are connected by arrows called as edges. The label or weight on edge indicates the input character that can appear after that state." }, { "code": null, "e": 377, "s": 328, "text": "Transition diagram of identifier is given below:" }, { "code": null, "e": 707, "s": 377, "text": "This transition diagram for identifier reading first letter and after that letter or digit until the next input character is delimiter for identifier, means the character that is neither letter nor digit. To turn up the transition diagram into a program we construct the program segment code for each state of transition diagram." }, { "code": null, "e": 759, "s": 707, "text": "Program segment code for each state is given below:" }, { "code": null, "e": 768, "s": 759, "text": "State-0:" }, { "code": null, "e": 825, "s": 768, "text": "C=GETCHAR();\nif LETTER(C) then goto State 1\nelse FAIL() " }, { "code": null, "e": 834, "s": 825, "text": "State-1:" }, { "code": null, "e": 942, "s": 834, "text": "C=GETCHAR();\nif LETTER(C) OR DIGIT(C) then goto State 1\nelse if DELIMITER(C) then goto State 2\nelse FAIL() " }, { "code": null, "e": 951, "s": 942, "text": "State-2:" }, { "code": null, "e": 984, "s": 951, "text": "RETRACT();\nRETURN(ID, INSTALL())" }, { "code": null, "e": 1855, "s": 984, "text": "Where,Next character for input buffer we use GETCHAR() which return next character.LETTER(C) is a procedure which returns the true value if and only if C is a letter.FAIL(C) is a routine which RETRACT the look ahead pointer and start up the next transition diagram otherwise call error routine.DIGIT(C) is a procedure which returns the true value if and only if C is a digit.DELIMITER(C) is a procedure which returns the true value if and only if C Is a character that could follow the identifier for example blank symbol, arithmetic, logical operator, left parenthesis, right parenthesis, +, :, ; etc.Because DELIMITER is not part of identifier therefore we must RETRACT the look ahead pointer one character for this purpose we use the RETRACT() procedure .Because identifier has a value so to install the value of identifier in symbol table we use INSTALL() procedure." }, { "code": null, "e": 1871, "s": 1855, "text": "Compiler Design" }, { "code": null, "e": 1969, "s": 1871, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2027, "s": 1969, "text": "Directed Acyclic graph in Compiler Design (with examples)" }, { "code": null, "e": 2060, "s": 2027, "text": "Type Checking in Compiler Design" }, { "code": null, "e": 2091, "s": 2060, "text": "Data flow analysis in Compiler" }, { "code": null, "e": 2161, "s": 2091, "text": "S - attributed and L - attributed SDTs in Syntax directed translation" }, { "code": null, "e": 2201, "s": 2161, "text": "Runtime Environments in Compiler Design" }, { "code": null, "e": 2229, "s": 2201, "text": "Compiler construction tools" }, { "code": null, "e": 2261, "s": 2229, "text": "Basic Blocks in Compiler Design" }, { "code": null, "e": 2289, "s": 2261, "text": "Token, Patterns, and Lexems" }, { "code": null, "e": 2331, "s": 2289, "text": "Compiler Design - Variants of Syntax Tree" } ]
Python | Inverse Sorting String
11 May, 2020 Sometimes, while participating in a competitive programming test, we can be encountered with a problem in which we require to sort a pair in opposite orders by indices. This particular article focuses on solving a problem in which we require to sort the number in descending order and then the String in increasing order. This is the type of problem which is common in the sorting of pairs. Let’s discuss a way in which this can be solved. Method : Using sorted() + lambdaThe combination of these functions can be used to perform this task. In these, we pass to lambda function the negative of the values so that the increasing order of number is evaluated as decreasing and hence a successful hack to perform this task. # Python3 code to demonstrate working of# Inverse sorting String, Integer tuple list# Using sorted() + lambda # initializing listtest_list = [("Geeks", 5), ("For", 3), ("Geeks", 6), ("Is", 5), ("Best", 7 ), ("For", 5), ("CS", 3)] # printing original listprint("The original list is : " + str(test_list)) # Inverse sorting String, Integer tuple list# Using sorted() + lambdares = sorted(test_list, key = lambda sub: (-sub[1], sub[0])) # printing result print("The list after inverse sorted tuple elements : " + str(res)) The original list is : [(‘Geeks’, 5), (‘For’, 3), (‘Geeks’, 6), (‘Is’, 5), (‘Best’, 7), (‘For’, 5), (‘CS’, 3)]The list after inverse sorted tuple elements : [(‘Best’, 7), (‘Geeks’, 6), (‘For’, 5), (‘Geeks’, 5), (‘Is’, 5), (‘CS’, 3), (‘For’, 3)] Python list-programs Python-sort Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Create a directory in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n11 May, 2020" }, { "code": null, "e": 468, "s": 28, "text": "Sometimes, while participating in a competitive programming test, we can be encountered with a problem in which we require to sort a pair in opposite orders by indices. This particular article focuses on solving a problem in which we require to sort the number in descending order and then the String in increasing order. This is the type of problem which is common in the sorting of pairs. Let’s discuss a way in which this can be solved." }, { "code": null, "e": 749, "s": 468, "text": "Method : Using sorted() + lambdaThe combination of these functions can be used to perform this task. In these, we pass to lambda function the negative of the values so that the increasing order of number is evaluated as decreasing and hence a successful hack to perform this task." }, { "code": "# Python3 code to demonstrate working of# Inverse sorting String, Integer tuple list# Using sorted() + lambda # initializing listtest_list = [(\"Geeks\", 5), (\"For\", 3), (\"Geeks\", 6), (\"Is\", 5), (\"Best\", 7 ), (\"For\", 5), (\"CS\", 3)] # printing original listprint(\"The original list is : \" + str(test_list)) # Inverse sorting String, Integer tuple list# Using sorted() + lambdares = sorted(test_list, key = lambda sub: (-sub[1], sub[0])) # printing result print(\"The list after inverse sorted tuple elements : \" + str(res))", "e": 1286, "s": 749, "text": null }, { "code": null, "e": 1531, "s": 1286, "text": "The original list is : [(‘Geeks’, 5), (‘For’, 3), (‘Geeks’, 6), (‘Is’, 5), (‘Best’, 7), (‘For’, 5), (‘CS’, 3)]The list after inverse sorted tuple elements : [(‘Best’, 7), (‘Geeks’, 6), (‘For’, 5), (‘Geeks’, 5), (‘Is’, 5), (‘CS’, 3), (‘For’, 3)]" }, { "code": null, "e": 1552, "s": 1531, "text": "Python list-programs" }, { "code": null, "e": 1564, "s": 1552, "text": "Python-sort" }, { "code": null, "e": 1571, "s": 1564, "text": "Python" }, { "code": null, "e": 1669, "s": 1571, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1701, "s": 1669, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1728, "s": 1701, "text": "Python Classes and Objects" }, { "code": null, "e": 1749, "s": 1728, "text": "Python OOPs Concepts" }, { "code": null, "e": 1772, "s": 1749, "text": "Introduction To PYTHON" }, { "code": null, "e": 1828, "s": 1772, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 1859, "s": 1828, "text": "Python | os.path.join() method" }, { "code": null, "e": 1901, "s": 1859, "text": "Check if element exists in list in Python" }, { "code": null, "e": 1943, "s": 1901, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 1982, "s": 1943, "text": "Python | Get unique values from a list" } ]
Constructor newInstance() method in Java with Examples
27 Nov, 2019 The newInstance() method of a Constructor class is used to create and initialize a new instance of this constructor, with the initialization parameters passed as parameter to this method. Each parameter is unwrapped to match primitive formal parameters, and both primitive and reference parameters are subject to method invocation conversions as necessary. If the number of formal parameters of the constructor is 0, the supplied parameter is of length 0 or null. If the constructor completes normally, returns the newly created and initialized instance. Syntax: public T newInstance(Object... initargs) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException Parameters: This method accepts initargs as the parameter which is an array of objects to be passed as arguments to the constructor call. The values of primitive types are wrapped in a wrapper object of the appropriate type (e.g. float in Float). Return value: This method returns a new object created by calling the constructor this object represents. Exception: This method throws following Exceptions: IllegalAccessException: if this Constructor object is enforcing Java language access control and the underlying constructor is inaccessible. IllegalArgumentException: if the number of actual and formal parameters differ; if an unwrapping conversion for primitive arguments fails; or if, after possible unwrapping, a parameter value cannot be converted to the corresponding formal parameter type by a method invocation conversion; if this constructor pertains to an enum type. InstantiationException: if the class that declares the underlying constructor represents an abstract class. InvocationTargetException: if the underlying constructor throws an exception. ExceptionInInitializerError: if the initialization provoked by this method fails. Below programs illustrate the newInstance() method:Program 1: // Java program to demonstrate// Constructor.newInstance() method import java.lang.reflect.Constructor;import java.lang.reflect.InvocationTargetException; public class GFG { public static void main(String... args) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { // An array of constructor Constructor[] constructor = Test.class.getConstructors(); // Apply newInstance method Test sampleObject = (Test)constructor[0].newInstance(); System.out.println(sampleObject.value); }} class Test { String value; public Test() { System.out.println("New Instance is created"); value = "New Instance"; }} Output: New Instance is created New Instance Program 2: // Java program to demonstrate// Constructor.newInstance() method import java.lang.reflect.Constructor;import java.lang.reflect.InvocationTargetException; public class GFG { public static void main(String... args) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { // an array of constructor Constructor[] constructor = Test.class.getConstructors(); // apply newInstance method Test sampleObject = (Test)constructor[0] .newInstance("New Field"); System.out.println(sampleObject.getField()); }} class Test { private String field; public Test(String field) { this.field = field; } public String getField() { return field; } public void setField(String field) { this.field = field; }} Output: New Field References: https://docs.oracle.com/javase/10/docs/api/java/lang/reflect/Constructor.html#newInstance(java.lang.Object...) Java-Constructors Java-Functions java-lang-reflect-package 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 Nov, 2019" }, { "code": null, "e": 385, "s": 28, "text": "The newInstance() method of a Constructor class is used to create and initialize a new instance of this constructor, with the initialization parameters passed as parameter to this method. Each parameter is unwrapped to match primitive formal parameters, and both primitive and reference parameters are subject to method invocation conversions as necessary." }, { "code": null, "e": 583, "s": 385, "text": "If the number of formal parameters of the constructor is 0, the supplied parameter is of length 0 or null. If the constructor completes normally, returns the newly created and initialized instance." }, { "code": null, "e": 591, "s": 583, "text": "Syntax:" }, { "code": null, "e": 751, "s": 591, "text": "public T newInstance(Object... initargs)\n throws InstantiationException, IllegalAccessException,\n IllegalArgumentException, InvocationTargetException\n" }, { "code": null, "e": 998, "s": 751, "text": "Parameters: This method accepts initargs as the parameter which is an array of objects to be passed as arguments to the constructor call. The values of primitive types are wrapped in a wrapper object of the appropriate type (e.g. float in Float)." }, { "code": null, "e": 1104, "s": 998, "text": "Return value: This method returns a new object created by calling the constructor this object represents." }, { "code": null, "e": 1156, "s": 1104, "text": "Exception: This method throws following Exceptions:" }, { "code": null, "e": 1297, "s": 1156, "text": "IllegalAccessException: if this Constructor object is enforcing Java language access control and the underlying constructor is inaccessible." }, { "code": null, "e": 1632, "s": 1297, "text": "IllegalArgumentException: if the number of actual and formal parameters differ; if an unwrapping conversion for primitive arguments fails; or if, after possible unwrapping, a parameter value cannot be converted to the corresponding formal parameter type by a method invocation conversion; if this constructor pertains to an enum type." }, { "code": null, "e": 1740, "s": 1632, "text": "InstantiationException: if the class that declares the underlying constructor represents an abstract class." }, { "code": null, "e": 1818, "s": 1740, "text": "InvocationTargetException: if the underlying constructor throws an exception." }, { "code": null, "e": 1900, "s": 1818, "text": "ExceptionInInitializerError: if the initialization provoked by this method fails." }, { "code": null, "e": 1962, "s": 1900, "text": "Below programs illustrate the newInstance() method:Program 1:" }, { "code": "// Java program to demonstrate// Constructor.newInstance() method import java.lang.reflect.Constructor;import java.lang.reflect.InvocationTargetException; public class GFG { public static void main(String... args) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { // An array of constructor Constructor[] constructor = Test.class.getConstructors(); // Apply newInstance method Test sampleObject = (Test)constructor[0].newInstance(); System.out.println(sampleObject.value); }} class Test { String value; public Test() { System.out.println(\"New Instance is created\"); value = \"New Instance\"; }}", "e": 2770, "s": 1962, "text": null }, { "code": null, "e": 2778, "s": 2770, "text": "Output:" }, { "code": null, "e": 2816, "s": 2778, "text": "New Instance is created\nNew Instance\n" }, { "code": null, "e": 2827, "s": 2816, "text": "Program 2:" }, { "code": "// Java program to demonstrate// Constructor.newInstance() method import java.lang.reflect.Constructor;import java.lang.reflect.InvocationTargetException; public class GFG { public static void main(String... args) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { // an array of constructor Constructor[] constructor = Test.class.getConstructors(); // apply newInstance method Test sampleObject = (Test)constructor[0] .newInstance(\"New Field\"); System.out.println(sampleObject.getField()); }} class Test { private String field; public Test(String field) { this.field = field; } public String getField() { return field; } public void setField(String field) { this.field = field; }}", "e": 3769, "s": 2827, "text": null }, { "code": null, "e": 3777, "s": 3769, "text": "Output:" }, { "code": null, "e": 3788, "s": 3777, "text": "New Field\n" }, { "code": null, "e": 3911, "s": 3788, "text": "References: https://docs.oracle.com/javase/10/docs/api/java/lang/reflect/Constructor.html#newInstance(java.lang.Object...)" }, { "code": null, "e": 3929, "s": 3911, "text": "Java-Constructors" }, { "code": null, "e": 3944, "s": 3929, "text": "Java-Functions" }, { "code": null, "e": 3970, "s": 3944, "text": "java-lang-reflect-package" }, { "code": null, "e": 3975, "s": 3970, "text": "Java" }, { "code": null, "e": 3980, "s": 3975, "text": "Java" } ]
Chinese Remainder Theorem | Set 2 (Inverse Modulo based Implementation)
07 Apr, 2022 We are given two arrays num[0..k-1] and rem[0..k-1]. In num[0..k-1], every pair is coprime (gcd for every pair is 1). We need to find minimum positive number x such that: x % num[0] = rem[0], x % num[1] = rem[1], ....................... x % num[k-1] = rem[k-1] Example: Input: num[] = {3, 4, 5}, rem[] = {2, 3, 1} Output: 11 Explanation: 11 is the smallest number such that: (1) When we divide it by 3, we get remainder 2. (2) When we divide it by 4, we get remainder 3. (3) When we divide it by 5, we get remainder 1. We strongly recommend to refer below post as a prerequisite for this. Chinese Remainder Theorem | Set 1 (Introduction)We have discussed a Naive solution to find minimum x. In this article, an efficient solution to find x is discussed.The solution is based on below formula. x = ( ∑ (rem[i]*pp[i]*inv[i]) ) % prod Where 0 <= i <= n-1 rem[i] is given array of remainders prod is product of all given numbers prod = num[0] * num[1] * ... * num[k-1] pp[i] is product of all divided by num[i] pp[i] = prod / num[i] inv[i] = Modular Multiplicative Inverse of pp[i] with respect to num[i] Example: Let us take below example to understand the solution num[] = {3, 4, 5}, rem[] = {2, 3, 1} prod = 60 pp[] = {20, 15, 12} inv[] = {2, 3, 3} // (20*2)%3 = 1, (15*3)%4 = 1 // (12*3)%5 = 1 x = (rem[0]*pp[0]*inv[0] + rem[1]*pp[1]*inv[1] + rem[2]*pp[2]*inv[2]) % prod = (2*20*2 + 3*15*3 + 1*12*3) % 60 = (80 + 135 + 36) % 60 = 11 Refer this for nice visual explanation of above formula. Below is the implementation of above formula. We can use Extended Euclid based method discussed here to find inverse modulo. C++ Java Python3 C# PHP Javascript // A C++ program to demonstrate// working of Chinese remainder// Theorem#include <bits/stdc++.h>using namespace std; // Returns modulo inverse of a// with respect to m using// extended Euclid Algorithm.// Refer below post for details:// https://www.geeksforgeeks.org/// multiplicative-inverse-under-modulo-m/int inv(int a, int m){ int m0 = m, t, q; int x0 = 0, x1 = 1; if (m == 1) return 0; // Apply extended Euclid Algorithm while (a > 1) { // q is quotient q = a / m; t = m; // m is remainder now, process same as // euclid's algo m = a % m, a = t; t = x0; x0 = x1 - q * x0; x1 = t; } // Make x1 positive if (x1 < 0) x1 += m0; return x1;} // k is size of num[] and rem[]. Returns the smallest// number x such that:// x % num[0] = rem[0],// x % num[1] = rem[1],// ..................// x % num[k-2] = rem[k-1]// Assumption: Numbers in num[] are pairwise coprime// (gcd for every pair is 1)int findMinX(int num[], int rem[], int k){ // Compute product of all numbers int prod = 1; for (int i = 0; i < k; i++) prod *= num[i]; // Initialize result int result = 0; // Apply above formula for (int i = 0; i < k; i++) { int pp = prod / num[i]; result += rem[i] * inv(pp, num[i]) * pp; } return result % prod;} // Driver methodint main(void){ int num[] = { 3, 4, 5 }; int rem[] = { 2, 3, 1 }; int k = sizeof(num) / sizeof(num[0]); cout << "x is " << findMinX(num, rem, k); return 0;} // A Java program to demonstrate// working of Chinese remainder// Theoremimport java.io.*; class GFG { // Returns modulo inverse of a // with respect to m using extended // Euclid Algorithm. Refer below post for details: // https://www.geeksforgeeks.org/ // multiplicative-inverse-under-modulo-m/ static int inv(int a, int m) { int m0 = m, t, q; int x0 = 0, x1 = 1; if (m == 1) return 0; // Apply extended Euclid Algorithm while (a > 1) { // q is quotient q = a / m; t = m; // m is remainder now, process // same as euclid's algo m = a % m; a = t; t = x0; x0 = x1 - q * x0; x1 = t; } // Make x1 positive if (x1 < 0) x1 += m0; return x1; } // k is size of num[] and rem[]. // Returns the smallest number // x such that: // x % num[0] = rem[0], // x % num[1] = rem[1], // .................. // x % num[k-2] = rem[k-1] // Assumption: Numbers in num[] are pairwise // coprime (gcd for every pair is 1) static int findMinX(int num[], int rem[], int k) { // Compute product of all numbers int prod = 1; for (int i = 0; i < k; i++) prod *= num[i]; // Initialize result int result = 0; // Apply above formula for (int i = 0; i < k; i++) { int pp = prod / num[i]; result += rem[i] * inv(pp, num[i]) * pp; } return result % prod; } // Driver method public static void main(String args[]) { int num[] = { 3, 4, 5 }; int rem[] = { 2, 3, 1 }; int k = num.length; System.out.println("x is " + findMinX(num, rem, k)); }} // This code is contributed by nikita Tiwari. # A Python3 program to demonstrate# working of Chinese remainder# Theorem # Returns modulo inverse of a with# respect to m using extended# Euclid Algorithm. Refer below# post for details:# https://www.geeksforgeeks.org/# multiplicative-inverse-under-modulo-m/def inv(a, m) : m0 = m x0 = 0 x1 = 1 if (m == 1) : return 0 # Apply extended Euclid Algorithm while (a > 1) : # q is quotient q = a // m t = m # m is remainder now, process # same as euclid's algo m = a % m a = t t = x0 x0 = x1 - q * x0 x1 = t # Make x1 positive if (x1 < 0) : x1 = x1 + m0 return x1 # k is size of num[] and rem[].# Returns the smallest# number x such that:# x % num[0] = rem[0],# x % num[1] = rem[1],# ..................# x % num[k-2] = rem[k-1]# Assumption: Numbers in num[]# are pairwise coprime# (gcd for every pair is 1)def findMinX(num, rem, k) : # Compute product of all numbers prod = 1 for i in range(0, k) : prod = prod * num[i] # Initialize result result = 0 # Apply above formula for i in range(0,k): pp = prod // num[i] result = result + rem[i] * inv(pp, num[i]) * pp return result % prod # Driver methodnum = [3, 4, 5]rem = [2, 3, 1]k = len(num)print( "x is " , findMinX(num, rem, k)) # This code is contributed by Nikita Tiwari. // A C# program to demonstrate// working of Chinese remainder// Theoremusing System; class GFG{ // Returns modulo inverse of // 'a' with respect to 'm' // using extended Euclid Algorithm. // Refer below post for details: // https://www.geeksforgeeks.org/ // multiplicative-inverse-under-modulo-m/ static int inv(int a, int m) { int m0 = m, t, q; int x0 = 0, x1 = 1; if (m == 1) return 0; // Apply extended // Euclid Algorithm while (a > 1) { // q is quotient q = a / m; t = m; // m is remainder now, // process same as // euclid's algo m = a % m; a = t; t = x0; x0 = x1 - q * x0; x1 = t; } // Make x1 positive if (x1 < 0) x1 += m0; return x1; } // k is size of num[] and rem[]. // Returns the smallest number // x such that: // x % num[0] = rem[0], // x % num[1] = rem[1], // .................. // x % num[k-2] = rem[k-1] // Assumption: Numbers in num[] // are pairwise coprime (gcd // for every pair is 1) static int findMinX(int []num, int []rem, int k) { // Compute product // of all numbers int prod = 1; for (int i = 0; i < k; i++) prod *= num[i]; // Initialize result int result = 0; // Apply above formula for (int i = 0; i < k; i++) { int pp = prod / num[i]; result += rem[i] * inv(pp, num[i]) * pp; } return result % prod; } // Driver Code static public void Main () { int []num = {3, 4, 5}; int []rem = {2, 3, 1}; int k = num.Length; Console.WriteLine("x is " + findMinX(num, rem, k)); }} // This code is contributed// by ajit <?php// PHP program to demonstrate working// of Chinese remainder Theorem // Returns modulo inverse of a with// respect to m using extended Euclid// Algorithm. Refer below post for details:// https://www.geeksforgeeks.org/// multiplicative-inverse-under-modulo-m/function inv($a, $m){ $m0 = $m; $x0 = 0; $x1 = 1; if ($m == 1) return 0; // Apply extended Euclid Algorithm while ($a > 1) { // q is quotient $q = (int)($a / $m); $t = $m; // m is remainder now, process // same as euclid's algo $m = $a % $m; $a = $t; $t = $x0; $x0 = $x1 - $q * $x0; $x1 = $t; } // Make x1 positive if ($x1 < 0) $x1 += $m0; return $x1;} // k is size of num[] and rem[].// Returns the smallest// number x such that:// x % num[0] = rem[0],// x % num[1] = rem[1],// ..................// x % num[k-2] = rem[k-1]// Assumption: Numbers in num[]// are pairwise coprime (gcd for// every pair is 1)function findMinX($num, $rem, $k){ // Compute product of all numbers $prod = 1; for ($i = 0; $i < $k; $i++) $prod *= $num[$i]; // Initialize result $result = 0; // Apply above formula for ($i = 0; $i < $k; $i++) { $pp = (int)$prod / $num[$i]; $result += $rem[$i] * inv($pp, $num[$i]) * $pp; } return $result % $prod;} // Driver Code$num = array(3, 4, 5);$rem = array(2, 3, 1);$k = sizeof($num);echo "x is ". findMinX($num, $rem, $k); // This code is contributed by mits?> <script>// Javascript program to demonstrate working// of Chinese remainder Theorem // Returns modulo inverse of a with// respect to m using extended Euclid// Algorithm. Refer below post for details:// https://www.geeksforgeeks.org/// multiplicative-inverse-under-modulo-m/function inv(a, m){ let m0 = m; let x0 = 0; let x1 = 1; if (m == 1) return 0; // Apply extended Euclid Algorithm while (a > 1) { // q is quotient let q = parseInt(a / m); let t = m; // m is remainder now, process // same as euclid's algo m = a % m; a = t; t = x0; x0 = x1 - q * x0; x1 = t; } // Make x1 positive if (x1 < 0) x1 += m0; return x1;} // k is size of num[] and rem[].// Returns the smallest// number x such that:// x % num[0] = rem[0],// x % num[1] = rem[1],// ..................// x % num[k-2] = rem[k-1]// Assumption: Numbers in num[]// are pairwise coprime (gcd for// every pair is 1)function findMinX(num, rem, k){ // Compute product of all numbers let prod = 1; for (let i = 0; i < k; i++) prod *= num[i]; // Initialize result let result = 0; // Apply above formula for (let i = 0; i < k; i++) { pp = parseInt(prod / num[i]); result += rem[i] * inv(pp, num[i]) * pp; } return result % prod;} // Driver Codelet num = new Array(3, 4, 5);let rem = new Array(2, 3, 1);let k = num.length;document.write("x is " + findMinX(num, rem, k)); // This code is contributed by _saurabh_jaiswal</script> Output: x is 11 Time Complexity : O(N*LogN) Auxiliary Space : O(1) This article is contributed by Ruchir Garg. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above Abhinav jain NSIT jit_t Mithun Kumar 6jarv91 jyoti369 _saurabh_jaiswal simmytarika5 Modular Arithmetic Mathematical Mathematical Modular Arithmetic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program for Fibonacci numbers Set in C++ Standard Template Library (STL) Write a program to print all permutations of a given string C++ Data Types Merge two sorted arrays Coin Change | DP-7 Operators in C / C++ Prime Numbers Program to find GCD or HCF of two numbers Minimum number of jumps to reach end
[ { "code": null, "e": 52, "s": 24, "text": "\n07 Apr, 2022" }, { "code": null, "e": 224, "s": 52, "text": "We are given two arrays num[0..k-1] and rem[0..k-1]. In num[0..k-1], every pair is coprime (gcd for every pair is 1). We need to find minimum positive number x such that: " }, { "code": null, "e": 346, "s": 224, "text": " x % num[0] = rem[0], \n x % num[1] = rem[1], \n .......................\n x % num[k-1] = rem[k-1]" }, { "code": null, "e": 356, "s": 346, "text": "Example: " }, { "code": null, "e": 614, "s": 356, "text": "Input: num[] = {3, 4, 5}, rem[] = {2, 3, 1}\nOutput: 11\nExplanation: \n11 is the smallest number such that:\n (1) When we divide it by 3, we get remainder 2. \n (2) When we divide it by 4, we get remainder 3.\n (3) When we divide it by 5, we get remainder 1." }, { "code": null, "e": 684, "s": 614, "text": "We strongly recommend to refer below post as a prerequisite for this." }, { "code": null, "e": 888, "s": 684, "text": "Chinese Remainder Theorem | Set 1 (Introduction)We have discussed a Naive solution to find minimum x. In this article, an efficient solution to find x is discussed.The solution is based on below formula." }, { "code": null, "e": 1214, "s": 888, "text": "x = ( ∑ (rem[i]*pp[i]*inv[i]) ) % prod\n Where 0 <= i <= n-1\n\nrem[i] is given array of remainders\n\nprod is product of all given numbers\nprod = num[0] * num[1] * ... * num[k-1]\n\npp[i] is product of all divided by num[i]\npp[i] = prod / num[i]\n\ninv[i] = Modular Multiplicative Inverse of \n pp[i] with respect to num[i]" }, { "code": null, "e": 1224, "s": 1214, "text": "Example: " }, { "code": null, "e": 1617, "s": 1224, "text": "Let us take below example to understand the solution\n num[] = {3, 4, 5}, rem[] = {2, 3, 1}\n prod = 60 \n pp[] = {20, 15, 12}\n inv[] = {2, 3, 3} // (20*2)%3 = 1, (15*3)%4 = 1\n // (12*3)%5 = 1\n\n x = (rem[0]*pp[0]*inv[0] + rem[1]*pp[1]*inv[1] + \n rem[2]*pp[2]*inv[2]) % prod\n = (2*20*2 + 3*15*3 + 1*12*3) % 60\n = (80 + 135 + 36) % 60\n = 11" }, { "code": null, "e": 1674, "s": 1617, "text": "Refer this for nice visual explanation of above formula." }, { "code": null, "e": 1800, "s": 1674, "text": "Below is the implementation of above formula. We can use Extended Euclid based method discussed here to find inverse modulo. " }, { "code": null, "e": 1804, "s": 1800, "text": "C++" }, { "code": null, "e": 1809, "s": 1804, "text": "Java" }, { "code": null, "e": 1817, "s": 1809, "text": "Python3" }, { "code": null, "e": 1820, "s": 1817, "text": "C#" }, { "code": null, "e": 1824, "s": 1820, "text": "PHP" }, { "code": null, "e": 1835, "s": 1824, "text": "Javascript" }, { "code": "// A C++ program to demonstrate// working of Chinese remainder// Theorem#include <bits/stdc++.h>using namespace std; // Returns modulo inverse of a// with respect to m using// extended Euclid Algorithm.// Refer below post for details:// https://www.geeksforgeeks.org/// multiplicative-inverse-under-modulo-m/int inv(int a, int m){ int m0 = m, t, q; int x0 = 0, x1 = 1; if (m == 1) return 0; // Apply extended Euclid Algorithm while (a > 1) { // q is quotient q = a / m; t = m; // m is remainder now, process same as // euclid's algo m = a % m, a = t; t = x0; x0 = x1 - q * x0; x1 = t; } // Make x1 positive if (x1 < 0) x1 += m0; return x1;} // k is size of num[] and rem[]. Returns the smallest// number x such that:// x % num[0] = rem[0],// x % num[1] = rem[1],// ..................// x % num[k-2] = rem[k-1]// Assumption: Numbers in num[] are pairwise coprime// (gcd for every pair is 1)int findMinX(int num[], int rem[], int k){ // Compute product of all numbers int prod = 1; for (int i = 0; i < k; i++) prod *= num[i]; // Initialize result int result = 0; // Apply above formula for (int i = 0; i < k; i++) { int pp = prod / num[i]; result += rem[i] * inv(pp, num[i]) * pp; } return result % prod;} // Driver methodint main(void){ int num[] = { 3, 4, 5 }; int rem[] = { 2, 3, 1 }; int k = sizeof(num) / sizeof(num[0]); cout << \"x is \" << findMinX(num, rem, k); return 0;}", "e": 3391, "s": 1835, "text": null }, { "code": "// A Java program to demonstrate// working of Chinese remainder// Theoremimport java.io.*; class GFG { // Returns modulo inverse of a // with respect to m using extended // Euclid Algorithm. Refer below post for details: // https://www.geeksforgeeks.org/ // multiplicative-inverse-under-modulo-m/ static int inv(int a, int m) { int m0 = m, t, q; int x0 = 0, x1 = 1; if (m == 1) return 0; // Apply extended Euclid Algorithm while (a > 1) { // q is quotient q = a / m; t = m; // m is remainder now, process // same as euclid's algo m = a % m; a = t; t = x0; x0 = x1 - q * x0; x1 = t; } // Make x1 positive if (x1 < 0) x1 += m0; return x1; } // k is size of num[] and rem[]. // Returns the smallest number // x such that: // x % num[0] = rem[0], // x % num[1] = rem[1], // .................. // x % num[k-2] = rem[k-1] // Assumption: Numbers in num[] are pairwise // coprime (gcd for every pair is 1) static int findMinX(int num[], int rem[], int k) { // Compute product of all numbers int prod = 1; for (int i = 0; i < k; i++) prod *= num[i]; // Initialize result int result = 0; // Apply above formula for (int i = 0; i < k; i++) { int pp = prod / num[i]; result += rem[i] * inv(pp, num[i]) * pp; } return result % prod; } // Driver method public static void main(String args[]) { int num[] = { 3, 4, 5 }; int rem[] = { 2, 3, 1 }; int k = num.length; System.out.println(\"x is \" + findMinX(num, rem, k)); }} // This code is contributed by nikita Tiwari.", "e": 5249, "s": 3391, "text": null }, { "code": "# A Python3 program to demonstrate# working of Chinese remainder# Theorem # Returns modulo inverse of a with# respect to m using extended# Euclid Algorithm. Refer below# post for details:# https://www.geeksforgeeks.org/# multiplicative-inverse-under-modulo-m/def inv(a, m) : m0 = m x0 = 0 x1 = 1 if (m == 1) : return 0 # Apply extended Euclid Algorithm while (a > 1) : # q is quotient q = a // m t = m # m is remainder now, process # same as euclid's algo m = a % m a = t t = x0 x0 = x1 - q * x0 x1 = t # Make x1 positive if (x1 < 0) : x1 = x1 + m0 return x1 # k is size of num[] and rem[].# Returns the smallest# number x such that:# x % num[0] = rem[0],# x % num[1] = rem[1],# ..................# x % num[k-2] = rem[k-1]# Assumption: Numbers in num[]# are pairwise coprime# (gcd for every pair is 1)def findMinX(num, rem, k) : # Compute product of all numbers prod = 1 for i in range(0, k) : prod = prod * num[i] # Initialize result result = 0 # Apply above formula for i in range(0,k): pp = prod // num[i] result = result + rem[i] * inv(pp, num[i]) * pp return result % prod # Driver methodnum = [3, 4, 5]rem = [2, 3, 1]k = len(num)print( \"x is \" , findMinX(num, rem, k)) # This code is contributed by Nikita Tiwari.", "e": 6660, "s": 5249, "text": null }, { "code": "// A C# program to demonstrate// working of Chinese remainder// Theoremusing System; class GFG{ // Returns modulo inverse of // 'a' with respect to 'm' // using extended Euclid Algorithm. // Refer below post for details: // https://www.geeksforgeeks.org/ // multiplicative-inverse-under-modulo-m/ static int inv(int a, int m) { int m0 = m, t, q; int x0 = 0, x1 = 1; if (m == 1) return 0; // Apply extended // Euclid Algorithm while (a > 1) { // q is quotient q = a / m; t = m; // m is remainder now, // process same as // euclid's algo m = a % m; a = t; t = x0; x0 = x1 - q * x0; x1 = t; } // Make x1 positive if (x1 < 0) x1 += m0; return x1; } // k is size of num[] and rem[]. // Returns the smallest number // x such that: // x % num[0] = rem[0], // x % num[1] = rem[1], // .................. // x % num[k-2] = rem[k-1] // Assumption: Numbers in num[] // are pairwise coprime (gcd // for every pair is 1) static int findMinX(int []num, int []rem, int k) { // Compute product // of all numbers int prod = 1; for (int i = 0; i < k; i++) prod *= num[i]; // Initialize result int result = 0; // Apply above formula for (int i = 0; i < k; i++) { int pp = prod / num[i]; result += rem[i] * inv(pp, num[i]) * pp; } return result % prod; } // Driver Code static public void Main () { int []num = {3, 4, 5}; int []rem = {2, 3, 1}; int k = num.Length; Console.WriteLine(\"x is \" + findMinX(num, rem, k)); }} // This code is contributed// by ajit", "e": 8672, "s": 6660, "text": null }, { "code": "<?php// PHP program to demonstrate working// of Chinese remainder Theorem // Returns modulo inverse of a with// respect to m using extended Euclid// Algorithm. Refer below post for details:// https://www.geeksforgeeks.org/// multiplicative-inverse-under-modulo-m/function inv($a, $m){ $m0 = $m; $x0 = 0; $x1 = 1; if ($m == 1) return 0; // Apply extended Euclid Algorithm while ($a > 1) { // q is quotient $q = (int)($a / $m); $t = $m; // m is remainder now, process // same as euclid's algo $m = $a % $m; $a = $t; $t = $x0; $x0 = $x1 - $q * $x0; $x1 = $t; } // Make x1 positive if ($x1 < 0) $x1 += $m0; return $x1;} // k is size of num[] and rem[].// Returns the smallest// number x such that:// x % num[0] = rem[0],// x % num[1] = rem[1],// ..................// x % num[k-2] = rem[k-1]// Assumption: Numbers in num[]// are pairwise coprime (gcd for// every pair is 1)function findMinX($num, $rem, $k){ // Compute product of all numbers $prod = 1; for ($i = 0; $i < $k; $i++) $prod *= $num[$i]; // Initialize result $result = 0; // Apply above formula for ($i = 0; $i < $k; $i++) { $pp = (int)$prod / $num[$i]; $result += $rem[$i] * inv($pp, $num[$i]) * $pp; } return $result % $prod;} // Driver Code$num = array(3, 4, 5);$rem = array(2, 3, 1);$k = sizeof($num);echo \"x is \". findMinX($num, $rem, $k); // This code is contributed by mits?>", "e": 10203, "s": 8672, "text": null }, { "code": "<script>// Javascript program to demonstrate working// of Chinese remainder Theorem // Returns modulo inverse of a with// respect to m using extended Euclid// Algorithm. Refer below post for details:// https://www.geeksforgeeks.org/// multiplicative-inverse-under-modulo-m/function inv(a, m){ let m0 = m; let x0 = 0; let x1 = 1; if (m == 1) return 0; // Apply extended Euclid Algorithm while (a > 1) { // q is quotient let q = parseInt(a / m); let t = m; // m is remainder now, process // same as euclid's algo m = a % m; a = t; t = x0; x0 = x1 - q * x0; x1 = t; } // Make x1 positive if (x1 < 0) x1 += m0; return x1;} // k is size of num[] and rem[].// Returns the smallest// number x such that:// x % num[0] = rem[0],// x % num[1] = rem[1],// ..................// x % num[k-2] = rem[k-1]// Assumption: Numbers in num[]// are pairwise coprime (gcd for// every pair is 1)function findMinX(num, rem, k){ // Compute product of all numbers let prod = 1; for (let i = 0; i < k; i++) prod *= num[i]; // Initialize result let result = 0; // Apply above formula for (let i = 0; i < k; i++) { pp = parseInt(prod / num[i]); result += rem[i] * inv(pp, num[i]) * pp; } return result % prod;} // Driver Codelet num = new Array(3, 4, 5);let rem = new Array(2, 3, 1);let k = num.length;document.write(\"x is \" + findMinX(num, rem, k)); // This code is contributed by _saurabh_jaiswal</script>", "e": 11772, "s": 10203, "text": null }, { "code": null, "e": 11781, "s": 11772, "text": "Output: " }, { "code": null, "e": 11789, "s": 11781, "text": "x is 11" }, { "code": null, "e": 11817, "s": 11789, "text": "Time Complexity : O(N*LogN)" }, { "code": null, "e": 11840, "s": 11817, "text": "Auxiliary Space : O(1)" }, { "code": null, "e": 12009, "s": 11840, "text": "This article is contributed by Ruchir Garg. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 12027, "s": 12009, "text": "Abhinav jain NSIT" }, { "code": null, "e": 12033, "s": 12027, "text": "jit_t" }, { "code": null, "e": 12046, "s": 12033, "text": "Mithun Kumar" }, { "code": null, "e": 12054, "s": 12046, "text": "6jarv91" }, { "code": null, "e": 12063, "s": 12054, "text": "jyoti369" }, { "code": null, "e": 12080, "s": 12063, "text": "_saurabh_jaiswal" }, { "code": null, "e": 12093, "s": 12080, "text": "simmytarika5" }, { "code": null, "e": 12112, "s": 12093, "text": "Modular Arithmetic" }, { "code": null, "e": 12125, "s": 12112, "text": "Mathematical" }, { "code": null, "e": 12138, "s": 12125, "text": "Mathematical" }, { "code": null, "e": 12157, "s": 12138, "text": "Modular Arithmetic" }, { "code": null, "e": 12255, "s": 12157, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 12285, "s": 12255, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 12328, "s": 12285, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 12388, "s": 12328, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 12403, "s": 12388, "text": "C++ Data Types" }, { "code": null, "e": 12427, "s": 12403, "text": "Merge two sorted arrays" }, { "code": null, "e": 12446, "s": 12427, "text": "Coin Change | DP-7" }, { "code": null, "e": 12467, "s": 12446, "text": "Operators in C / C++" }, { "code": null, "e": 12481, "s": 12467, "text": "Prime Numbers" }, { "code": null, "e": 12523, "s": 12481, "text": "Program to find GCD or HCF of two numbers" } ]
Perfect Sum Problem
21 Dec, 2021 Given an array arr[] of integers and an integer K, the task is to print all subsets of the given array with the sum equal to the given target K.Examples: Input: arr[] = {5, 10, 12, 13, 15, 18}, K = 30 Output: {12, 18}, {5, 12, 13}, {5, 10, 15} Explanation: Subsets with sum 30 are: 12 + 18 = 30 5 + 12 + 13 = 30 5 + 10 + 15 = 30 Input: arr[] = {1, 2, 3, 4}, K = 5 Output: {2, 3}, {1, 4} Approach: The idea is to find out all the subsets using the Power Set concept. For every set, check if the sum of the set is equal to K or not. If it is equal, then the set is printed. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the above approach#include <bits/stdc++.h> using namespace std; // Function to print the subsets whose// sum is equal to the given target Kvoid sumSubsets(vector<int> set, int n, int target){ // Create the new array with size // equal to array set[] to create // binary array as per n(decimal number) int x[set.size()]; int j = set.size() - 1; // Convert the array into binary array while (n > 0) { x[j] = n % 2; n = n / 2; j--; } int sum = 0; // Calculate the sum of this subset for (int i = 0; i < set.size(); i++) if (x[i] == 1) sum = sum + set[i]; // Check whether sum is equal to target // if it is equal, then print the subset if (sum == target) { cout<<("{"); for (int i = 0; i < set.size(); i++) if (x[i] == 1) cout << set[i] << ", "; cout << ("}, "); }} // Function to find the subsets with sum Kvoid findSubsets(vector<int> arr, int K){ // Calculate the total no. of subsets int x = pow(2, arr.size()); // Run loop till total no. of subsets // and call the function for each subset for (int i = 1; i < x; i++) sumSubsets(arr, i, K);} // Driver codeint main(){ vector<int> arr = { 5, 10, 12, 13, 15, 18 }; int K = 30; findSubsets(arr, K); return 0;} // This code is contributed by mohit kumar 29 // Java implementation of the above approachimport java.util.*; class GFG { // Function to print the subsets whose // sum is equal to the given target K public static void sumSubsets( int set[], int n, int target) { // Create the new array with size // equal to array set[] to create // binary array as per n(decimal number) int x[] = new int[set.length]; int j = set.length - 1; // Convert the array into binary array while (n > 0) { x[j] = n % 2; n = n / 2; j--; } int sum = 0; // Calculate the sum of this subset for (int i = 0; i < set.length; i++) if (x[i] == 1) sum = sum + set[i]; // Check whether sum is equal to target // if it is equal, then print the subset if (sum == target) { System.out.print("{"); for (int i = 0; i < set.length; i++) if (x[i] == 1) System.out.print(set[i] + ", "); System.out.print("}, "); } } // Function to find the subsets with sum K public static void findSubsets(int[] arr, int K) { // Calculate the total no. of subsets int x = (int)Math.pow(2, arr.length); // Run loop till total no. of subsets // and call the function for each subset for (int i = 1; i < x; i++) sumSubsets(arr, i, K); } // Driver code public static void main(String args[]) { int arr[] = { 5, 10, 12, 13, 15, 18 }; int K = 30; findSubsets(arr, K); }} # Python3 implementation of the above approach # Function to print the subsets whose# sum is equal to the given target Kdef sumSubsets(sets, n, target) : # Create the new array with size # equal to array set[] to create # binary array as per n(decimal number) x = [0]*len(sets); j = len(sets) - 1; # Convert the array into binary array while (n > 0) : x[j] = n % 2; n = n // 2; j -= 1; sum = 0; # Calculate the sum of this subset for i in range(len(sets)) : if (x[i] == 1) : sum += sets[i]; # Check whether sum is equal to target # if it is equal, then print the subset if (sum == target) : print("{",end=""); for i in range(len(sets)) : if (x[i] == 1) : print(sets[i],end= ", "); print("}, ",end=""); # Function to find the subsets with sum Kdef findSubsets(arr, K) : # Calculate the total no. of subsets x = pow(2, len(arr)); # Run loop till total no. of subsets # and call the function for each subset for i in range(1, x) : sumSubsets(arr, i, K); # Driver codeif __name__ == "__main__" : arr = [ 5, 10, 12, 13, 15, 18 ]; K = 30; findSubsets(arr, K); # This code is contributed by Yash_R // C# implementation of the above approachusing System; class GFG{ // Function to print the subsets whose // sum is equal to the given target K public static void sumSubsets( int []set, int n, int target) { // Create the new array with size // equal to array set[] to create // binary array as per n(decimal number) int []x = new int[set.Length]; int j = set.Length - 1; // Convert the array into binary array while (n > 0) { x[j] = n % 2; n = n / 2; j--; } int sum = 0; // Calculate the sum of this subset for (int i = 0; i < set.Length; i++) if (x[i] == 1) sum = sum + set[i]; // Check whether sum is equal to target // if it is equal, then print the subset if (sum == target) { Console.Write("{"); for (int i = 0; i < set.Length; i++) if (x[i] == 1) Console.Write(set[i] + ", "); Console.Write("}, "); } } // Function to find the subsets with sum K public static void findSubsets(int[] arr, int K) { // Calculate the total no. of subsets int x = (int)Math.Pow(2, arr.Length); // Run loop till total no. of subsets // and call the function for each subset for (int i = 1; i < x; i++) sumSubsets(arr, i, K); } // Driver code public static void Main(String []args) { int []arr = { 5, 10, 12, 13, 15, 18 }; int K = 30; findSubsets(arr, K); }} // This code is contributed by 29AjayKumar <script> // JavaScript implementation of the above approach // Function to print the subsets whose// sum is equal to the given target Kfunction sumSubsets(set, n, target) { // Create the new array with length // equal to array set[] to create // binary array as per n(decimal number) let x = new Array(set.length); let j = set.length - 1; // Convert the array into binary array while (n > 0) { x[j] = n % 2; n = Math.floor(n / 2); j--; } let sum = 0; // Calculate the sum of this subset for (let i = 0; i < set.length; i++) if (x[i] == 1) sum = sum + set[i]; // Check whether sum is equal to target // if it is equal, then print the subset if (sum == target) { document.write("{"); for (let i = 0; i < set.length; i++) if (x[i] == 1) document.write(set[i] + ", "); document.write("}, "); }} // Function to find the subsets with sum Kfunction findSubsets(arr, K) { // Calculate the total no. of subsets let x = Math.pow(2, arr.length); // Run loop till total no. of subsets // and call the function for each subset for (let i = 1; i < x; i++) sumSubsets(arr, i, K);} // Driver code let arr = [5, 10, 12, 13, 15, 18];let K = 30;findSubsets(arr, K); // This code is contributed by gfgking </script> {12, 18, }, {5, 12, 13, }, {5, 10, 15, }, Time Complexity: 2N Auxiliary Space: O(N)Efficient Approach: This problem can also be solved using Dynamic Programming. Refer to this article. mohit kumar 29 29AjayKumar Yash_R gfgking vansikasharma1329 subset Arrays Backtracking Mathematical Arrays Mathematical subset Backtracking Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Multidimensional Arrays in Java Stack Data Structure (Introduction and Program) Linear Search Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) N Queen Problem | Backtracking-3 Backtracking | Introduction Rat in a Maze | Backtracking-2 The Knight's tour problem | Backtracking-1
[ { "code": null, "e": 54, "s": 26, "text": "\n21 Dec, 2021" }, { "code": null, "e": 210, "s": 54, "text": "Given an array arr[] of integers and an integer K, the task is to print all subsets of the given array with the sum equal to the given target K.Examples: " }, { "code": null, "e": 445, "s": 210, "text": "Input: arr[] = {5, 10, 12, 13, 15, 18}, K = 30\nOutput: {12, 18}, {5, 12, 13}, {5, 10, 15}\nExplanation: \nSubsets with sum 30 are:\n12 + 18 = 30\n5 + 12 + 13 = 30\n5 + 10 + 15 = 30\n\nInput: arr[] = {1, 2, 3, 4}, K = 5\nOutput: {2, 3}, {1, 4}" }, { "code": null, "e": 684, "s": 447, "text": "Approach: The idea is to find out all the subsets using the Power Set concept. For every set, check if the sum of the set is equal to K or not. If it is equal, then the set is printed. Below is the implementation of the above approach: " }, { "code": null, "e": 688, "s": 684, "text": "C++" }, { "code": null, "e": 693, "s": 688, "text": "Java" }, { "code": null, "e": 701, "s": 693, "text": "Python3" }, { "code": null, "e": 704, "s": 701, "text": "C#" }, { "code": null, "e": 715, "s": 704, "text": "Javascript" }, { "code": "// C++ implementation of the above approach#include <bits/stdc++.h> using namespace std; // Function to print the subsets whose// sum is equal to the given target Kvoid sumSubsets(vector<int> set, int n, int target){ // Create the new array with size // equal to array set[] to create // binary array as per n(decimal number) int x[set.size()]; int j = set.size() - 1; // Convert the array into binary array while (n > 0) { x[j] = n % 2; n = n / 2; j--; } int sum = 0; // Calculate the sum of this subset for (int i = 0; i < set.size(); i++) if (x[i] == 1) sum = sum + set[i]; // Check whether sum is equal to target // if it is equal, then print the subset if (sum == target) { cout<<(\"{\"); for (int i = 0; i < set.size(); i++) if (x[i] == 1) cout << set[i] << \", \"; cout << (\"}, \"); }} // Function to find the subsets with sum Kvoid findSubsets(vector<int> arr, int K){ // Calculate the total no. of subsets int x = pow(2, arr.size()); // Run loop till total no. of subsets // and call the function for each subset for (int i = 1; i < x; i++) sumSubsets(arr, i, K);} // Driver codeint main(){ vector<int> arr = { 5, 10, 12, 13, 15, 18 }; int K = 30; findSubsets(arr, K); return 0;} // This code is contributed by mohit kumar 29", "e": 2121, "s": 715, "text": null }, { "code": "// Java implementation of the above approachimport java.util.*; class GFG { // Function to print the subsets whose // sum is equal to the given target K public static void sumSubsets( int set[], int n, int target) { // Create the new array with size // equal to array set[] to create // binary array as per n(decimal number) int x[] = new int[set.length]; int j = set.length - 1; // Convert the array into binary array while (n > 0) { x[j] = n % 2; n = n / 2; j--; } int sum = 0; // Calculate the sum of this subset for (int i = 0; i < set.length; i++) if (x[i] == 1) sum = sum + set[i]; // Check whether sum is equal to target // if it is equal, then print the subset if (sum == target) { System.out.print(\"{\"); for (int i = 0; i < set.length; i++) if (x[i] == 1) System.out.print(set[i] + \", \"); System.out.print(\"}, \"); } } // Function to find the subsets with sum K public static void findSubsets(int[] arr, int K) { // Calculate the total no. of subsets int x = (int)Math.pow(2, arr.length); // Run loop till total no. of subsets // and call the function for each subset for (int i = 1; i < x; i++) sumSubsets(arr, i, K); } // Driver code public static void main(String args[]) { int arr[] = { 5, 10, 12, 13, 15, 18 }; int K = 30; findSubsets(arr, K); }}", "e": 3734, "s": 2121, "text": null }, { "code": "# Python3 implementation of the above approach # Function to print the subsets whose# sum is equal to the given target Kdef sumSubsets(sets, n, target) : # Create the new array with size # equal to array set[] to create # binary array as per n(decimal number) x = [0]*len(sets); j = len(sets) - 1; # Convert the array into binary array while (n > 0) : x[j] = n % 2; n = n // 2; j -= 1; sum = 0; # Calculate the sum of this subset for i in range(len(sets)) : if (x[i] == 1) : sum += sets[i]; # Check whether sum is equal to target # if it is equal, then print the subset if (sum == target) : print(\"{\",end=\"\"); for i in range(len(sets)) : if (x[i] == 1) : print(sets[i],end= \", \"); print(\"}, \",end=\"\"); # Function to find the subsets with sum Kdef findSubsets(arr, K) : # Calculate the total no. of subsets x = pow(2, len(arr)); # Run loop till total no. of subsets # and call the function for each subset for i in range(1, x) : sumSubsets(arr, i, K); # Driver codeif __name__ == \"__main__\" : arr = [ 5, 10, 12, 13, 15, 18 ]; K = 30; findSubsets(arr, K); # This code is contributed by Yash_R", "e": 4999, "s": 3734, "text": null }, { "code": "// C# implementation of the above approachusing System; class GFG{ // Function to print the subsets whose // sum is equal to the given target K public static void sumSubsets( int []set, int n, int target) { // Create the new array with size // equal to array set[] to create // binary array as per n(decimal number) int []x = new int[set.Length]; int j = set.Length - 1; // Convert the array into binary array while (n > 0) { x[j] = n % 2; n = n / 2; j--; } int sum = 0; // Calculate the sum of this subset for (int i = 0; i < set.Length; i++) if (x[i] == 1) sum = sum + set[i]; // Check whether sum is equal to target // if it is equal, then print the subset if (sum == target) { Console.Write(\"{\"); for (int i = 0; i < set.Length; i++) if (x[i] == 1) Console.Write(set[i] + \", \"); Console.Write(\"}, \"); } } // Function to find the subsets with sum K public static void findSubsets(int[] arr, int K) { // Calculate the total no. of subsets int x = (int)Math.Pow(2, arr.Length); // Run loop till total no. of subsets // and call the function for each subset for (int i = 1; i < x; i++) sumSubsets(arr, i, K); } // Driver code public static void Main(String []args) { int []arr = { 5, 10, 12, 13, 15, 18 }; int K = 30; findSubsets(arr, K); }} // This code is contributed by 29AjayKumar", "e": 6651, "s": 4999, "text": null }, { "code": "<script> // JavaScript implementation of the above approach // Function to print the subsets whose// sum is equal to the given target Kfunction sumSubsets(set, n, target) { // Create the new array with length // equal to array set[] to create // binary array as per n(decimal number) let x = new Array(set.length); let j = set.length - 1; // Convert the array into binary array while (n > 0) { x[j] = n % 2; n = Math.floor(n / 2); j--; } let sum = 0; // Calculate the sum of this subset for (let i = 0; i < set.length; i++) if (x[i] == 1) sum = sum + set[i]; // Check whether sum is equal to target // if it is equal, then print the subset if (sum == target) { document.write(\"{\"); for (let i = 0; i < set.length; i++) if (x[i] == 1) document.write(set[i] + \", \"); document.write(\"}, \"); }} // Function to find the subsets with sum Kfunction findSubsets(arr, K) { // Calculate the total no. of subsets let x = Math.pow(2, arr.length); // Run loop till total no. of subsets // and call the function for each subset for (let i = 1; i < x; i++) sumSubsets(arr, i, K);} // Driver code let arr = [5, 10, 12, 13, 15, 18];let K = 30;findSubsets(arr, K); // This code is contributed by gfgking </script>", "e": 8007, "s": 6651, "text": null }, { "code": null, "e": 8049, "s": 8007, "text": "{12, 18, }, {5, 12, 13, }, {5, 10, 15, }," }, { "code": null, "e": 8071, "s": 8051, "text": "Time Complexity: 2N" }, { "code": null, "e": 8195, "s": 8071, "text": "Auxiliary Space: O(N)Efficient Approach: This problem can also be solved using Dynamic Programming. Refer to this article. " }, { "code": null, "e": 8210, "s": 8195, "text": "mohit kumar 29" }, { "code": null, "e": 8222, "s": 8210, "text": "29AjayKumar" }, { "code": null, "e": 8229, "s": 8222, "text": "Yash_R" }, { "code": null, "e": 8237, "s": 8229, "text": "gfgking" }, { "code": null, "e": 8255, "s": 8237, "text": "vansikasharma1329" }, { "code": null, "e": 8262, "s": 8255, "text": "subset" }, { "code": null, "e": 8269, "s": 8262, "text": "Arrays" }, { "code": null, "e": 8282, "s": 8269, "text": "Backtracking" }, { "code": null, "e": 8295, "s": 8282, "text": "Mathematical" }, { "code": null, "e": 8302, "s": 8295, "text": "Arrays" }, { "code": null, "e": 8315, "s": 8302, "text": "Mathematical" }, { "code": null, "e": 8322, "s": 8315, "text": "subset" }, { "code": null, "e": 8335, "s": 8322, "text": "Backtracking" }, { "code": null, "e": 8433, "s": 8335, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8501, "s": 8433, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 8545, "s": 8501, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 8577, "s": 8545, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 8625, "s": 8577, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 8639, "s": 8625, "text": "Linear Search" }, { "code": null, "e": 8724, "s": 8639, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 8757, "s": 8724, "text": "N Queen Problem | Backtracking-3" }, { "code": null, "e": 8785, "s": 8757, "text": "Backtracking | Introduction" }, { "code": null, "e": 8816, "s": 8785, "text": "Rat in a Maze | Backtracking-2" } ]
Scala String substring() method with example
23 Oct, 2019 The substring() method is utilized to find the sub-string from the stated String which starts from the index specified. Method Definition: String substring(int beginIndex) Return Type: It returns the content from the given String Which starts from the index we specify. Example: 1# // Scala program of substring()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Applying substring method val result = "GeeksforGeeks".substring(8) // Displays output println(result) }} Geeks Example: 2# // Scala program of substring()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Applying substring method val result = "GeeksforGeeks".substring(11) // Displays output println(result) }} ks Scala Scala-Method Scala-Strings Scala Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Class and Object in Scala Operators in Scala Scala Constructors Enumeration in Scala How to get the first element of List in Scala Inheritance in Scala How to Install Scala with VSCode? HashMap in Scala Break statement in Scala Scala Map get() method with example
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Oct, 2019" }, { "code": null, "e": 148, "s": 28, "text": "The substring() method is utilized to find the sub-string from the stated String which starts from the index specified." }, { "code": null, "e": 200, "s": 148, "text": "Method Definition: String substring(int beginIndex)" }, { "code": null, "e": 298, "s": 200, "text": "Return Type: It returns the content from the given String Which starts from the index we specify." }, { "code": null, "e": 310, "s": 298, "text": "Example: 1#" }, { "code": "// Scala program of substring()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Applying substring method val result = \"GeeksforGeeks\".substring(8) // Displays output println(result) }} ", "e": 603, "s": 310, "text": null }, { "code": null, "e": 610, "s": 603, "text": "Geeks\n" }, { "code": null, "e": 622, "s": 610, "text": "Example: 2#" }, { "code": "// Scala program of substring()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Applying substring method val result = \"GeeksforGeeks\".substring(11) // Displays output println(result) }} ", "e": 920, "s": 622, "text": null }, { "code": null, "e": 924, "s": 920, "text": "ks\n" }, { "code": null, "e": 930, "s": 924, "text": "Scala" }, { "code": null, "e": 943, "s": 930, "text": "Scala-Method" }, { "code": null, "e": 957, "s": 943, "text": "Scala-Strings" }, { "code": null, "e": 963, "s": 957, "text": "Scala" }, { "code": null, "e": 1061, "s": 963, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1087, "s": 1061, "text": "Class and Object in Scala" }, { "code": null, "e": 1106, "s": 1087, "text": "Operators in Scala" }, { "code": null, "e": 1125, "s": 1106, "text": "Scala Constructors" }, { "code": null, "e": 1146, "s": 1125, "text": "Enumeration in Scala" }, { "code": null, "e": 1192, "s": 1146, "text": "How to get the first element of List in Scala" }, { "code": null, "e": 1213, "s": 1192, "text": "Inheritance in Scala" }, { "code": null, "e": 1247, "s": 1213, "text": "How to Install Scala with VSCode?" }, { "code": null, "e": 1264, "s": 1247, "text": "HashMap in Scala" }, { "code": null, "e": 1289, "s": 1264, "text": "Break statement in Scala" } ]
Maximum product of a pair of nodes from largest connected component in a Graph
05 Jul, 2021 Given an undirected weighted graph G consisting of N vertices and M edges, and two arrays Edges[][2] and Weight[] consisting of M edges of the graph and weights of each edge respectively, the task is to find the maximum product of any two vertices of the largest connected component of the graph, formed by connecting all edges with the same weight. Examples: Input: N = 4, Edges[][] = {{1, 2}, {1, 2}, {2, 3}, {2, 3}, {2, 4}}, Weight[] = {1, 2, 1, 3, 3}Output: 12Explanation: Components of edges of weight 1, 1 ↔ 2 ↔ 3. The maximum product of any two vertices of this component is 6. Components of edges of weight 2, 1 ↔ 2. The maximum product of any two vertices of this component is 2. Components of edges of weight 3, 4 ↔ 2 ↔ 3. The maximum product of any two vertices of this component is 12. Therefore, the maximum product among all the connected components of size 3 (which is maximum) is 12. Input: N = 5, Edges[][] = {{1, 5}, {2, 5}, {3, 5}, {4, 5}, {1, 2}, {2, 3}, {3, 4}}, Weight[] = {1, 1, 1, 1, 2, 2, 2}Output: 20 Approach: The given problem can be solved by performing the DFS traversal on the given graph and maximize the product of the first and second maximum node for all the connected components of the same weight. Follow the steps below to solve the problem: Store all the edges corresponding to all the unique weight in a map M. Initialize a variable, say res as 0 to store the maximum product of any two nodes of the connected components of the same weights. Traverse the map and for each key as weight create a graph by connecting all the edges mapped with the particular weight and perform the following operations:Find the value of the maximum(say M1) and the second maximum(say M2) node’s value and the size of all the connected components of the graph by performing the DFS Traversal on the created graph.Update the value of res to the maximum of res, M1, and M2 if the size of the currently connected components is at least the largest size connected component found previously. Find the value of the maximum(say M1) and the second maximum(say M2) node’s value and the size of all the connected components of the graph by performing the DFS Traversal on the created graph. Update the value of res to the maximum of res, M1, and M2 if the size of the currently connected components is at least the largest size connected component found previously. After completing the above steps, print the value of res as the maximum product. Below is the implementation of the above approach: C++ // C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Stores the first and second largest// element in a connected componentint Max, sMax; // Stores the count of nodes// in the connected componentsint cnt = 0; // Function to perform DFS Traversal// on a given graph and find the first// and the second largest elementsvoid dfs(int u, int N, vector<bool>& vis, vector<vector<int> >& adj){ // Update the maximum value if (u > Max) { sMax = Max; Max = u; } // Update the second max value else if (u > sMax) { sMax = u; } // Increment size of component cnt++; // Mark current node visited vis[u] = true; // Traverse the adjacent nodes for (auto to : adj[u]) { // If to is not already visited if (!vis[to]) { dfs(to, N, vis, adj); } } return;} // Function to find the maximum// product of a connected componentint MaximumProduct( int N, vector<pair<int, int> > Edge, vector<int> wt){ // Stores the count of edges int M = wt.size(); // Stores all the edges mapped // with a particular weight unordered_map<int, vector<pair<int, int> > > mp; // Update the map mp for (int i = 0; i < M; i++) mp[wt[i]].push_back(Edge[i]); // Stores the result int res = 0; // Traverse the map mp for (auto i : mp) { // Stores the adjacency list vector<vector<int> > adj(N + 1); // Stores the edges of // a particular weight vector<pair<int, int> > v = i.second; // Traverse the vector v for (int j = 0; j < v.size(); j++) { int U = v[j].first; int V = v[j].second; // Add an edge adj[U].push_back(V); adj[V].push_back(U); } // Stores if a vertex // is visited or not vector<bool> vis(N + 1, 0); // Stores the maximum // size of a component int cntMax = 0; // Iterate over the range [1, N] for (int u = 1; u <= N; u++) { // Assign Max, sMax, count = 0 Max = sMax = cnt = 0; // If vertex u is not visited if (!vis[u]) { dfs(u, N, vis, adj); // If cnt is greater // than cntMax if (cnt > cntMax) { // Update the res res = Max * sMax; cntMax = cnt; } // If already largest // connected component else if (cnt == cntMax) { // Update res res = max(res, Max * sMax); } } } } // Return res return res;} // Driver Codeint main(){ int N = 5; vector<pair<int, int> > Edges = { { 1, 2 }, { 2, 5 }, { 3, 5 }, { 4, 5 }, { 1, 2 }, { 2, 3 }, { 3, 4 } }; vector<int> Weight = { 1, 1, 1, 1, 2, 2, 2 }; cout << MaximumProduct(N, Edges, Weight); return 0;} 20 Time Complexity: O(N2 * log N + M)Auxiliary Space: O(N2) simranarora5sos DFS Graph Traversals graph-connectivity Graph Mathematical Recursion Searching Searching Mathematical Recursion DFS Graph Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Find if there is a path between two vertices in a directed graph Introduction to Data Structures What is Data Structure: Types, Classifications and Applications Find if there is a path between two vertices in an undirected graph Minimum steps to reach target by a Knight | Set 1 Program for Fibonacci numbers Set in C++ Standard Template Library (STL) Write a program to print all permutations of a given string C++ Data Types Merge two sorted arrays
[ { "code": null, "e": 52, "s": 24, "text": "\n05 Jul, 2021" }, { "code": null, "e": 402, "s": 52, "text": "Given an undirected weighted graph G consisting of N vertices and M edges, and two arrays Edges[][2] and Weight[] consisting of M edges of the graph and weights of each edge respectively, the task is to find the maximum product of any two vertices of the largest connected component of the graph, formed by connecting all edges with the same weight." }, { "code": null, "e": 412, "s": 402, "text": "Examples:" }, { "code": null, "e": 529, "s": 412, "text": "Input: N = 4, Edges[][] = {{1, 2}, {1, 2}, {2, 3}, {2, 3}, {2, 4}}, Weight[] = {1, 2, 1, 3, 3}Output: 12Explanation:" }, { "code": null, "e": 637, "s": 529, "text": "Components of edges of weight 1, 1 ↔ 2 ↔ 3. The maximum product of any two vertices of this component is 6." }, { "code": null, "e": 741, "s": 637, "text": "Components of edges of weight 2, 1 ↔ 2. The maximum product of any two vertices of this component is 2." }, { "code": null, "e": 850, "s": 741, "text": "Components of edges of weight 3, 4 ↔ 2 ↔ 3. The maximum product of any two vertices of this component is 12." }, { "code": null, "e": 952, "s": 850, "text": "Therefore, the maximum product among all the connected components of size 3 (which is maximum) is 12." }, { "code": null, "e": 1079, "s": 952, "text": "Input: N = 5, Edges[][] = {{1, 5}, {2, 5}, {3, 5}, {4, 5}, {1, 2}, {2, 3}, {3, 4}}, Weight[] = {1, 1, 1, 1, 2, 2, 2}Output: 20" }, { "code": null, "e": 1332, "s": 1079, "text": "Approach: The given problem can be solved by performing the DFS traversal on the given graph and maximize the product of the first and second maximum node for all the connected components of the same weight. Follow the steps below to solve the problem:" }, { "code": null, "e": 1403, "s": 1332, "text": "Store all the edges corresponding to all the unique weight in a map M." }, { "code": null, "e": 1534, "s": 1403, "text": "Initialize a variable, say res as 0 to store the maximum product of any two nodes of the connected components of the same weights." }, { "code": null, "e": 2060, "s": 1534, "text": "Traverse the map and for each key as weight create a graph by connecting all the edges mapped with the particular weight and perform the following operations:Find the value of the maximum(say M1) and the second maximum(say M2) node’s value and the size of all the connected components of the graph by performing the DFS Traversal on the created graph.Update the value of res to the maximum of res, M1, and M2 if the size of the currently connected components is at least the largest size connected component found previously." }, { "code": null, "e": 2254, "s": 2060, "text": "Find the value of the maximum(say M1) and the second maximum(say M2) node’s value and the size of all the connected components of the graph by performing the DFS Traversal on the created graph." }, { "code": null, "e": 2429, "s": 2254, "text": "Update the value of res to the maximum of res, M1, and M2 if the size of the currently connected components is at least the largest size connected component found previously." }, { "code": null, "e": 2510, "s": 2429, "text": "After completing the above steps, print the value of res as the maximum product." }, { "code": null, "e": 2561, "s": 2510, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 2565, "s": 2561, "text": "C++" }, { "code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Stores the first and second largest// element in a connected componentint Max, sMax; // Stores the count of nodes// in the connected componentsint cnt = 0; // Function to perform DFS Traversal// on a given graph and find the first// and the second largest elementsvoid dfs(int u, int N, vector<bool>& vis, vector<vector<int> >& adj){ // Update the maximum value if (u > Max) { sMax = Max; Max = u; } // Update the second max value else if (u > sMax) { sMax = u; } // Increment size of component cnt++; // Mark current node visited vis[u] = true; // Traverse the adjacent nodes for (auto to : adj[u]) { // If to is not already visited if (!vis[to]) { dfs(to, N, vis, adj); } } return;} // Function to find the maximum// product of a connected componentint MaximumProduct( int N, vector<pair<int, int> > Edge, vector<int> wt){ // Stores the count of edges int M = wt.size(); // Stores all the edges mapped // with a particular weight unordered_map<int, vector<pair<int, int> > > mp; // Update the map mp for (int i = 0; i < M; i++) mp[wt[i]].push_back(Edge[i]); // Stores the result int res = 0; // Traverse the map mp for (auto i : mp) { // Stores the adjacency list vector<vector<int> > adj(N + 1); // Stores the edges of // a particular weight vector<pair<int, int> > v = i.second; // Traverse the vector v for (int j = 0; j < v.size(); j++) { int U = v[j].first; int V = v[j].second; // Add an edge adj[U].push_back(V); adj[V].push_back(U); } // Stores if a vertex // is visited or not vector<bool> vis(N + 1, 0); // Stores the maximum // size of a component int cntMax = 0; // Iterate over the range [1, N] for (int u = 1; u <= N; u++) { // Assign Max, sMax, count = 0 Max = sMax = cnt = 0; // If vertex u is not visited if (!vis[u]) { dfs(u, N, vis, adj); // If cnt is greater // than cntMax if (cnt > cntMax) { // Update the res res = Max * sMax; cntMax = cnt; } // If already largest // connected component else if (cnt == cntMax) { // Update res res = max(res, Max * sMax); } } } } // Return res return res;} // Driver Codeint main(){ int N = 5; vector<pair<int, int> > Edges = { { 1, 2 }, { 2, 5 }, { 3, 5 }, { 4, 5 }, { 1, 2 }, { 2, 3 }, { 3, 4 } }; vector<int> Weight = { 1, 1, 1, 1, 2, 2, 2 }; cout << MaximumProduct(N, Edges, Weight); return 0;}", "e": 5626, "s": 2565, "text": null }, { "code": null, "e": 5629, "s": 5626, "text": "20" }, { "code": null, "e": 5688, "s": 5631, "text": "Time Complexity: O(N2 * log N + M)Auxiliary Space: O(N2)" }, { "code": null, "e": 5704, "s": 5688, "text": "simranarora5sos" }, { "code": null, "e": 5708, "s": 5704, "text": "DFS" }, { "code": null, "e": 5725, "s": 5708, "text": "Graph Traversals" }, { "code": null, "e": 5744, "s": 5725, "text": "graph-connectivity" }, { "code": null, "e": 5750, "s": 5744, "text": "Graph" }, { "code": null, "e": 5763, "s": 5750, "text": "Mathematical" }, { "code": null, "e": 5773, "s": 5763, "text": "Recursion" }, { "code": null, "e": 5783, "s": 5773, "text": "Searching" }, { "code": null, "e": 5793, "s": 5783, "text": "Searching" }, { "code": null, "e": 5806, "s": 5793, "text": "Mathematical" }, { "code": null, "e": 5816, "s": 5806, "text": "Recursion" }, { "code": null, "e": 5820, "s": 5816, "text": "DFS" }, { "code": null, "e": 5826, "s": 5820, "text": "Graph" }, { "code": null, "e": 5924, "s": 5826, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5989, "s": 5924, "text": "Find if there is a path between two vertices in a directed graph" }, { "code": null, "e": 6021, "s": 5989, "text": "Introduction to Data Structures" }, { "code": null, "e": 6085, "s": 6021, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 6153, "s": 6085, "text": "Find if there is a path between two vertices in an undirected graph" }, { "code": null, "e": 6203, "s": 6153, "text": "Minimum steps to reach target by a Knight | Set 1" }, { "code": null, "e": 6233, "s": 6203, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 6276, "s": 6233, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 6336, "s": 6276, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 6351, "s": 6336, "text": "C++ Data Types" } ]
XML | Basics
29 Oct, 2020 Extensible Markup Language (XML) is a markup language that defines a set of rules for encoding documents in a format that is both human-readable and machine-readable. The design goals of XML focus on simplicity, generality, and usability across the Internet. It is a textual data format with strong support via Unicode for different human languages. Although the design of XML focuses on documents, the language is widely used for the representation of arbitrary data structures such as those used in web services. XML stands for extensible Markup LanguageXML is a markup language like HTMLXML is designed to store and transport dataXML is designed to be self-descriptive XML stands for extensible Markup Language XML is a markup language like HTML XML is designed to store and transport data XML is designed to be self-descriptive Differences between XML and HTML XML and HTML were designed with different goals: XML is designed to carry data emphasizing on what type of data it is. HTML is designed to display data emphasizing on how data looks XML tags are not predefined like HTML tags. HTML is a markup language whereas XML provides a framework for defining markup languages. HTML is about displaying data,hence it is static whereas XML is about carrying information,which makes it dynamic. EXAMPLE :XML code for a note is given below HTML code for the note is given below <!DOCTYPE html><html><h1>Note</h1><body><p>To:RAJ<br>From:RAVI</p><h1>Reminder</h1><p>Meeting at 8am</p></body></html> OUTPUT: Note: The output in both the cases is same but while using HTML we have used predefined tags like p tag and h1 tag whereas while using XML we have used self defined tags like “To” tag and “from” tag. Another Example:The XML above is quite self-descriptive: It has sender information. It has receiver information. It has a heading. It has a message body. The tags in the example below are not defined in any XML standard. These tags are “invented” by the author of the XML document.HTML works with predefined tags like p tag, h1 tag, etc.While in XML, the author must define both the tags and the document structure. Input: Output: Basically XML above does not do anything. XML is just information wrapped in tags. Users must require a piece of software to send, receive, store, or display it. XML makes web development User Friendly : Many computer systems contain data in incompatible formats. Exchanging data between incompatible systems or upgraded systems is a time-consuming task for web developers. Large amounts of data must be converted, and incompatible data is often lost. XML stores data in plain text format. This provides a software- and hardware-independent way of storing, transporting, and sharing data. XML is Extensible: XML applications will work as expected even if data is edited i.e. added or removed. Example :The above note is edited into a newer version by adding date tag and hour tag , and by removing the heading tag.Previous version New VersionQuiz on HTML and XML This article is contributed by Shubrodeep Banerjee. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. anshitaagarwal HTML and XML Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n29 Oct, 2020" }, { "code": null, "e": 569, "s": 54, "text": "Extensible Markup Language (XML) is a markup language that defines a set of rules for encoding documents in a format that is both human-readable and machine-readable. The design goals of XML focus on simplicity, generality, and usability across the Internet. It is a textual data format with strong support via Unicode for different human languages. Although the design of XML focuses on documents, the language is widely used for the representation of arbitrary data structures such as those used in web services." }, { "code": null, "e": 726, "s": 569, "text": "XML stands for extensible Markup LanguageXML is a markup language like HTMLXML is designed to store and transport dataXML is designed to be self-descriptive" }, { "code": null, "e": 768, "s": 726, "text": "XML stands for extensible Markup Language" }, { "code": null, "e": 803, "s": 768, "text": "XML is a markup language like HTML" }, { "code": null, "e": 847, "s": 803, "text": "XML is designed to store and transport data" }, { "code": null, "e": 886, "s": 847, "text": "XML is designed to be self-descriptive" }, { "code": null, "e": 919, "s": 886, "text": "Differences between XML and HTML" }, { "code": null, "e": 968, "s": 919, "text": "XML and HTML were designed with different goals:" }, { "code": null, "e": 1038, "s": 968, "text": "XML is designed to carry data emphasizing on what type of data it is." }, { "code": null, "e": 1101, "s": 1038, "text": "HTML is designed to display data emphasizing on how data looks" }, { "code": null, "e": 1145, "s": 1101, "text": "XML tags are not predefined like HTML tags." }, { "code": null, "e": 1235, "s": 1145, "text": "HTML is a markup language whereas XML provides a framework for defining markup languages." }, { "code": null, "e": 1350, "s": 1235, "text": "HTML is about displaying data,hence it is static whereas XML is about carrying information,which makes it dynamic." }, { "code": null, "e": 1394, "s": 1350, "text": "EXAMPLE :XML code for a note is given below" }, { "code": null, "e": 1432, "s": 1394, "text": "HTML code for the note is given below" }, { "code": "<!DOCTYPE html><html><h1>Note</h1><body><p>To:RAJ<br>From:RAVI</p><h1>Reminder</h1><p>Meeting at 8am</p></body></html>", "e": 1551, "s": 1432, "text": null }, { "code": null, "e": 1560, "s": 1551, "text": "OUTPUT: " }, { "code": null, "e": 1760, "s": 1560, "text": "Note: The output in both the cases is same but while using HTML we have used predefined tags like p tag and h1 tag whereas while using XML we have used self defined tags like “To” tag and “from” tag." }, { "code": null, "e": 1817, "s": 1760, "text": "Another Example:The XML above is quite self-descriptive:" }, { "code": null, "e": 1844, "s": 1817, "text": "It has sender information." }, { "code": null, "e": 1873, "s": 1844, "text": "It has receiver information." }, { "code": null, "e": 1891, "s": 1873, "text": "It has a heading." }, { "code": null, "e": 1914, "s": 1891, "text": "It has a message body." }, { "code": null, "e": 2176, "s": 1914, "text": "The tags in the example below are not defined in any XML standard. These tags are “invented” by the author of the XML document.HTML works with predefined tags like p tag, h1 tag, etc.While in XML, the author must define both the tags and the document structure." }, { "code": null, "e": 2183, "s": 2176, "text": "Input:" }, { "code": null, "e": 2191, "s": 2183, "text": "Output:" }, { "code": null, "e": 2353, "s": 2191, "text": "Basically XML above does not do anything. XML is just information wrapped in tags. Users must require a piece of software to send, receive, store, or display it." }, { "code": null, "e": 2780, "s": 2353, "text": "XML makes web development User Friendly : Many computer systems contain data in incompatible formats. Exchanging data between incompatible systems or upgraded systems is a time-consuming task for web developers. Large amounts of data must be converted, and incompatible data is often lost. XML stores data in plain text format. This provides a software- and hardware-independent way of storing, transporting, and sharing data." }, { "code": null, "e": 3022, "s": 2780, "text": "XML is Extensible: XML applications will work as expected even if data is edited i.e. added or removed. Example :The above note is edited into a newer version by adding date tag and hour tag , and by removing the heading tag.Previous version" }, { "code": null, "e": 3055, "s": 3022, "text": " New VersionQuiz on HTML and XML" }, { "code": null, "e": 3362, "s": 3055, "text": "This article is contributed by Shubrodeep Banerjee. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 3487, "s": 3362, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 3502, "s": 3487, "text": "anshitaagarwal" }, { "code": null, "e": 3515, "s": 3502, "text": "HTML and XML" }, { "code": null, "e": 3532, "s": 3515, "text": "Web Technologies" } ]
PyQt5 QListWidget – Getting Current Selected Row
01 Aug, 2020 In this article we will see how we can get the current selected row of the QListWidget. QListWidget is a convenience class that provides a list view with a classic item-based interface for adding and removing items. QListWidget uses an internal model to manage each QListWidgetItem in the list. Current row property holds the row of the current item. Depending on the current selection mode, the row may also be selected with the help of setCurrentRow method. In order to do this we will use currentRow method with the list widget object. Syntax : list_widget.currentRow() Argument : It takes no argument Return : It returns integer Below is the implementation # importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 500, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a QListWidget list_widget = QListWidget(self) # setting geometry to it list_widget.setGeometry(50, 70, 150, 60) # list widget items item1 = QListWidgetItem("A") item2 = QListWidgetItem("B") item3 = QListWidgetItem("C") # adding items to the list widget list_widget.addItem(item1) list_widget.addItem(item2) list_widget.addItem(item3) # setting current row list_widget.setCurrentRow(2) # creating a label label = QLabel("GeesforGeeks", self) # setting geometry to the label label.setGeometry(230, 80, 300, 80) # making label multi line label.setWordWrap(True) # getting current selected row value = list_widget.currentRow() # setting text to the label label.setText("Current Selected Row : " + str(value)) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec()) Output : Python PyQt-QListWidget Python-gui Python-PyQt Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Convert integer to string in Python Python OOPs Concepts
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Aug, 2020" }, { "code": null, "e": 488, "s": 28, "text": "In this article we will see how we can get the current selected row of the QListWidget. QListWidget is a convenience class that provides a list view with a classic item-based interface for adding and removing items. QListWidget uses an internal model to manage each QListWidgetItem in the list. Current row property holds the row of the current item. Depending on the current selection mode, the row may also be selected with the help of setCurrentRow method." }, { "code": null, "e": 567, "s": 488, "text": "In order to do this we will use currentRow method with the list widget object." }, { "code": null, "e": 601, "s": 567, "text": "Syntax : list_widget.currentRow()" }, { "code": null, "e": 633, "s": 601, "text": "Argument : It takes no argument" }, { "code": null, "e": 661, "s": 633, "text": "Return : It returns integer" }, { "code": null, "e": 689, "s": 661, "text": "Below is the implementation" }, { "code": "# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 500, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a QListWidget list_widget = QListWidget(self) # setting geometry to it list_widget.setGeometry(50, 70, 150, 60) # list widget items item1 = QListWidgetItem(\"A\") item2 = QListWidgetItem(\"B\") item3 = QListWidgetItem(\"C\") # adding items to the list widget list_widget.addItem(item1) list_widget.addItem(item2) list_widget.addItem(item3) # setting current row list_widget.setCurrentRow(2) # creating a label label = QLabel(\"GeesforGeeks\", self) # setting geometry to the label label.setGeometry(230, 80, 300, 80) # making label multi line label.setWordWrap(True) # getting current selected row value = list_widget.currentRow() # setting text to the label label.setText(\"Current Selected Row : \" + str(value)) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())", "e": 2265, "s": 689, "text": null }, { "code": null, "e": 2274, "s": 2265, "text": "Output :" }, { "code": null, "e": 2298, "s": 2274, "text": "Python PyQt-QListWidget" }, { "code": null, "e": 2309, "s": 2298, "text": "Python-gui" }, { "code": null, "e": 2321, "s": 2309, "text": "Python-PyQt" }, { "code": null, "e": 2328, "s": 2321, "text": "Python" }, { "code": null, "e": 2426, "s": 2328, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2444, "s": 2426, "text": "Python Dictionary" }, { "code": null, "e": 2486, "s": 2444, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2508, "s": 2486, "text": "Enumerate() in Python" }, { "code": null, "e": 2534, "s": 2508, "text": "Python String | replace()" }, { "code": null, "e": 2566, "s": 2534, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2595, "s": 2566, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2622, "s": 2595, "text": "Python Classes and Objects" }, { "code": null, "e": 2652, "s": 2622, "text": "Iterate over a list in Python" }, { "code": null, "e": 2688, "s": 2652, "text": "Convert integer to string in Python" } ]
Java program to implement selection sort
Selection sort is a simple sorting algorithm. This sorting algorithm is an in-place comparison-based algorithm in which the list is divided into two parts, the sorted part at the left end and the unsorted part at the right end. Initially, the sorted part is empty and the unsorted part is the entire list. The smallest element is selected from the unsorted array and swapped with the leftmost element, and that element becomes a part of the sorted array. This process continues moving unsorted array boundary from one element to the right. 1.Set MIN to location 0 2.Search the minimum element in the list 3.Swap with value at location MIN 4.Increment MIN to point to next element 5.Repeat until the list is sorted Live Demo public class SelectionSort { public static void main(String args[]){ int array[] = {10, 20, 25, 63, 96, 57}; int size = array.length; for (int i = 0 ;i< size-1; i++){ int min = i; for (int j = i+1; j<size; j++){ if (array[j] < array[min]){ min = j; } } int temp = array[min]; array[min] = array[i]; array[i] = temp; } for (int i = 0 ;i< size; i++){ System.out.print(" "+array[i]); } } }
[ { "code": null, "e": 1368, "s": 1062, "text": "Selection sort is a simple sorting algorithm. This sorting algorithm is an in-place comparison-based algorithm in which the list is divided into two parts, the sorted part at the left end and the unsorted part at the right end. Initially, the sorted part is empty and the unsorted part is the entire list." }, { "code": null, "e": 1602, "s": 1368, "text": "The smallest element is selected from the unsorted array and swapped with the leftmost element, and that element becomes a part of the sorted array. This process continues moving unsorted array boundary from one element to the right." }, { "code": null, "e": 1776, "s": 1602, "text": "1.Set MIN to location 0\n2.Search the minimum element in the list\n3.Swap with value at location MIN\n4.Increment MIN to point to next element\n5.Repeat until the list is sorted" }, { "code": null, "e": 1786, "s": 1776, "text": "Live Demo" }, { "code": null, "e": 2319, "s": 1786, "text": "public class SelectionSort {\n public static void main(String args[]){\n int array[] = {10, 20, 25, 63, 96, 57};\n int size = array.length;\n\n for (int i = 0 ;i< size-1; i++){\n int min = i;\n\n for (int j = i+1; j<size; j++){\n if (array[j] < array[min]){\n min = j;\n }\n }\n int temp = array[min];\n array[min] = array[i];\n array[i] = temp;\n }\n\n for (int i = 0 ;i< size; i++){\n System.out.print(\" \"+array[i]);\n }\n } \n}" } ]
How to check if an alert exists using WebDriver?
We can check if an alert exists with Selenium webdriver. An alert is created with the help of Javascript. We shall use the explicit wait concept in synchronization to verify the presence of an alert. Let us consider the below alert and check its presence on the page. There is a condition called alertIsPresent which we will use to check for alerts. It shall wait for a specified amount of time for the alert after which it shall throw an exception. We need to import org.openqa.selenium.support.ui.ExpectedConditions and import org.openqa.selenium.support.ui.WebDriverWait to incorporate expected conditions and WebDriverWait class. import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; import org.openqa.selenium.support.ui.WebDriverWait; import org.openqa.selenium.support.ui.ExpectedConditions; public class VerifyAlert{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver","C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); String u ="https://www.tutorialspoint.com/selenium/selenium_automation_practice.htm"driver.get(u); driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); // identify and click submit WebElement t = driver.findElement(By.name("submit")); t.click(); // Explicit wait condition for alert WebDriverWait w = new WebDriverWait(driver, 5); //alertIsPresent() condition applied if(w.until(ExpectedConditions.alertIsPresent())==null) System.out.println("Alert not exists"); else System.out.println("Alert exists"); driver.close(); } }
[ { "code": null, "e": 1262, "s": 1062, "text": "We can check if an alert exists with Selenium webdriver. An alert is created with the help of Javascript. We shall use the explicit wait concept in synchronization to verify the presence of an alert." }, { "code": null, "e": 1512, "s": 1262, "text": "Let us consider the below alert and check its presence on the page. There is a condition called alertIsPresent which we will use to check for alerts. It shall wait for\na specified amount of time for the alert after which it shall throw an exception." }, { "code": null, "e": 1696, "s": 1512, "text": "We need to import org.openqa.selenium.support.ui.ExpectedConditions and import org.openqa.selenium.support.ui.WebDriverWait to incorporate expected conditions and WebDriverWait class." }, { "code": null, "e": 2834, "s": 1696, "text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport java.util.concurrent.TimeUnit;\nimport org.openqa.selenium.support.ui.WebDriverWait;\nimport org.openqa.selenium.support.ui.ExpectedConditions;\n\npublic class VerifyAlert{\n public static void main(String[] args) {\nSystem.setProperty(\"webdriver.chrome.driver\",\"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n String u =\"https://www.tutorialspoint.com/selenium/selenium_automation_practice.htm\"driver.get(u);\n driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);\n // identify and click submit\n WebElement t = driver.findElement(By.name(\"submit\"));\n t.click();\n // Explicit wait condition for alert\n WebDriverWait w = new WebDriverWait(driver, 5);\n //alertIsPresent() condition applied\n if(w.until(ExpectedConditions.alertIsPresent())==null)\n System.out.println(\"Alert not exists\");\n else\n System.out.println(\"Alert exists\");\n driver.close();\n }\n}" } ]
Understand how your TensorFlow Model is Making Predictions | by Karl Weinmeister | Towards Data Science
Machine learning can answer questions more quickly and accurately than ever before. As machine learning is used in more mission-critical applications, it is increasingly important to understand how these predictions are derived. In this blog post, we’ll build a neural network model using the Keras API from TensorFlow, an open-source machine learning framework. One our model is trained, we’ll integrate it with SHAP, an interpretability library. We’ll use SHAP to learn which factors are correlated with the model predictions. Our model will be predicting the graduation debt of a university’s graduates, relative to their future earnings. This debt-to-earnings ratio is intended to be a rough indicator of a university’s return on investment (ROI). The data comes from the US Department of Education’s College Scorecard, an interactive website that makes its data publicly available. The features in the model are listed in the table below. More details on the dataset can be found in the data documentation. +-------------------------+--------------------------------------+| Feature | Description |+-------------------------+--------------------------------------+| ADM_RATE | Admission rate || SAT_AVG | SAT average || TRANS_4 | Transfer rate || NPT4 | Net price (list price - average aid) || INC_N | Family income || PUBLIC | Public institution || UGDS | Number of undergraduate students || PPTUG_EF | % part-time students || FIRST_GEN | % first-generation students || MD_INC_COMP_ORIG_YR4_RT | % completed within 4 years |+-------------------------+--------------------------------------+ We derive the target variable (debt-to-earnings ratio) from the debt and earnings data available in the dataset. Specifically, it is the median debt accumulated at graduation (MD_INC_DEBT_MDN), divided by the mean earnings 6 years after graduation (MN_EARN_WNE_INC2_P6). Scatter plots were created to visualize each feature’s correlation with our target variable. Each chart below shows the feature on the X-axis and the debt/earnings ratio on the Y-axis. We’ll use a Sequential model with 2 densely-connected hidden layers and a ReLU activation function: model = keras.Sequential([ layers.Dense(16, activation=tf.nn.relu, input_shape=[len(df.keys())]), layers.Dense(16, activation=tf.nn.relu), layers.Dense(1) Below we see a plot of the training process. The widening gap between the training and validation error indicates some over-fitting. The over-fitting is most likely due to the limited number of samples (1,117) in the dataset with all of the required features. Nonetheless, given that the mean debt-to-earnings ratio is approximately 0.45, a mean absolute error of 0.1 demonstrates a meaningful prediction. To run the notebook directly in your browser, you can use Colab. It is also available in Github. The issue of college debt, which we are investigating in this blog post, has strong links to broader socio-economic issues. Any model and its training data should be carefully evaluated to ensure it is serving all of its users equitably. For example, if our training data included mostly schools where students attend from high-income households, the model’s predictions would misrepresent schools whose students typically have many student loans. Where possible, data values have been filtered for middle-income students, to provide a consistent analysis across universities with students of varying household income levels. The College Scorecard data defines the middle-income segment as students with family household incomes between $30,000 and $75,000. Not all of the available data provides this filter, but it is available for key features such as the net price, earnings, debt, and completion rates. With this thought process in mind, the analysis can be further expanded to other facets in the dataset. It is also worth noting that interpretability reveals which features contribute most to a model’s predictions. It does not indicate whether there is a causal relationship between the features and predictions. Interpretability is essentially the ability to understand what is happening in a model. There is often a tradeoff between a model’s accuracy and its interpretability. Simple linear models can be straightforward to understand, as they directly expose the variables and coefficients. Non-linear models, including those derived by neural networks or gradient-boosted trees, can be much more difficult to interpret. Enter SHAP. SHAP, or SHapley Additive exPlanations, is a Python library created by Scott Lundberg that can explain the output of many machine learning frameworks. It can help explain an individual prediction or summarize predictions across a larger population. SHAP works by perturbing input data to assess the impact of each feature. Each feature’s contribution is averaged across all possible feature interactions. This approach is based on the concept of Shapley values from game theory. It provides a robust approximation, which can be more computationally expensive relative to other approaches like LIME. More details on SHAP theory can be found in the library author’s 2017 NeurIPS paper. SHAP provides several Explainer classes that use different implementations but all leverage the Shapley value based approach. In this blog post, we’ll demonstrate how to use the KernelExplainer and DeepExplainer classes. KernelExplainer is model-agnostic, as it takes the model predictions and training data as input. DeepExplainer is optimized for deep-learning frameworks (TensorFlow / Keras). The SHAP DeepExplainer currently does not support eager execution mode or TensorFlow 2.0. However, KernelExplainer will work just fine, although it is significantly slower. Let’s start with using the KernelExplainer to draw a summary plot of the model. We will first summarize the training data into n clusters. This is an optional but helpful step, because the time to generate Shapley values increases exponentially with the size of the dataset. # Summarize the training set to accelerate analysisdf_train_normed_summary = shap.kmeans(df_train_normed.values, 25)# Instantiate an explainer with the model predictions and training data summaryexplainer = shap.KernelExplainer(model.predict, df_train_normed_summary)# Extract Shapley values from the explainershap_values = explainer.shap_values(df_train_normed.values)# Summarize the Shapley values in a plotshap.summary_plot(shap_values[0], df_train_normed) The summary plot displays a distribution of Shapley values for each feature. The color of each point is on a spectrum where highest values for that feature are red, and lowest values are blue. The features are ranked by the sum of the absolute values of the Shapley values. Let’s look at some relationships from the plot. The first three features with the highest contribution are the average SAT score, % of first-generation students, and % part-time enrollment. Note that each of these features have predominantly blue dots (low feature values) on the right-side where there are positive SHAP values. This tells us that low values for these features lead our model to predict a high DTE ratio. The fourth feature in the list, net price, has an opposite relationship, where a higher net price is associated with a higher DTE ratio. It is also possible to explain one particular instance, using the force_plot() function: # Plot the SHAP values for one instanceINSTANCE_NUM = 0shap.force_plot(explainer.expected_value[0], shap_values[0][INSTANCE_NUM], df_train.iloc[INSTANCE_NUM,:]) In this particular example, the college’s SAT average contributed most to its DTE prediction of 0.53, pushing its value higher. The completion rate (MD_INC_COMP_ORIG_YR4_RT) was the second most important feature, pushing the prediction lower. The values shown series of SHAP values can also be reviewed, across the whole data set, or a slice of n instances as shown here: # Plot the SHAP values for multiple instancesNUM_ROWS = 10shap.force_plot(explainer.expected_value[0], shap_values[0][0:NUM_ROWS], df_train.iloc[0:NUM_ROWS]) SHAP will split the feature contribution across correlated variables. This is important to keep in mind when selecting features for a model, and when analyzing feature importances. Let’s calculate the correlation matrix and see what we find: corr = df.corr()sns.heatmap(corr) Let’s cross-reference our top three features from the summary plot with the correlation matrix, to see which ones might be split: SAT average is correlated with the completion rate, and inversely correlated with admission rate and first-generation ratio. First-generation ratio is correlated with the part-time ratio, and inversely correlated with the completion rate. Several of the correlated features were grouped in the top of the summary plot list. It’s worth keeping an eye on the completion rate and admission rate, which were lower in the list. SHAP has a dependence_plot() function which can help reveal more details. For example, let’s look at the interaction between the first-generation ratio and the part-time ratio. As we observed in the summary plot, we can see that that the first-generation ratio is inversely correlated with its Shapley values. The dependency plot also shows us that the correlation is stronger when the university has a lower proportion of part-time students. shap.dependence_plot('FIRST_GEN', shap_values[0], df_train, interaction_index='PPTUG_EF') In this blog post, we demonstrated how to interpret a tf.keras model with SHAP. We also reviewed how to use the SHAP APIs and several SHAP plot types. Finally, for a complete and accurate picture, we discussed considerations about fairness and correlated variables. You now have the tools to better understand what’s happening in your TensorFlow Keras models! For more info on what I covered here, check out these resources: Colab notebook to run the model from your browser GitHub repository with notebook Getting started with tf.keras SHAP GitHub repository Let me know what you think on Twitter!
[ { "code": null, "e": 401, "s": 172, "text": "Machine learning can answer questions more quickly and accurately than ever before. As machine learning is used in more mission-critical applications, it is increasingly important to understand how these predictions are derived." }, { "code": null, "e": 701, "s": 401, "text": "In this blog post, we’ll build a neural network model using the Keras API from TensorFlow, an open-source machine learning framework. One our model is trained, we’ll integrate it with SHAP, an interpretability library. We’ll use SHAP to learn which factors are correlated with the model predictions." }, { "code": null, "e": 1059, "s": 701, "text": "Our model will be predicting the graduation debt of a university’s graduates, relative to their future earnings. This debt-to-earnings ratio is intended to be a rough indicator of a university’s return on investment (ROI). The data comes from the US Department of Education’s College Scorecard, an interactive website that makes its data publicly available." }, { "code": null, "e": 1184, "s": 1059, "text": "The features in the model are listed in the table below. More details on the dataset can be found in the data documentation." }, { "code": null, "e": 2109, "s": 1184, "text": "+-------------------------+--------------------------------------+| Feature | Description |+-------------------------+--------------------------------------+| ADM_RATE | Admission rate || SAT_AVG | SAT average || TRANS_4 | Transfer rate || NPT4 | Net price (list price - average aid) || INC_N | Family income || PUBLIC | Public institution || UGDS | Number of undergraduate students || PPTUG_EF | % part-time students || FIRST_GEN | % first-generation students || MD_INC_COMP_ORIG_YR4_RT | % completed within 4 years |+-------------------------+--------------------------------------+" }, { "code": null, "e": 2380, "s": 2109, "text": "We derive the target variable (debt-to-earnings ratio) from the debt and earnings data available in the dataset. Specifically, it is the median debt accumulated at graduation (MD_INC_DEBT_MDN), divided by the mean earnings 6 years after graduation (MN_EARN_WNE_INC2_P6)." }, { "code": null, "e": 2565, "s": 2380, "text": "Scatter plots were created to visualize each feature’s correlation with our target variable. Each chart below shows the feature on the X-axis and the debt/earnings ratio on the Y-axis." }, { "code": null, "e": 2665, "s": 2565, "text": "We’ll use a Sequential model with 2 densely-connected hidden layers and a ReLU activation function:" }, { "code": null, "e": 2829, "s": 2665, "text": "model = keras.Sequential([ layers.Dense(16, activation=tf.nn.relu, input_shape=[len(df.keys())]), layers.Dense(16, activation=tf.nn.relu), layers.Dense(1)" }, { "code": null, "e": 3235, "s": 2829, "text": "Below we see a plot of the training process. The widening gap between the training and validation error indicates some over-fitting. The over-fitting is most likely due to the limited number of samples (1,117) in the dataset with all of the required features. Nonetheless, given that the mean debt-to-earnings ratio is approximately 0.45, a mean absolute error of 0.1 demonstrates a meaningful prediction." }, { "code": null, "e": 3332, "s": 3235, "text": "To run the notebook directly in your browser, you can use Colab. It is also available in Github." }, { "code": null, "e": 3780, "s": 3332, "text": "The issue of college debt, which we are investigating in this blog post, has strong links to broader socio-economic issues. Any model and its training data should be carefully evaluated to ensure it is serving all of its users equitably. For example, if our training data included mostly schools where students attend from high-income households, the model’s predictions would misrepresent schools whose students typically have many student loans." }, { "code": null, "e": 4240, "s": 3780, "text": "Where possible, data values have been filtered for middle-income students, to provide a consistent analysis across universities with students of varying household income levels. The College Scorecard data defines the middle-income segment as students with family household incomes between $30,000 and $75,000. Not all of the available data provides this filter, but it is available for key features such as the net price, earnings, debt, and completion rates." }, { "code": null, "e": 4553, "s": 4240, "text": "With this thought process in mind, the analysis can be further expanded to other facets in the dataset. It is also worth noting that interpretability reveals which features contribute most to a model’s predictions. It does not indicate whether there is a causal relationship between the features and predictions." }, { "code": null, "e": 4965, "s": 4553, "text": "Interpretability is essentially the ability to understand what is happening in a model. There is often a tradeoff between a model’s accuracy and its interpretability. Simple linear models can be straightforward to understand, as they directly expose the variables and coefficients. Non-linear models, including those derived by neural networks or gradient-boosted trees, can be much more difficult to interpret." }, { "code": null, "e": 5226, "s": 4965, "text": "Enter SHAP. SHAP, or SHapley Additive exPlanations, is a Python library created by Scott Lundberg that can explain the output of many machine learning frameworks. It can help explain an individual prediction or summarize predictions across a larger population." }, { "code": null, "e": 5661, "s": 5226, "text": "SHAP works by perturbing input data to assess the impact of each feature. Each feature’s contribution is averaged across all possible feature interactions. This approach is based on the concept of Shapley values from game theory. It provides a robust approximation, which can be more computationally expensive relative to other approaches like LIME. More details on SHAP theory can be found in the library author’s 2017 NeurIPS paper." }, { "code": null, "e": 6057, "s": 5661, "text": "SHAP provides several Explainer classes that use different implementations but all leverage the Shapley value based approach. In this blog post, we’ll demonstrate how to use the KernelExplainer and DeepExplainer classes. KernelExplainer is model-agnostic, as it takes the model predictions and training data as input. DeepExplainer is optimized for deep-learning frameworks (TensorFlow / Keras)." }, { "code": null, "e": 6230, "s": 6057, "text": "The SHAP DeepExplainer currently does not support eager execution mode or TensorFlow 2.0. However, KernelExplainer will work just fine, although it is significantly slower." }, { "code": null, "e": 6505, "s": 6230, "text": "Let’s start with using the KernelExplainer to draw a summary plot of the model. We will first summarize the training data into n clusters. This is an optional but helpful step, because the time to generate Shapley values increases exponentially with the size of the dataset." }, { "code": null, "e": 6965, "s": 6505, "text": "# Summarize the training set to accelerate analysisdf_train_normed_summary = shap.kmeans(df_train_normed.values, 25)# Instantiate an explainer with the model predictions and training data summaryexplainer = shap.KernelExplainer(model.predict, df_train_normed_summary)# Extract Shapley values from the explainershap_values = explainer.shap_values(df_train_normed.values)# Summarize the Shapley values in a plotshap.summary_plot(shap_values[0], df_train_normed)" }, { "code": null, "e": 7239, "s": 6965, "text": "The summary plot displays a distribution of Shapley values for each feature. The color of each point is on a spectrum where highest values for that feature are red, and lowest values are blue. The features are ranked by the sum of the absolute values of the Shapley values." }, { "code": null, "e": 7798, "s": 7239, "text": "Let’s look at some relationships from the plot. The first three features with the highest contribution are the average SAT score, % of first-generation students, and % part-time enrollment. Note that each of these features have predominantly blue dots (low feature values) on the right-side where there are positive SHAP values. This tells us that low values for these features lead our model to predict a high DTE ratio. The fourth feature in the list, net price, has an opposite relationship, where a higher net price is associated with a higher DTE ratio." }, { "code": null, "e": 7887, "s": 7798, "text": "It is also possible to explain one particular instance, using the force_plot() function:" }, { "code": null, "e": 8048, "s": 7887, "text": "# Plot the SHAP values for one instanceINSTANCE_NUM = 0shap.force_plot(explainer.expected_value[0], shap_values[0][INSTANCE_NUM], df_train.iloc[INSTANCE_NUM,:])" }, { "code": null, "e": 8420, "s": 8048, "text": "In this particular example, the college’s SAT average contributed most to its DTE prediction of 0.53, pushing its value higher. The completion rate (MD_INC_COMP_ORIG_YR4_RT) was the second most important feature, pushing the prediction lower. The values shown series of SHAP values can also be reviewed, across the whole data set, or a slice of n instances as shown here:" }, { "code": null, "e": 8578, "s": 8420, "text": "# Plot the SHAP values for multiple instancesNUM_ROWS = 10shap.force_plot(explainer.expected_value[0], shap_values[0][0:NUM_ROWS], df_train.iloc[0:NUM_ROWS])" }, { "code": null, "e": 8820, "s": 8578, "text": "SHAP will split the feature contribution across correlated variables. This is important to keep in mind when selecting features for a model, and when analyzing feature importances. Let’s calculate the correlation matrix and see what we find:" }, { "code": null, "e": 8854, "s": 8820, "text": "corr = df.corr()sns.heatmap(corr)" }, { "code": null, "e": 8984, "s": 8854, "text": "Let’s cross-reference our top three features from the summary plot with the correlation matrix, to see which ones might be split:" }, { "code": null, "e": 9109, "s": 8984, "text": "SAT average is correlated with the completion rate, and inversely correlated with admission rate and first-generation ratio." }, { "code": null, "e": 9223, "s": 9109, "text": "First-generation ratio is correlated with the part-time ratio, and inversely correlated with the completion rate." }, { "code": null, "e": 9407, "s": 9223, "text": "Several of the correlated features were grouped in the top of the summary plot list. It’s worth keeping an eye on the completion rate and admission rate, which were lower in the list." }, { "code": null, "e": 9850, "s": 9407, "text": "SHAP has a dependence_plot() function which can help reveal more details. For example, let’s look at the interaction between the first-generation ratio and the part-time ratio. As we observed in the summary plot, we can see that that the first-generation ratio is inversely correlated with its Shapley values. The dependency plot also shows us that the correlation is stronger when the university has a lower proportion of part-time students." }, { "code": null, "e": 9940, "s": 9850, "text": "shap.dependence_plot('FIRST_GEN', shap_values[0], df_train, interaction_index='PPTUG_EF')" }, { "code": null, "e": 10300, "s": 9940, "text": "In this blog post, we demonstrated how to interpret a tf.keras model with SHAP. We also reviewed how to use the SHAP APIs and several SHAP plot types. Finally, for a complete and accurate picture, we discussed considerations about fairness and correlated variables. You now have the tools to better understand what’s happening in your TensorFlow Keras models!" }, { "code": null, "e": 10365, "s": 10300, "text": "For more info on what I covered here, check out these resources:" }, { "code": null, "e": 10415, "s": 10365, "text": "Colab notebook to run the model from your browser" }, { "code": null, "e": 10447, "s": 10415, "text": "GitHub repository with notebook" }, { "code": null, "e": 10477, "s": 10447, "text": "Getting started with tf.keras" }, { "code": null, "e": 10500, "s": 10477, "text": "SHAP GitHub repository" } ]
Playit
#myDIV { background-color:lightblue; transform:translate(10px);}
[]
Finding word starting with specific letter in JavaScript
We are required to write a JavaScript function that takes in an array of string literals as the first argument and a single string character as the second argument. Then our function should find and return the first array entry that starts with the character specified by the second argument. The code for this will be − const names = ['Naman', 'Kartik', 'Anmol', 'Rajat', 'Keshav', 'Harsh', 'Suresh', 'Rahul']; const firstIndexOf = (arr = [], char = '') => { for(let i = 0; i < arr.length; i++){ const el = arr[i]; if(el.substring(0, 1) === char){ return i; }; }; return -1; }; console.log(firstIndexOf(names, 'K')); console.log(firstIndexOf(names, 'R')); console.log(firstIndexOf(names, 'J')); And the output in the console will be − 1 3 -1
[ { "code": null, "e": 1227, "s": 1062, "text": "We are required to write a JavaScript function that takes in an array of string literals as the first argument and a single string character as the second argument." }, { "code": null, "e": 1355, "s": 1227, "text": "Then our function should find and return the first array entry that starts with the character specified by the second argument." }, { "code": null, "e": 1383, "s": 1355, "text": "The code for this will be −" }, { "code": null, "e": 1794, "s": 1383, "text": "const names = ['Naman', 'Kartik', 'Anmol', 'Rajat', 'Keshav', 'Harsh', 'Suresh', 'Rahul'];\nconst firstIndexOf = (arr = [], char = '') => {\n for(let i = 0; i < arr.length; i++){\n const el = arr[i];\n if(el.substring(0, 1) === char){\n return i;\n };\n };\n return -1;\n};\nconsole.log(firstIndexOf(names, 'K'));\nconsole.log(firstIndexOf(names, 'R'));\nconsole.log(firstIndexOf(names, 'J'));" }, { "code": null, "e": 1834, "s": 1794, "text": "And the output in the console will be −" }, { "code": null, "e": 1841, "s": 1834, "text": "1\n3\n-1" } ]
How to use RecyclerView inside NestedScrollView in Android?
This example demonstrates how do I use RecyclerView inside NestedScrollView 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. Add the following dependency in the build.gradle (Module: app) implementation 'com.android.support:appcompat-v7:28.0.0' implementation 'com.android.support:design:28.0.0' implementation 'com.android.support:recyclerview-v7:28.0.0' implementation 'com.android.support:cardview-v7:28.0.0' implementation 'com.intuit.sdp:sdp-android:1.0.3' 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:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <androidx.core.widget.NestedScrollView android:layout_width="match_parent" android:layout_height="wrap_content" android:scrollbars="none"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:focusableInTouchMode="true" android:orientation="vertical"> <ImageView android:id="@+id/sellerProduct" android:layout_width="match_parent" android:layout_height="200dp" android:adjustViewBounds="true" android:src="@drawable/iphone" android:scaleType="fitXY" android:contentDescription="@string/app_name" /> <androidx.recyclerview.widget.RecyclerView android:layout_width="match_parent" android:layout_height="match_parent" android:scrollbars="vertical" android:id="@+id/productList"/> </LinearLayout> </androidx.core.widget.NestedScrollView> </LinearLayout> Step 3 − Create a layout resource file (list_item.xml) and add the following code − <?xml version="1.0" encoding="utf-8"?> <androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" app:cardElevation="2dp" app:cardUseCompatPadding="true"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:orientation="vertical" android:padding="8dp"> <ImageView android:id="@+id/phoneImage" android:layout_width="wrap_content" android:layout_height="wrap_content" android:adjustViewBounds="true" android:contentDescription="TODO" android:src="@drawable/iphone2" /> <TextView android:id="@+id/phoneName" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:text="IPHONE" android:textColor="@color/colorPrimaryDark" android:textSize="12sp" android:textStyle="bold" /> </LinearLayout> </androidx.cardview.widget.CardView> Step 4 − Create java class files as mentioned below and add the respective codes − PhoneAdapter.java − import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import java.util.List; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; public class PhoneAdapter extends RecyclerView.Adapter<PhoneViewHolder>{ private Context context; private List<ProductObject> productList; PhoneAdapter(Context context, List<ProductObject> productList) { this.context = context; this.productList = productList; } @NonNull @Override public PhoneViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, parent, false); return new PhoneViewHolder(view); } @Override public void onBindViewHolder(PhoneViewHolder holder, int position){ ProductObject productObject = productList.get(position); int imageRes = getResourceId(context, productObject.getImagePath(), context.getPackageName()); holder.phoneImage.setImageResource(imageRes); holder.phoneName.setText(productObject.getName()); } @Override public int getItemCount() { return productList.size(); } private static int getResourceId(Context context, String pVariableName, String pPackageName) throws RuntimeException { try { return context.getResources().getIdentifier(pVariableName, "drawable", pPackageName); } catch (Exception e) { throw new RuntimeException("Error getting Resource ID.", e); } } } PhoneViewHolder.java − import android.view.View; import android.widget.ImageView; import android.widget.TextView; import androidx.recyclerview.widget.RecyclerView; class PhoneViewHolder extends RecyclerView.ViewHolder { ImageView phoneImage; TextView phoneName; PhoneViewHolder(View itemView) { super(itemView); phoneName = itemView.findViewById(R.id.phoneName); phoneImage = itemView.findViewById(R.id.phoneImage); } } ProductObject.java − class ProductObject { private String imagePath; private String name; ProductObject(String name, String imagePath) { this.imagePath = imagePath; this.name = name; } String getImagePath() { return imagePath; } String getName() { return name; } } Step 5 − Add the following code to src/MainActivity.java import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.GridLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.os.Bundle; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); RecyclerView bestRecyclerView = findViewById(R.id.productList); GridLayoutManager mGrid = new GridLayoutManager(this, 2); bestRecyclerView.setLayoutManager(mGrid); bestRecyclerView.setHasFixedSize(true); PhoneAdapter mAdapter = new PhoneAdapter(MainActivity.this, getProductTestData()); bestRecyclerView.setAdapter(mAdapter); } private List<ProductObject> getProductTestData() { List<ProductObject> featuredProducts = new ArrayList<>(); featuredProducts.add(new ProductObject("Iphone 6", "iphone2")); featuredProducts.add(new ProductObject("Iphone 6S", "iphone2")); featuredProducts.add(new ProductObject("Iphone 8S", "iphone2")); featuredProducts.add(new ProductObject("Iphone X", "iphone2")); featuredProducts.add(new ProductObject("Iphone XR", "iphone2")); featuredProducts.add(new ProductObject("Iphone XS", "iphone2")); return featuredProducts; } } Step 6 − 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 the 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": 1150, "s": 1062, "text": "This example demonstrates how do I use RecyclerView inside NestedScrollView in android." }, { "code": null, "e": 1279, "s": 1150, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1342, "s": 1279, "text": "Add the following dependency in the build.gradle (Module: app)" }, { "code": null, "e": 1616, "s": 1342, "text": "implementation 'com.android.support:appcompat-v7:28.0.0'\nimplementation 'com.android.support:design:28.0.0'\nimplementation 'com.android.support:recyclerview-v7:28.0.0'\nimplementation 'com.android.support:cardview-v7:28.0.0'\nimplementation 'com.intuit.sdp:sdp-android:1.0.3'" }, { "code": null, "e": 1681, "s": 1616, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2941, "s": 1681, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout\nxmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:orientation=\"vertical\"\n tools:context=\".MainActivity\">\n <androidx.core.widget.NestedScrollView\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:scrollbars=\"none\">\n <LinearLayout\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:focusableInTouchMode=\"true\"\n android:orientation=\"vertical\">\n <ImageView\n android:id=\"@+id/sellerProduct\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"200dp\"\n android:adjustViewBounds=\"true\"\n android:src=\"@drawable/iphone\"\n android:scaleType=\"fitXY\"\n android:contentDescription=\"@string/app_name\" />\n <androidx.recyclerview.widget.RecyclerView\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:scrollbars=\"vertical\"\n android:id=\"@+id/productList\"/>\n </LinearLayout>\n </androidx.core.widget.NestedScrollView>\n</LinearLayout>" }, { "code": null, "e": 3025, "s": 2941, "text": "Step 3 − Create a layout resource file (list_item.xml) and add the following code −" }, { "code": null, "e": 4257, "s": 3025, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<androidx.cardview.widget.CardView\nxmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:app=\"http://schemas.android.com/apk/res-auto\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:orientation=\"vertical\"\n app:cardElevation=\"2dp\"\n app:cardUseCompatPadding=\"true\">\n <LinearLayout\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:gravity=\"center\"\n android:orientation=\"vertical\"\n android:padding=\"8dp\">\n <ImageView\n android:id=\"@+id/phoneImage\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:adjustViewBounds=\"true\"\n android:contentDescription=\"TODO\"\n android:src=\"@drawable/iphone2\" />\n <TextView\n android:id=\"@+id/phoneName\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_marginTop=\"10dp\"\n android:text=\"IPHONE\"\n android:textColor=\"@color/colorPrimaryDark\"\n android:textSize=\"12sp\"\n android:textStyle=\"bold\" />\n </LinearLayout>\n</androidx.cardview.widget.CardView>" }, { "code": null, "e": 4340, "s": 4257, "text": "Step 4 − Create java class files as mentioned below and add the respective codes −" }, { "code": null, "e": 4360, "s": 4340, "text": "PhoneAdapter.java −" }, { "code": null, "e": 5920, "s": 4360, "text": "import android.content.Context;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport java.util.List;\nimport androidx.annotation.NonNull;\nimport androidx.recyclerview.widget.RecyclerView;\npublic class PhoneAdapter extends RecyclerView.Adapter<PhoneViewHolder>{\n private Context context;\n private List<ProductObject> productList;\n PhoneAdapter(Context context, List<ProductObject> productList) {\n this.context = context;\n this.productList = productList;\n }\n @NonNull\n @Override\n public PhoneViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {\n View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, parent, false);\n return new PhoneViewHolder(view);\n }\n @Override\n public void onBindViewHolder(PhoneViewHolder holder, int position){\n ProductObject productObject = productList.get(position);\n int imageRes = getResourceId(context, productObject.getImagePath(), context.getPackageName());\n holder.phoneImage.setImageResource(imageRes);\n holder.phoneName.setText(productObject.getName());\n }\n @Override\n public int getItemCount() {\n return productList.size();\n }\n private static int getResourceId(Context context, String pVariableName, String pPackageName) throws RuntimeException {\n try {\n return context.getResources().getIdentifier(pVariableName, \"drawable\", pPackageName);\n } catch (Exception e) {\n throw new RuntimeException(\"Error getting Resource ID.\", e);\n }\n }\n}" }, { "code": null, "e": 5943, "s": 5920, "text": "PhoneViewHolder.java −" }, { "code": null, "e": 6370, "s": 5943, "text": "import android.view.View;\nimport android.widget.ImageView;\nimport android.widget.TextView;\nimport androidx.recyclerview.widget.RecyclerView;\nclass PhoneViewHolder extends RecyclerView.ViewHolder {\n ImageView phoneImage;\n TextView phoneName;\n PhoneViewHolder(View itemView) {\n super(itemView);\n phoneName = itemView.findViewById(R.id.phoneName);\n phoneImage = itemView.findViewById(R.id.phoneImage);\n }\n}" }, { "code": null, "e": 6391, "s": 6370, "text": "ProductObject.java −" }, { "code": null, "e": 6683, "s": 6391, "text": "class ProductObject {\n private String imagePath;\n private String name;\n ProductObject(String name, String imagePath) {\n this.imagePath = imagePath;\n this.name = name;\n }\n String getImagePath() {\n return imagePath;\n }\n String getName() {\n return name;\n }\n}" }, { "code": null, "e": 6740, "s": 6683, "text": "Step 5 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 8129, "s": 6740, "text": "import androidx.appcompat.app.AppCompatActivity;\nimport androidx.recyclerview.widget.GridLayoutManager;\nimport androidx.recyclerview.widget.RecyclerView;\nimport android.os.Bundle;\nimport java.util.ArrayList;\nimport java.util.List;\npublic class MainActivity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n RecyclerView bestRecyclerView = findViewById(R.id.productList);\n GridLayoutManager mGrid = new GridLayoutManager(this, 2);\n bestRecyclerView.setLayoutManager(mGrid);\n bestRecyclerView.setHasFixedSize(true);\n PhoneAdapter mAdapter = new PhoneAdapter(MainActivity.this, getProductTestData());\n bestRecyclerView.setAdapter(mAdapter);\n }\n private List<ProductObject> getProductTestData() {\n List<ProductObject> featuredProducts = new ArrayList<>();\n featuredProducts.add(new ProductObject(\"Iphone 6\", \"iphone2\"));\n featuredProducts.add(new ProductObject(\"Iphone 6S\", \"iphone2\"));\n featuredProducts.add(new ProductObject(\"Iphone 8S\", \"iphone2\"));\n featuredProducts.add(new ProductObject(\"Iphone X\", \"iphone2\"));\n featuredProducts.add(new ProductObject(\"Iphone XR\", \"iphone2\"));\n featuredProducts.add(new ProductObject(\"Iphone XS\", \"iphone2\"));\n return featuredProducts;\n }\n}" }, { "code": null, "e": 8184, "s": 8129, "text": "Step 6 − Add the following code to androidManifest.xml" }, { "code": null, "e": 8854, "s": 8184, "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": 9205, "s": 8854, "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 the 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": 9246, "s": 9205, "text": "Click here to download the project code." } ]
How to count all child elements of a particular element using JavaScript ? - GeeksforGeeks
24 Jan, 2022 Given an HTML document containing some elements nested elements and the task is to count all the child elements of a particular element. It is very simple to count the number of child elements of a particular element using JavaScript. For example: If you have a parent element consisting of many child elements then you can use HTML DOM childElementCount property to count all the child elements of a particular element. Syntax node.childElementCount Example: <!DOCTYPE html><html> <head> <title> How to count all child elements of a particular element using JavaScript? </title></head> <body> <h1 style="color:green">GeeksforGeeks</h1> <h3> Click the button to count all<br> children the div element </h3> <h5>Count all child elements of <ul> elements</h5> <ul id="parentID"> <li>First element</li> <li>Second element</li> <li>Third element</li> <li>Fourth element</li> </ul> <button onclick="myGeeks()"> Click Here! </button> <h5 id="GFG"></h5> <script> // This function count the child elements function myGeeks() { var count = document.getElementById( "parentID").childElementCount; document.getElementById("GFG").innerHTML = "Total Number of Child node: " + count; } </script></body> </html> Output: Before Clicking the Button: After Clicking the Button: Akanksha_Rai simmytarika5 HTML-Misc JavaScript-Misc HTML JavaScript Web Technologies Web technologies Questions Write From Home HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to update Node.js and NPM to next version ? How to Insert Form Data into Database using PHP ? Types of CSS (Cascading Style Sheet) REST API (Introduction) Form validation using HTML and JavaScript Convert a string to an integer in JavaScript How to calculate the number of days between two dates in javascript? Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React File uploading in React.js
[ { "code": null, "e": 24486, "s": 24458, "text": "\n24 Jan, 2022" }, { "code": null, "e": 24907, "s": 24486, "text": "Given an HTML document containing some elements nested elements and the task is to count all the child elements of a particular element. It is very simple to count the number of child elements of a particular element using JavaScript. For example: If you have a parent element consisting of many child elements then you can use HTML DOM childElementCount property to count all the child elements of a particular element." }, { "code": null, "e": 24914, "s": 24907, "text": "Syntax" }, { "code": null, "e": 24937, "s": 24914, "text": "node.childElementCount" }, { "code": null, "e": 24946, "s": 24937, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title> How to count all child elements of a particular element using JavaScript? </title></head> <body> <h1 style=\"color:green\">GeeksforGeeks</h1> <h3> Click the button to count all<br> children the div element </h3> <h5>Count all child elements of <ul> elements</h5> <ul id=\"parentID\"> <li>First element</li> <li>Second element</li> <li>Third element</li> <li>Fourth element</li> </ul> <button onclick=\"myGeeks()\"> Click Here! </button> <h5 id=\"GFG\"></h5> <script> // This function count the child elements function myGeeks() { var count = document.getElementById( \"parentID\").childElementCount; document.getElementById(\"GFG\").innerHTML = \"Total Number of Child node: \" + count; } </script></body> </html>", "e": 25890, "s": 24946, "text": null }, { "code": null, "e": 25898, "s": 25890, "text": "Output:" }, { "code": null, "e": 25926, "s": 25898, "text": "Before Clicking the Button:" }, { "code": null, "e": 25953, "s": 25926, "text": "After Clicking the Button:" }, { "code": null, "e": 25966, "s": 25953, "text": "Akanksha_Rai" }, { "code": null, "e": 25979, "s": 25966, "text": "simmytarika5" }, { "code": null, "e": 25989, "s": 25979, "text": "HTML-Misc" }, { "code": null, "e": 26005, "s": 25989, "text": "JavaScript-Misc" }, { "code": null, "e": 26010, "s": 26005, "text": "HTML" }, { "code": null, "e": 26021, "s": 26010, "text": "JavaScript" }, { "code": null, "e": 26038, "s": 26021, "text": "Web Technologies" }, { "code": null, "e": 26065, "s": 26038, "text": "Web technologies Questions" }, { "code": null, "e": 26081, "s": 26065, "text": "Write From Home" }, { "code": null, "e": 26086, "s": 26081, "text": "HTML" }, { "code": null, "e": 26184, "s": 26086, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26193, "s": 26184, "text": "Comments" }, { "code": null, "e": 26206, "s": 26193, "text": "Old Comments" }, { "code": null, "e": 26254, "s": 26206, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 26304, "s": 26254, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 26341, "s": 26304, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 26365, "s": 26341, "text": "REST API (Introduction)" }, { "code": null, "e": 26407, "s": 26365, "text": "Form validation using HTML and JavaScript" }, { "code": null, "e": 26452, "s": 26407, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 26521, "s": 26452, "text": "How to calculate the number of days between two dates in javascript?" }, { "code": null, "e": 26582, "s": 26521, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 26654, "s": 26582, "text": "Differences between Functional Components and Class Components in React" } ]
How can we assign a function to a variable in JavaScript?
In JavaScript, you can assign a function in a variable using the concept of anonymous functions. Anonymous, as the name suggests, allows creating a function without any names identifier. It can be used as an argument to other functions. They are called using the variable name − This is how JavaScript anonymous functions can be used − var func = function() { alert(‘This is anonymous'); } func(); Anonymous functions are always loaded using a variable name. Anonymous, as the name suggests, allows creating a function without any names identifier. It can be used as an argument to other functions. Call them using a variable name − Here’s an example − //anonymous function var a = function() { return 5; }
[ { "code": null, "e": 1341, "s": 1062, "text": "In JavaScript, you can assign a function in a variable using the concept of anonymous functions. Anonymous, as the name suggests, allows creating a function without any names identifier. It can be used as an argument to other functions. They are called using the variable name −" }, { "code": null, "e": 1398, "s": 1341, "text": "This is how JavaScript anonymous functions can be used −" }, { "code": null, "e": 1463, "s": 1398, "text": "var func = function() {\n alert(‘This is anonymous');\n}\nfunc();" }, { "code": null, "e": 1698, "s": 1463, "text": "Anonymous functions are always loaded using a variable name. Anonymous, as the name suggests, allows creating a function without any names identifier. It can be used as an argument to other functions. Call them using a variable name −" }, { "code": null, "e": 1718, "s": 1698, "text": "Here’s an example −" }, { "code": null, "e": 1775, "s": 1718, "text": "//anonymous function\nvar a = function() {\n return 5;\n}" } ]
Shading an area between two points in a Matplotlib plot
To shade an area between two points in matplotlib, we can take the following steps− Create x and y data points using numpy. Plot x and y data points, with color=red and linewidth=2. To shade an area parallel to X-axis, initialize two variables, y1 and y2. To add horizontal span across the axes, use axhspan() method with y1, y2, green as shade color,and alpha for transprency of the shade. To display the figure, use show() method. import numpy as np import matplotlib.pyplot as plt plt.rcParams["figure.figsize"] = [7.00, 3.50] plt.rcParams["figure.autolayout"] = True x = np.linspace(0, 20, 500) y = np.cos(3*x) + np.sin(2*x) plt.plot(x, y, c='red', lw=2) y1 = 0.5 y2 = -0.5 plt.axhspan(y1, y2, color='green', alpha=0.75, lw=0) plt.show()
[ { "code": null, "e": 1146, "s": 1062, "text": "To shade an area between two points in matplotlib, we can take the following steps−" }, { "code": null, "e": 1186, "s": 1146, "text": "Create x and y data points using numpy." }, { "code": null, "e": 1244, "s": 1186, "text": "Plot x and y data points, with color=red and linewidth=2." }, { "code": null, "e": 1318, "s": 1244, "text": "To shade an area parallel to X-axis, initialize two variables, y1 and y2." }, { "code": null, "e": 1453, "s": 1318, "text": "To add horizontal span across the axes, use axhspan() method with y1, y2, green as shade color,and alpha for transprency of the shade." }, { "code": null, "e": 1495, "s": 1453, "text": "To display the figure, use show() method." }, { "code": null, "e": 1804, "s": 1495, "text": "import numpy as np\nimport matplotlib.pyplot as plt\nplt.rcParams[\"figure.figsize\"] = [7.00, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\nx = np.linspace(0, 20, 500)\ny = np.cos(3*x) + np.sin(2*x)\nplt.plot(x, y, c='red', lw=2)\ny1 = 0.5\ny2 = -0.5\nplt.axhspan(y1, y2, color='green', alpha=0.75, lw=0)\nplt.show()" } ]
Change current working directory with Python - GeeksforGeeks
07 Sep, 2021 The OS module in Python is used for interacting with the operating system. This module comes under Python’s standard utility module so there is no need to install it externally. All functions in OS module raise OSError in the case of invalid or inaccessible file names and paths, or other arguments that have the correct type but are not accepted by the operating system.To change the current working directory(CWD) os.chdir() method is used. This method changes the CWD to a specified path. It only takes a single argument as a new directory path.Note: The current working directory is the folder in which the Python script is operating. Syntax: os.chdir(path)Parameters: path: A complete path of the directory to be changed to the new directory path.Returns: Doesn’t return any value Example #1: We will first get the current working directory of the script and then we will change it. Below is the implementation. Python3 # Python program to change the# current working directory import os # Function to Get the current# working directorydef current_path(): print("Current working directory before") print(os.getcwd()) print() # Driver's code# Printing CWD beforecurrent_path() # Changing the CWDos.chdir('../') # Printing CWD aftercurrent_path() Output: Current working directory before C:\Users\Nikhil Aggarwal\Desktop\gfg Current working directory after C:\Users\Nikhil Aggarwal\Desktop Example #2: Handling the errors while changing the directory. Python3 # Python program to change the# current working directory # importing all necessary librariesimport sys, os # initial directorycwd = os.getcwd() # some non existing directoryfd = 'false_dir/temp' # trying to insert to false directorytry: print("Inserting inside-", os.getcwd()) os.chdir(fd) # Caching the exception except: print("Something wrong with specified directory. Exception- ") print(sys.exc_info()) # handling with finally finally: print() print("Restoring the path") os.chdir(cwd) print("Current directory is-", os.getcwd()) Output: Inserting inside- C:\Users\Nikhil Aggarwal\Desktop\gfgSomething wrong with specified directory. Exception- (<class ‘FileNotFoundError’>, FileNotFoundError(2, ‘The system cannot find the path specified’), <traceback object at 0x00000268184630C8>)Restoring the path Current directory is- C:\Users\Nikhil Aggarwal\Desktop\gfg sumitgumber28 Python directory-program Python os-module-programs python-file-handling python-os-module Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python program to convert a list to string Python String | replace() Reading and Writing to text files in Python sum() function in Python
[ { "code": null, "e": 23895, "s": 23867, "text": "\n07 Sep, 2021" }, { "code": null, "e": 24535, "s": 23895, "text": "The OS module in Python is used for interacting with the operating system. This module comes under Python’s standard utility module so there is no need to install it externally. All functions in OS module raise OSError in the case of invalid or inaccessible file names and paths, or other arguments that have the correct type but are not accepted by the operating system.To change the current working directory(CWD) os.chdir() method is used. This method changes the CWD to a specified path. It only takes a single argument as a new directory path.Note: The current working directory is the folder in which the Python script is operating. " }, { "code": null, "e": 24684, "s": 24535, "text": "Syntax: os.chdir(path)Parameters: path: A complete path of the directory to be changed to the new directory path.Returns: Doesn’t return any value " }, { "code": null, "e": 24817, "s": 24684, "text": "Example #1: We will first get the current working directory of the script and then we will change it. Below is the implementation. " }, { "code": null, "e": 24825, "s": 24817, "text": "Python3" }, { "code": "# Python program to change the# current working directory import os # Function to Get the current# working directorydef current_path(): print(\"Current working directory before\") print(os.getcwd()) print() # Driver's code# Printing CWD beforecurrent_path() # Changing the CWDos.chdir('../') # Printing CWD aftercurrent_path()", "e": 25161, "s": 24825, "text": null }, { "code": null, "e": 25171, "s": 25161, "text": "Output: " }, { "code": null, "e": 25307, "s": 25171, "text": "Current working directory before\nC:\\Users\\Nikhil Aggarwal\\Desktop\\gfg\n\nCurrent working directory after\nC:\\Users\\Nikhil Aggarwal\\Desktop" }, { "code": null, "e": 25371, "s": 25307, "text": "Example #2: Handling the errors while changing the directory. " }, { "code": null, "e": 25379, "s": 25371, "text": "Python3" }, { "code": "# Python program to change the# current working directory # importing all necessary librariesimport sys, os # initial directorycwd = os.getcwd() # some non existing directoryfd = 'false_dir/temp' # trying to insert to false directorytry: print(\"Inserting inside-\", os.getcwd()) os.chdir(fd) # Caching the exception except: print(\"Something wrong with specified directory. Exception- \") print(sys.exc_info()) # handling with finally finally: print() print(\"Restoring the path\") os.chdir(cwd) print(\"Current directory is-\", os.getcwd())", "e": 25975, "s": 25379, "text": null }, { "code": null, "e": 25984, "s": 25975, "text": "Output: " }, { "code": null, "e": 26309, "s": 25984, "text": "Inserting inside- C:\\Users\\Nikhil Aggarwal\\Desktop\\gfgSomething wrong with specified directory. Exception- (<class ‘FileNotFoundError’>, FileNotFoundError(2, ‘The system cannot find the path specified’), <traceback object at 0x00000268184630C8>)Restoring the path Current directory is- C:\\Users\\Nikhil Aggarwal\\Desktop\\gfg " }, { "code": null, "e": 26325, "s": 26311, "text": "sumitgumber28" }, { "code": null, "e": 26350, "s": 26325, "text": "Python directory-program" }, { "code": null, "e": 26376, "s": 26350, "text": "Python os-module-programs" }, { "code": null, "e": 26397, "s": 26376, "text": "python-file-handling" }, { "code": null, "e": 26414, "s": 26397, "text": "python-os-module" }, { "code": null, "e": 26421, "s": 26414, "text": "Python" }, { "code": null, "e": 26519, "s": 26421, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26528, "s": 26519, "text": "Comments" }, { "code": null, "e": 26541, "s": 26528, "text": "Old Comments" }, { "code": null, "e": 26559, "s": 26541, "text": "Python Dictionary" }, { "code": null, "e": 26594, "s": 26559, "text": "Read a file line by line in Python" }, { "code": null, "e": 26616, "s": 26594, "text": "Enumerate() in Python" }, { "code": null, "e": 26648, "s": 26616, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26678, "s": 26648, "text": "Iterate over a list in Python" }, { "code": null, "e": 26720, "s": 26678, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26763, "s": 26720, "text": "Python program to convert a list to string" }, { "code": null, "e": 26789, "s": 26763, "text": "Python String | replace()" }, { "code": null, "e": 26833, "s": 26789, "text": "Reading and Writing to text files in Python" } ]
Spark 3.0 SQL Feature Update| ANSI SQL Compliance, Store Assignment policy, Upgraded query semantics, Function Upgrades | by Prabhakaran Vijayanagulu | Towards Data Science
Spark has added a lot of notable features with Spark SQL. Some will have a huge impact on checks like data quality and data validations. Though there is a lot of upgraded features, I’m listing out a few of those as these would be used in most common cases. For Spark developers, who are at the initial stage of learning SQL commands, query identifier validation might be helpful. They might use keywords as identifiers that are not meant to be used. Even it will work completely fine with spark, This will confuse others who work with the code in the future. Spark will allow certain unusual cases like using some reserved keywords as identifiers. Something like this: select * from table_1 create where create.column_1= 1 This query will run without any issues in spark. create is the most common reserved keyword, used for creating tables with SQL, but it can be used as an identifier in spark without any issues. To overcome this, and involve query validation in runtime, Spark is now compliant with ANSI SQL standard. Validation has been added to the catalyst parser level. To enable ANSI mode query validation, switch property spark.sql.ansi.enabled to true. For the same query shown above, Spark will now throw the exception. Error in SQL statement: ParseException: no viable alternative at input 'create'(line 1, pos 38)== SQL == select * from table_1 create where create.column_1= 1 ----------------------^^^com.databricks.backend.common.rpc.DatabricksExceptions$SQLExecutionException: org.apache.spark.sql.catalyst.parser.ParseException: Following are the keywords standardized in Spark 3.0: To disable the ANSI standard validation, Falsify spark.sql.ansi.enabled. This feature is introduced for stern data quality checks during migration from SQL kind of environment. Below Insert table statement(Ingesting string into an integer column) would execute without any runtime exception in Spark 2.4 and below. This will work fine in Spark 3.0 as well. But by setting up the property “spark.sql.storeAssignmentPolicy” as ‘ANSI’, casting exception is thrown. This definitely improves data quality checks during the migration. from_json method is used in parsing JSON type value within a column. In Spark 3.0, it supports PERMISSIVE/FAIL_FAST mode similar to spark.read.json. So, if the JSON value cannot be parsed or malformed, it will throw an exception as follows: In Spark 3.0, numbers written in scientific notation(for example, 1E11) would be parsed as Double. In Spark version 2.4 and below, they’re parsed as Decimal. To restore the behavior before Spark 3.0, you can set spark.sql.legacy.exponentLiteralAsDecimal.enabled to false. In Spark 2.4, In Spark 3.0, and setting ‘spark.sql.legacy.exponentLiteralAsDecimal.enabled’ as true. In Spark version 2.4 and below, float/double -0.0 is semantically equal to 0.0, but -0.0 and 0.0 are considered as different values when used in aggregate grouping keys, window partition keys, and join keys. It’s a Bug and it is fixed in Spark 3.0. Now, Distinct of (-0.0,0.0) will give (0.0). Sample Dataset With Spark 2.4, you will get as follows, Whereas with Spark 3.0, with no additional property set, consideration will be the same irrespective of negative or positive. In Spark 3.0, Certain keywords are supported for converting a string to date. To Generate a ‘date’ from a string, Following are the keywords. Possible keywords: select date 'x''x' can have following values:> epoch -> 1970-01-01 (minimum date)> today -> the current date in the time zone specified by spark.sql.session.timeZone> yesterday -> the current date - 1> tomorrow -> the current date + 1> now -> the date of running the current query. It has the same notion as today Similarly, We have an option for getting timestamp from string. Possible keywords: select timestamp 'x''x' can have following values> epoch -> 1970-01-01 00:00:00+00 (Unix system time zero)> today -> midnight today> yesterday -> midnight yesterday> tomorrow -> midnight tomorrow> now -> current query start time In 3.0, Some of the SQL functions also have been updated/added, which has benefits in data aggregation and getting insights out of it in a simpler way. Find some of them below. These functions are one of the significant features that I have noted. These will get you the value of a column, with respect to maximum/minimum some other column. Usage: max_by(x,y) / min_by(x,y) → x = column from which value to be fetched. → y = column to get the aggregated maximum/minimum. From the above data, the Overall Maximum Price is 2.598 and the Overall Minimum price is 2.514. But with Max_by/Min_by, Maximum = 2.572, which is for the maximum order number 6 and Minimum = 2.548, which is for the minimum order number 1. CTE using with clause can now be used within subqueries. This will improve query readability and would be significant in using multiple CTE’s.Something like this: select * from (with inner_cte as (select * from sql_functions_test where order_num = 5)select order_num from inner_cte); This feature would be helpful in aggregation only for a set of rows, filtered based on a condition. This is an alternative to ‘replace’ function. But, It does have some advantages over replace. Usage : overlay(input_string placing replace_string from start_position for number_of_positions_to_be_replaced) Note: The input column should be a string. This is to validate a column based on the condition expression provided. Usage: Any(expr) , Every(expr), Some(expr) EVERY: will return true, only if all column values return true. ANY/SOME: will return true, even if one value returns true. This is similar to filter(where..), which will give you the non-distinct count of column records, that satisfy the condition provided. Usage: count_if(expr) This is to validate boolean columns, mimicking AND /OR operation. Usage: bool_and(column_value) , bool_or(column_value) Considering the sample table, having a boolean column. Applying BOOL_AND: returns true only if all the values are true. Applying BOOL_OR: returns true even if one value is true. Spark has not only added new features but fixed a few bugs with the earlier versions. Validation and quality checks have been easier than before. Functions like count with filter, max_by and min_by will reduce the complexity of executing multiple sub-queries.
[ { "code": null, "e": 428, "s": 171, "text": "Spark has added a lot of notable features with Spark SQL. Some will have a huge impact on checks like data quality and data validations. Though there is a lot of upgraded features, I’m listing out a few of those as these would be used in most common cases." }, { "code": null, "e": 730, "s": 428, "text": "For Spark developers, who are at the initial stage of learning SQL commands, query identifier validation might be helpful. They might use keywords as identifiers that are not meant to be used. Even it will work completely fine with spark, This will confuse others who work with the code in the future." }, { "code": null, "e": 840, "s": 730, "text": "Spark will allow certain unusual cases like using some reserved keywords as identifiers. Something like this:" }, { "code": null, "e": 894, "s": 840, "text": "select * from table_1 create where create.column_1= 1" }, { "code": null, "e": 1087, "s": 894, "text": "This query will run without any issues in spark. create is the most common reserved keyword, used for creating tables with SQL, but it can be used as an identifier in spark without any issues." }, { "code": null, "e": 1403, "s": 1087, "text": "To overcome this, and involve query validation in runtime, Spark is now compliant with ANSI SQL standard. Validation has been added to the catalyst parser level. To enable ANSI mode query validation, switch property spark.sql.ansi.enabled to true. For the same query shown above, Spark will now throw the exception." }, { "code": null, "e": 1720, "s": 1403, "text": "Error in SQL statement: ParseException: no viable alternative at input 'create'(line 1, pos 38)== SQL == select * from table_1 create where create.column_1= 1 ----------------------^^^com.databricks.backend.common.rpc.DatabricksExceptions$SQLExecutionException: org.apache.spark.sql.catalyst.parser.ParseException:" }, { "code": null, "e": 1774, "s": 1720, "text": "Following are the keywords standardized in Spark 3.0:" }, { "code": null, "e": 1847, "s": 1774, "text": "To disable the ANSI standard validation, Falsify spark.sql.ansi.enabled." }, { "code": null, "e": 2089, "s": 1847, "text": "This feature is introduced for stern data quality checks during migration from SQL kind of environment. Below Insert table statement(Ingesting string into an integer column) would execute without any runtime exception in Spark 2.4 and below." }, { "code": null, "e": 2236, "s": 2089, "text": "This will work fine in Spark 3.0 as well. But by setting up the property “spark.sql.storeAssignmentPolicy” as ‘ANSI’, casting exception is thrown." }, { "code": null, "e": 2303, "s": 2236, "text": "This definitely improves data quality checks during the migration." }, { "code": null, "e": 2544, "s": 2303, "text": "from_json method is used in parsing JSON type value within a column. In Spark 3.0, it supports PERMISSIVE/FAIL_FAST mode similar to spark.read.json. So, if the JSON value cannot be parsed or malformed, it will throw an exception as follows:" }, { "code": null, "e": 2816, "s": 2544, "text": "In Spark 3.0, numbers written in scientific notation(for example, 1E11) would be parsed as Double. In Spark version 2.4 and below, they’re parsed as Decimal. To restore the behavior before Spark 3.0, you can set spark.sql.legacy.exponentLiteralAsDecimal.enabled to false." }, { "code": null, "e": 2830, "s": 2816, "text": "In Spark 2.4," }, { "code": null, "e": 2917, "s": 2830, "text": "In Spark 3.0, and setting ‘spark.sql.legacy.exponentLiteralAsDecimal.enabled’ as true." }, { "code": null, "e": 3211, "s": 2917, "text": "In Spark version 2.4 and below, float/double -0.0 is semantically equal to 0.0, but -0.0 and 0.0 are considered as different values when used in aggregate grouping keys, window partition keys, and join keys. It’s a Bug and it is fixed in Spark 3.0. Now, Distinct of (-0.0,0.0) will give (0.0)." }, { "code": null, "e": 3226, "s": 3211, "text": "Sample Dataset" }, { "code": null, "e": 3267, "s": 3226, "text": "With Spark 2.4, you will get as follows," }, { "code": null, "e": 3393, "s": 3267, "text": "Whereas with Spark 3.0, with no additional property set, consideration will be the same irrespective of negative or positive." }, { "code": null, "e": 3471, "s": 3393, "text": "In Spark 3.0, Certain keywords are supported for converting a string to date." }, { "code": null, "e": 3535, "s": 3471, "text": "To Generate a ‘date’ from a string, Following are the keywords." }, { "code": null, "e": 3554, "s": 3535, "text": "Possible keywords:" }, { "code": null, "e": 3868, "s": 3554, "text": "select date 'x''x' can have following values:> epoch -> 1970-01-01 (minimum date)> today -> the current date in the time zone specified by spark.sql.session.timeZone> yesterday -> the current date - 1> tomorrow -> the current date + 1> now -> the date of running the current query. It has the same notion as today" }, { "code": null, "e": 3932, "s": 3868, "text": "Similarly, We have an option for getting timestamp from string." }, { "code": null, "e": 3951, "s": 3932, "text": "Possible keywords:" }, { "code": null, "e": 4180, "s": 3951, "text": "select timestamp 'x''x' can have following values> epoch -> 1970-01-01 00:00:00+00 (Unix system time zero)> today -> midnight today> yesterday -> midnight yesterday> tomorrow -> midnight tomorrow> now -> current query start time" }, { "code": null, "e": 4357, "s": 4180, "text": "In 3.0, Some of the SQL functions also have been updated/added, which has benefits in data aggregation and getting insights out of it in a simpler way. Find some of them below." }, { "code": null, "e": 4521, "s": 4357, "text": "These functions are one of the significant features that I have noted. These will get you the value of a column, with respect to maximum/minimum some other column." }, { "code": null, "e": 4554, "s": 4521, "text": "Usage: max_by(x,y) / min_by(x,y)" }, { "code": null, "e": 4599, "s": 4554, "text": "→ x = column from which value to be fetched." }, { "code": null, "e": 4651, "s": 4599, "text": "→ y = column to get the aggregated maximum/minimum." }, { "code": null, "e": 4747, "s": 4651, "text": "From the above data, the Overall Maximum Price is 2.598 and the Overall Minimum price is 2.514." }, { "code": null, "e": 4890, "s": 4747, "text": "But with Max_by/Min_by, Maximum = 2.572, which is for the maximum order number 6 and Minimum = 2.548, which is for the minimum order number 1." }, { "code": null, "e": 5053, "s": 4890, "text": "CTE using with clause can now be used within subqueries. This will improve query readability and would be significant in using multiple CTE’s.Something like this:" }, { "code": null, "e": 5174, "s": 5053, "text": "select * from (with inner_cte as (select * from sql_functions_test where order_num = 5)select order_num from inner_cte);" }, { "code": null, "e": 5274, "s": 5174, "text": "This feature would be helpful in aggregation only for a set of rows, filtered based on a condition." }, { "code": null, "e": 5368, "s": 5274, "text": "This is an alternative to ‘replace’ function. But, It does have some advantages over replace." }, { "code": null, "e": 5480, "s": 5368, "text": "Usage : overlay(input_string placing replace_string from start_position for number_of_positions_to_be_replaced)" }, { "code": null, "e": 5523, "s": 5480, "text": "Note: The input column should be a string." }, { "code": null, "e": 5596, "s": 5523, "text": "This is to validate a column based on the condition expression provided." }, { "code": null, "e": 5639, "s": 5596, "text": "Usage: Any(expr) , Every(expr), Some(expr)" }, { "code": null, "e": 5703, "s": 5639, "text": "EVERY: will return true, only if all column values return true." }, { "code": null, "e": 5763, "s": 5703, "text": "ANY/SOME: will return true, even if one value returns true." }, { "code": null, "e": 5898, "s": 5763, "text": "This is similar to filter(where..), which will give you the non-distinct count of column records, that satisfy the condition provided." }, { "code": null, "e": 5920, "s": 5898, "text": "Usage: count_if(expr)" }, { "code": null, "e": 5986, "s": 5920, "text": "This is to validate boolean columns, mimicking AND /OR operation." }, { "code": null, "e": 6040, "s": 5986, "text": "Usage: bool_and(column_value) , bool_or(column_value)" }, { "code": null, "e": 6095, "s": 6040, "text": "Considering the sample table, having a boolean column." }, { "code": null, "e": 6160, "s": 6095, "text": "Applying BOOL_AND: returns true only if all the values are true." }, { "code": null, "e": 6218, "s": 6160, "text": "Applying BOOL_OR: returns true even if one value is true." } ]
Deriving Patterns of Fraud from the Enron Dataset | by Mahnoor Javed | Towards Data Science
The Enron fraud is a big, messy and totally fascinating story about corporate malfeasance of nearly every imaginable type. In this article, we will use Python to analyze the dataset, and find out patterns and clues through data exploration, as well as build a regression model that could predict the bonus of a person at Enron based on the salaries they receive. But first, we need to know a bit about the biggest corporate fraud in American history! Enron Corporation was an American energy, commodities, and services company based in Houston, Texas. It was founded by Kenneth Lay as a merger between Houston Natural Gas and InterNorth in 1985. Although it started as an energy company, it was involved in so many complex things that people didn’t understand what exactly the company did, and as Bethnay McLean asked “How exactly does Enron make its money?”. Enron was fantastic! Very attractive to investors and the fastest growing company making money at a rate no one has ever seen before. They were the Wall Street darlings, a company that could never lose. It was well-connected politically, was making money at an incredible rate, and seemed to be the leading innovative company and very profitable investment. Fortune named Enron “America’s Most Innovative Company” for six consecutive years. Jeffrey Skilling was hired by Kenneth Lay in 1990 as chairman and chief executive officer of Enron Finance Corp. In 1992, Skilling devised a new accounting technique called the Mark to Market, under which the value of the asset could be adjusted on the balance sheet from its historical cost up to the fair market value, and the difference be captured as the gain or revenue. So under this technique, projected revenue was captured as revenue of today and Enron reaped billions. The company’s share prices went up from $10/share to around $80/share from 1999 – 2000. Enron was also guilty of setting up side companies and moving the debts to the new companies' financial records. Enron was thus portrayed as a very profitable investment when all numbers on the financial statements were illusionary and fake! Enron filed for bankruptcy on December 2, 2001. Arthur Anderson, one of the “Big Five” accounting firms, which audited the financial statements was dissolved as a result of the Enron scandal. The Enron email and financial datasets are big, messy treasure troves of information, which become much more useful once you know your way around them a bit. Enron’s complete data may be downloaded from this link here, and the refined pickle files may be downloaded from the following Github repository along with the complete code used in this article. github.com First of all, we will explore the dataset we have. Enron data is stored as a pickle file, which is a handy way to store and load Python objects directly. The aggregated Enron email + financial dataset is stored in a dictionary, where each key in the dictionary is a person’s name and the value is a dictionary containing all the features of that person. Let us find out the number of people in the dataset. We will first load the pickle file to retrieve the pickled data and store it in the variable enron_data (which is a dictionary). We will use Python’s len() command to calculate the length of the dictionary loaded from the pickle file, and print the value. import pickleenron_data = pickle.load(open("D:\ML Project\Enron Case\enron_data.pkl", "rb"))print("No of People in the Enron Dataset", len(enron_data)) As can be seen from the variable explorer, enron_data is a dictionary with 146 keys. It means there are 146 data points or persons we will be dealing with in our dataset. Moreover, it can be seen that enron_data is a nested dictionary. We have dictionaries within the dictionary and we have a total of 21 features for each person in the Enron dataset. Let us access the features of the nested dictionary. We will first get the first dictionary item of enron_data and then use it to print its features: first_item = list(enron_data.keys())[0]print(enron_data[first_item].keys()) The 21 features are: ‘salary’, ‘to_messages’, ‘deferral_payments’, ‘total_payments’, ‘loan_advances’, ‘bonus’, ‘email_address’, ‘restricted_stock_deferred’, ‘deferred_income’, ‘total_stock_value’, ‘expenses’, ‘from_poi_to_this_person’, ‘exercised_stock_options’, ‘from_messages’, ‘other’, ‘from_this_person_to_poi’, ‘poi’, ‘long_term_incentive’, ‘shared_receipt_with_poi’, ‘restricted_stock’: , ‘director_fees’. Let us explore the ‘poi’ feature. POI stands for “Person of Interest” and includes all the people who are indicted, charged with crime, and people who settled without admitting guilt and testified in exchange for immunity from prosecution in the Enron Scandal. The POI list had been prepared by Katie from Udacity’s course “Intro to Machine Learning”. The files can be found in the GitHub repository. The following is the code to calculate the number of People of Interest in the dictionary. Out of the 146 people in the enron_data dictionary, the number of POI is 18. people = 0poiCount = 0for person in enron_data: people = people + 1 if enron_data[person]['poi'] == 1: poiCount += 1print("No of POI:", poiCount) Out of the 146 people in the enron_data dictionary, the number of POI is 18. poiFile = open("D:\ML Project\Enron Case\poi_names.txt")poiCount2 = 0lines = poiFile.readlines() for line in lines: if line[0] == '(': poiCount2 += 1print("Total POIs:",poiCount2) There are a total of 35 POIs in the text file. Let us dive into the data available for the CEO at Enron: Jeffrey K Skilling. jeffrey_k_skilling = enron_data['SKILLING JEFFREY K']print(jeffrey_k_skilling) On printing we get the following information: Now, let us access the features of the different people in the dictionary. Following is the code to access and print Skilling’s and Lay’s salary, bonus, and total stocks value: print("Skilling's Salary:", enron_data["SKILLING JEFFREY K"]["salary"])print("Skilling's Bonus", enron_data["SKILLING JEFFREY K"]["bonus"])print("Skilling's Total Stocks Value", enron_data["SKILLING JEFFREY K"]["total_stock_value"])print("Lay's Salary:", enron_data["LAY KENNETH L"]["salary"])print("Lay's Bonus", enron_data["LAY KENNETH L"]["bonus"])print("Lay's Total Stocks Value", enron_data["LAY KENNETH L"]["total_stock_value"]) Let us find out how many people at Enron had quantified salary: people = 0have_quantified_salary = 0for person in enron_data: people = people + 1 if enron_data[person]['salary'] != 'NaN': have_quantified_salary += 1print(have_quantified_salary) 95 people from the 146 persons in enron_data have a quantified salary. The rest have NaN values in their salary features. This may pose problems while applying regression so we will remove them. Now let us see the range of the salaries of the Enron employees in our dataset. We will use plt.hist from the Matplotlib library in Python and create a histogram to visualize the salaries. We will also be using featureFormat function which will convert the dictionary list into a numpy array: feature1 = ["salary"]enron_data.pop('TOTAL', 0)salary = featureFormat(enron_data, feature1)counts, bins = np.histogram(salary)plt.hist(bins[:-1], bins, weights=counts) As can be seen, most of the employees had their salaries within the $0.1M — $0.3M range. We have a few outliers here as well. As can be seen, these are the data points for receiving salaries greater than 1 million USD. Let us find out the outliers and who is receiving such salaries: for x in salary: if x>1000000 : print(x) The salaries beyond $1M are the following: Let us see who earned these salaries: for person in enron_data: if enron_data[person]["salary"] == 1072321: print(person) if enron_data[person]["salary"] == 1111258: print(person) if enron_data[person]["salary"] == 1060932: print(person) Let us do the same with the ‘bonus’ features: feature2 = ["bonus"]enron_data.pop('TOTAL', 0)bonus = featureFormat(enron_data, feature2)counts, bins = np.histogram(bonus)plt.hist(bins[:-1], bins, weights=counts)for x in bonus: if x>5000000 : print("Outlier:", x) Hence, Lavorato John J, Lay Kenneth L, Belden Timothy N and Skilling Jeffrey K are the 4 people who earned the highest bonuses during their employment at Enron. What’s interesting is that although Lay and Skilling have been known for their fraud, we get additional 2 persons. Are these POIs as well? Let’s check: if enron_data["LAVORATO JOHN J"]["poi"] == 1: print("John J Lavorato is a Person of Interest (POI)")if enron_data["LAY KENNETH L"]["poi"] == 1: print("Kenneth L Lay is a Person of Interest (POI)")if enron_data["BELDEN TIMOTHY N"]["poi"] == 1: print("Timothy N Belden is a Person of Interest (POI)")if enron_data["SKILLING JEFFREY K"]["poi"] == 1: print("Jeffrey K Skilling is a Person of Interest (POI)") Now let us use some machine learning algorithms that would predict the bonus knowing the salary of the person. For this, we will be using sklearn’s linear regression. But first, let us plot the scatterplot to visualize how the salary and bonus of a person are related. We will use the features “bonus” and “salary” and define them in our own features_list. enron_data.pop('TOTAL', 0)features_list = ["bonus", "salary"]data = featureFormat(enron_data, features_list, remove_any_zeroes=True)target, features = targetFeatureSplit( data ) We will then use the sklearn.model_selection’s train_test_split to split the data into training and testing data. from sklearn.model_selection import train_test_splitfeature_train, feature_test, target_train, target_test = train_test_split(features, target, test_size=0.5, random_state=42)train_color = "b"test_color = "r" Lastly, we will plot the scatterplot using matplotlib: import matplotlib.pyplot as pltfor feature, target in zip(feature_test, target_test): plt.scatter( feature, target, color=test_color ) for feature, target in zip(feature_train, target_train): plt.scatter( feature, target, color=train_color )plt.xlabel(features_list[1])plt.ylabel(features_list[0])plt.scatter(feature_test[0], target_test[0], color=test_color, label="test")plt.scatter(feature_test[0], target_test[0], color=train_color, label="train")plt.legend() As can be seen, the data has been divided equally between testing and training data and are colored in the scatterplot for visualization purposes. Now we will use Linear Regression from sklearn in order to build the regression model for our data: from sklearn.linear_model import LinearRegressionreg = LinearRegression()reg.fit(feature_train, target_train)coef = reg.coef_intercept = reg.intercept_print('Slope: {}, Intercept: {}'.format(coef, intercept))training_score = reg.score(feature_train, target_train)test_score = reg.score(feature_test, target_test)print('Score when same data is used to train and test: {}'.format(training_score))print('Score when separate test data is used: {}'.format(test_score)) And plot the regression line. When we have predicted the regression line, and know the slope as well as the new intercept, we can now predict the bonuses of people at Enron based on the salary they receive. So these were some of the tasks we did with the Enron dataset. The dataset is enormous, and there are hundreds of other cool stuff you could do with it. For the sake of this article, we keep to the basic ones. You may explore further on your own! 😄
[ { "code": null, "e": 295, "s": 172, "text": "The Enron fraud is a big, messy and totally fascinating story about corporate malfeasance of nearly every imaginable type." }, { "code": null, "e": 535, "s": 295, "text": "In this article, we will use Python to analyze the dataset, and find out patterns and clues through data exploration, as well as build a regression model that could predict the bonus of a person at Enron based on the salaries they receive." }, { "code": null, "e": 623, "s": 535, "text": "But first, we need to know a bit about the biggest corporate fraud in American history!" }, { "code": null, "e": 818, "s": 623, "text": "Enron Corporation was an American energy, commodities, and services company based in Houston, Texas. It was founded by Kenneth Lay as a merger between Houston Natural Gas and InterNorth in 1985." }, { "code": null, "e": 1032, "s": 818, "text": "Although it started as an energy company, it was involved in so many complex things that people didn’t understand what exactly the company did, and as Bethnay McLean asked “How exactly does Enron make its money?”." }, { "code": null, "e": 1473, "s": 1032, "text": "Enron was fantastic! Very attractive to investors and the fastest growing company making money at a rate no one has ever seen before. They were the Wall Street darlings, a company that could never lose. It was well-connected politically, was making money at an incredible rate, and seemed to be the leading innovative company and very profitable investment. Fortune named Enron “America’s Most Innovative Company” for six consecutive years." }, { "code": null, "e": 2153, "s": 1473, "text": "Jeffrey Skilling was hired by Kenneth Lay in 1990 as chairman and chief executive officer of Enron Finance Corp. In 1992, Skilling devised a new accounting technique called the Mark to Market, under which the value of the asset could be adjusted on the balance sheet from its historical cost up to the fair market value, and the difference be captured as the gain or revenue. So under this technique, projected revenue was captured as revenue of today and Enron reaped billions. The company’s share prices went up from $10/share to around $80/share from 1999 – 2000. Enron was also guilty of setting up side companies and moving the debts to the new companies' financial records." }, { "code": null, "e": 2282, "s": 2153, "text": "Enron was thus portrayed as a very profitable investment when all numbers on the financial statements were illusionary and fake!" }, { "code": null, "e": 2474, "s": 2282, "text": "Enron filed for bankruptcy on December 2, 2001. Arthur Anderson, one of the “Big Five” accounting firms, which audited the financial statements was dissolved as a result of the Enron scandal." }, { "code": null, "e": 2828, "s": 2474, "text": "The Enron email and financial datasets are big, messy treasure troves of information, which become much more useful once you know your way around them a bit. Enron’s complete data may be downloaded from this link here, and the refined pickle files may be downloaded from the following Github repository along with the complete code used in this article." }, { "code": null, "e": 2839, "s": 2828, "text": "github.com" }, { "code": null, "e": 2993, "s": 2839, "text": "First of all, we will explore the dataset we have. Enron data is stored as a pickle file, which is a handy way to store and load Python objects directly." }, { "code": null, "e": 3193, "s": 2993, "text": "The aggregated Enron email + financial dataset is stored in a dictionary, where each key in the dictionary is a person’s name and the value is a dictionary containing all the features of that person." }, { "code": null, "e": 3502, "s": 3193, "text": "Let us find out the number of people in the dataset. We will first load the pickle file to retrieve the pickled data and store it in the variable enron_data (which is a dictionary). We will use Python’s len() command to calculate the length of the dictionary loaded from the pickle file, and print the value." }, { "code": null, "e": 3654, "s": 3502, "text": "import pickleenron_data = pickle.load(open(\"D:\\ML Project\\Enron Case\\enron_data.pkl\", \"rb\"))print(\"No of People in the Enron Dataset\", len(enron_data))" }, { "code": null, "e": 3825, "s": 3654, "text": "As can be seen from the variable explorer, enron_data is a dictionary with 146 keys. It means there are 146 data points or persons we will be dealing with in our dataset." }, { "code": null, "e": 4006, "s": 3825, "text": "Moreover, it can be seen that enron_data is a nested dictionary. We have dictionaries within the dictionary and we have a total of 21 features for each person in the Enron dataset." }, { "code": null, "e": 4156, "s": 4006, "text": "Let us access the features of the nested dictionary. We will first get the first dictionary item of enron_data and then use it to print its features:" }, { "code": null, "e": 4232, "s": 4156, "text": "first_item = list(enron_data.keys())[0]print(enron_data[first_item].keys())" }, { "code": null, "e": 4253, "s": 4232, "text": "The 21 features are:" }, { "code": null, "e": 4644, "s": 4253, "text": "‘salary’, ‘to_messages’, ‘deferral_payments’, ‘total_payments’, ‘loan_advances’, ‘bonus’, ‘email_address’, ‘restricted_stock_deferred’, ‘deferred_income’, ‘total_stock_value’, ‘expenses’, ‘from_poi_to_this_person’, ‘exercised_stock_options’, ‘from_messages’, ‘other’, ‘from_this_person_to_poi’, ‘poi’, ‘long_term_incentive’, ‘shared_receipt_with_poi’, ‘restricted_stock’: , ‘director_fees’." }, { "code": null, "e": 4905, "s": 4644, "text": "Let us explore the ‘poi’ feature. POI stands for “Person of Interest” and includes all the people who are indicted, charged with crime, and people who settled without admitting guilt and testified in exchange for immunity from prosecution in the Enron Scandal." }, { "code": null, "e": 5045, "s": 4905, "text": "The POI list had been prepared by Katie from Udacity’s course “Intro to Machine Learning”. The files can be found in the GitHub repository." }, { "code": null, "e": 5213, "s": 5045, "text": "The following is the code to calculate the number of People of Interest in the dictionary. Out of the 146 people in the enron_data dictionary, the number of POI is 18." }, { "code": null, "e": 5372, "s": 5213, "text": "people = 0poiCount = 0for person in enron_data: people = people + 1 if enron_data[person]['poi'] == 1: poiCount += 1print(\"No of POI:\", poiCount)" }, { "code": null, "e": 5449, "s": 5372, "text": "Out of the 146 people in the enron_data dictionary, the number of POI is 18." }, { "code": null, "e": 5639, "s": 5449, "text": "poiFile = open(\"D:\\ML Project\\Enron Case\\poi_names.txt\")poiCount2 = 0lines = poiFile.readlines() for line in lines: if line[0] == '(': poiCount2 += 1print(\"Total POIs:\",poiCount2)" }, { "code": null, "e": 5686, "s": 5639, "text": "There are a total of 35 POIs in the text file." }, { "code": null, "e": 5764, "s": 5686, "text": "Let us dive into the data available for the CEO at Enron: Jeffrey K Skilling." }, { "code": null, "e": 5843, "s": 5764, "text": "jeffrey_k_skilling = enron_data['SKILLING JEFFREY K']print(jeffrey_k_skilling)" }, { "code": null, "e": 5889, "s": 5843, "text": "On printing we get the following information:" }, { "code": null, "e": 6066, "s": 5889, "text": "Now, let us access the features of the different people in the dictionary. Following is the code to access and print Skilling’s and Lay’s salary, bonus, and total stocks value:" }, { "code": null, "e": 6501, "s": 6066, "text": "print(\"Skilling's Salary:\", enron_data[\"SKILLING JEFFREY K\"][\"salary\"])print(\"Skilling's Bonus\", enron_data[\"SKILLING JEFFREY K\"][\"bonus\"])print(\"Skilling's Total Stocks Value\", enron_data[\"SKILLING JEFFREY K\"][\"total_stock_value\"])print(\"Lay's Salary:\", enron_data[\"LAY KENNETH L\"][\"salary\"])print(\"Lay's Bonus\", enron_data[\"LAY KENNETH L\"][\"bonus\"])print(\"Lay's Total Stocks Value\", enron_data[\"LAY KENNETH L\"][\"total_stock_value\"])" }, { "code": null, "e": 6565, "s": 6501, "text": "Let us find out how many people at Enron had quantified salary:" }, { "code": null, "e": 6763, "s": 6565, "text": "people = 0have_quantified_salary = 0for person in enron_data: people = people + 1 if enron_data[person]['salary'] != 'NaN': have_quantified_salary += 1print(have_quantified_salary)" }, { "code": null, "e": 6958, "s": 6763, "text": "95 people from the 146 persons in enron_data have a quantified salary. The rest have NaN values in their salary features. This may pose problems while applying regression so we will remove them." }, { "code": null, "e": 7251, "s": 6958, "text": "Now let us see the range of the salaries of the Enron employees in our dataset. We will use plt.hist from the Matplotlib library in Python and create a histogram to visualize the salaries. We will also be using featureFormat function which will convert the dictionary list into a numpy array:" }, { "code": null, "e": 7419, "s": 7251, "text": "feature1 = [\"salary\"]enron_data.pop('TOTAL', 0)salary = featureFormat(enron_data, feature1)counts, bins = np.histogram(salary)plt.hist(bins[:-1], bins, weights=counts)" }, { "code": null, "e": 7638, "s": 7419, "text": "As can be seen, most of the employees had their salaries within the $0.1M — $0.3M range. We have a few outliers here as well. As can be seen, these are the data points for receiving salaries greater than 1 million USD." }, { "code": null, "e": 7703, "s": 7638, "text": "Let us find out the outliers and who is receiving such salaries:" }, { "code": null, "e": 7754, "s": 7703, "text": "for x in salary: if x>1000000 : print(x)" }, { "code": null, "e": 7797, "s": 7754, "text": "The salaries beyond $1M are the following:" }, { "code": null, "e": 7835, "s": 7797, "text": "Let us see who earned these salaries:" }, { "code": null, "e": 8065, "s": 7835, "text": "for person in enron_data: if enron_data[person][\"salary\"] == 1072321: print(person) if enron_data[person][\"salary\"] == 1111258: print(person) if enron_data[person][\"salary\"] == 1060932: print(person)" }, { "code": null, "e": 8111, "s": 8065, "text": "Let us do the same with the ‘bonus’ features:" }, { "code": null, "e": 8337, "s": 8111, "text": "feature2 = [\"bonus\"]enron_data.pop('TOTAL', 0)bonus = featureFormat(enron_data, feature2)counts, bins = np.histogram(bonus)plt.hist(bins[:-1], bins, weights=counts)for x in bonus: if x>5000000 : print(\"Outlier:\", x)" }, { "code": null, "e": 8650, "s": 8337, "text": "Hence, Lavorato John J, Lay Kenneth L, Belden Timothy N and Skilling Jeffrey K are the 4 people who earned the highest bonuses during their employment at Enron. What’s interesting is that although Lay and Skilling have been known for their fraud, we get additional 2 persons. Are these POIs as well? Let’s check:" }, { "code": null, "e": 9067, "s": 8650, "text": "if enron_data[\"LAVORATO JOHN J\"][\"poi\"] == 1: print(\"John J Lavorato is a Person of Interest (POI)\")if enron_data[\"LAY KENNETH L\"][\"poi\"] == 1: print(\"Kenneth L Lay is a Person of Interest (POI)\")if enron_data[\"BELDEN TIMOTHY N\"][\"poi\"] == 1: print(\"Timothy N Belden is a Person of Interest (POI)\")if enron_data[\"SKILLING JEFFREY K\"][\"poi\"] == 1: print(\"Jeffrey K Skilling is a Person of Interest (POI)\")" }, { "code": null, "e": 9178, "s": 9067, "text": "Now let us use some machine learning algorithms that would predict the bonus knowing the salary of the person." }, { "code": null, "e": 9234, "s": 9178, "text": "For this, we will be using sklearn’s linear regression." }, { "code": null, "e": 9424, "s": 9234, "text": "But first, let us plot the scatterplot to visualize how the salary and bonus of a person are related. We will use the features “bonus” and “salary” and define them in our own features_list." }, { "code": null, "e": 9602, "s": 9424, "text": "enron_data.pop('TOTAL', 0)features_list = [\"bonus\", \"salary\"]data = featureFormat(enron_data, features_list, remove_any_zeroes=True)target, features = targetFeatureSplit( data )" }, { "code": null, "e": 9716, "s": 9602, "text": "We will then use the sklearn.model_selection’s train_test_split to split the data into training and testing data." }, { "code": null, "e": 9925, "s": 9716, "text": "from sklearn.model_selection import train_test_splitfeature_train, feature_test, target_train, target_test = train_test_split(features, target, test_size=0.5, random_state=42)train_color = \"b\"test_color = \"r\"" }, { "code": null, "e": 9980, "s": 9925, "text": "Lastly, we will plot the scatterplot using matplotlib:" }, { "code": null, "e": 10450, "s": 9980, "text": "import matplotlib.pyplot as pltfor feature, target in zip(feature_test, target_test): plt.scatter( feature, target, color=test_color ) for feature, target in zip(feature_train, target_train): plt.scatter( feature, target, color=train_color )plt.xlabel(features_list[1])plt.ylabel(features_list[0])plt.scatter(feature_test[0], target_test[0], color=test_color, label=\"test\")plt.scatter(feature_test[0], target_test[0], color=train_color, label=\"train\")plt.legend()" }, { "code": null, "e": 10597, "s": 10450, "text": "As can be seen, the data has been divided equally between testing and training data and are colored in the scatterplot for visualization purposes." }, { "code": null, "e": 10697, "s": 10597, "text": "Now we will use Linear Regression from sklearn in order to build the regression model for our data:" }, { "code": null, "e": 11161, "s": 10697, "text": "from sklearn.linear_model import LinearRegressionreg = LinearRegression()reg.fit(feature_train, target_train)coef = reg.coef_intercept = reg.intercept_print('Slope: {}, Intercept: {}'.format(coef, intercept))training_score = reg.score(feature_train, target_train)test_score = reg.score(feature_test, target_test)print('Score when same data is used to train and test: {}'.format(training_score))print('Score when separate test data is used: {}'.format(test_score))" }, { "code": null, "e": 11191, "s": 11161, "text": "And plot the regression line." }, { "code": null, "e": 11368, "s": 11191, "text": "When we have predicted the regression line, and know the slope as well as the new intercept, we can now predict the bonuses of people at Enron based on the salary they receive." } ]
Sum of all the Boundary Nodes of a Binary Tree - GeeksforGeeks
28 Jun, 2021 Given a binary tree, the task is to print the sum of all the boundary nodes of the tree. Examples: Input: 1 / \ 2 3 / \ / \ 4 5 6 7 Output: 28 Input: 1 / \ 2 3 \ / 4 5 \ 6 / \ 7 8 Output: 36 Approach: We have already discussed the Boundary Traversal of a Binary tree. Here we will find the sum of the boundary nodes of the given binary tree in four steps: Sum up all the nodes of the left boundary, Sum up all the leaf nodes of the left sub-tree, Sum up all the leaf nodes of the right sub-tree and Sum up all the nodes of the right boundary. We will have to take care of one thing that nodes don’t add up again, i.e. the left most node is also the leaf node of the tree. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // A binary tree node has data,// pointer to left child// and a pointer to right childstruct Node { int data; struct Node* left; struct Node* right;}; // Utility function to create a nodeNode* newNode(int data){ Node* temp = new Node; temp->left = NULL; temp->right = NULL; temp->data = data; return temp;} // Function to sum up all the left boundary nodes// except the leaf nodesvoid LeftBoundary(Node* root, int& sum_of_boundary_nodes){ if (root) { if (root->left) { sum_of_boundary_nodes += root->data; LeftBoundary(root->left, sum_of_boundary_nodes); } else if (root->right) { sum_of_boundary_nodes += root->data; LeftBoundary(root->right, sum_of_boundary_nodes); } }} // Function to sum up all the right boundary nodes// except the leaf nodesvoid RightBoundary(Node* root, int& sum_of_boundary_nodes){ if (root) { if (root->right) { RightBoundary(root->right, sum_of_boundary_nodes); sum_of_boundary_nodes += root->data; } else if (root->left) { RightBoundary(root->left, sum_of_boundary_nodes); sum_of_boundary_nodes += root->data; } }} // Function to sum up all the leaf nodes// of a binary treevoid Leaves(Node* root, int& sum_of_boundary_nodes){ if (root) { Leaves(root->left, sum_of_boundary_nodes); // Sum it up if it is a leaf node if (!(root->left) && !(root->right)) sum_of_boundary_nodes += root->data; Leaves(root->right, sum_of_boundary_nodes); }} // Function to return the sum of all the// boundary nodes of the given binary treeint sumOfBoundaryNodes(struct Node* root){ if (root) { // Root node is also a boundary node int sum_of_boundary_nodes = root->data; // Sum up all the left nodes // in TOP DOWN manner LeftBoundary(root->left, sum_of_boundary_nodes); // Sum up all the // leaf nodes Leaves(root->left, sum_of_boundary_nodes); Leaves(root->right, sum_of_boundary_nodes); // Sum up all the right nodes // in BOTTOM UP manner RightBoundary(root->right, sum_of_boundary_nodes); // Return the sum of // all the boundary nodes return sum_of_boundary_nodes; } return 0;} // Driver codeint main(){ Node* root = newNode(10); root->left = newNode(2); root->right = newNode(5); root->left->left = newNode(8); root->left->right = newNode(14); root->right->left = newNode(11); root->right->right = newNode(3); root->left->right->left = newNode(12); root->right->left->right = newNode(1); root->right->left->left = newNode(7); cout << sumOfBoundaryNodes(root); return 0;} // Java implementation of the approachclass GFG{ static int sum_of_boundary_nodes=0; // A binary tree node has data,// pointer to left childstatic class Node{ int data; Node left; Node right;}; // Utility function to create a nodestatic Node newNode(int data){ Node temp = new Node(); temp.left = null; temp.right = null; temp.data = data; return temp;} // Function to sum up all the left boundary nodes// except the leaf nodesstatic void LeftBoundary(Node root){ if (root != null) { if (root.left != null) { sum_of_boundary_nodes += root.data; LeftBoundary(root.left); } else if (root.right != null) { sum_of_boundary_nodes += root.data; LeftBoundary(root.right); } }} // Function to sum up all the right boundary nodes// except the leaf nodesstatic void RightBoundary(Node root){ if (root != null) { if (root.right != null) { RightBoundary(root.right); sum_of_boundary_nodes += root.data; } else if (root.left != null) { RightBoundary(root.left); sum_of_boundary_nodes += root.data; } }} // Function to sum up all the leaf nodes// of a binary treestatic void Leaves(Node root){ if (root != null) { Leaves(root.left); // Sum it up if it is a leaf node if ((root.left == null) && (root.right == null)) sum_of_boundary_nodes += root.data; Leaves(root.right); }} // Function to return the sum of all the// boundary nodes of the given binary treestatic int sumOfBoundaryNodes( Node root){ if (root != null) { // Root node is also a boundary node sum_of_boundary_nodes = root.data; // Sum up all the left nodes // in TOP DOWN manner LeftBoundary(root.left); // Sum up all the // leaf nodes Leaves(root.left); Leaves(root.right); // Sum up all the right nodes // in BOTTOM UP manner RightBoundary(root.right); // Return the sum of // all the boundary nodes return sum_of_boundary_nodes; } return 0;} // Driver codepublic static void main(String args[]){ Node root = newNode(10); root.left = newNode(2); root.right = newNode(5); root.left.left = newNode(8); root.left.right = newNode(14); root.right.left = newNode(11); root.right.right = newNode(3); root.left.right.left = newNode(12); root.right.left.right = newNode(1); root.right.left.left = newNode(7); System.out.println(sumOfBoundaryNodes(root));}} // This code is contributed by andrew1234 # Python3 implementation of the approach # A binary tree node has data,# pointer to left child# and a pointer to right childclass Node: def __init__(self): self.left = None self.right = None sum_of_boundary_nodes = 0 # Utility function to create a nodedef newNode(data): temp = Node() temp.data = data; return temp; # Function to sum up all the# left boundary nodes except# the leaf nodesdef LeftBoundary(root): global sum_of_boundary_nodes if (root != None): if (root.left != None): sum_of_boundary_nodes += root.data; LeftBoundary(root.left); elif (root.right != None): sum_of_boundary_nodes += root.data; LeftBoundary(root.right); # Function to sum up all the right# boundary nodes except the leaf nodesdef RightBoundary(root): global sum_of_boundary_nodes if (root != None): if (root.right != None): RightBoundary(root.right); sum_of_boundary_nodes += root.data; elif (root.left != None): RightBoundary(root.left); sum_of_boundary_nodes += root.data; # Function to sum up all the leaf nodes# of a binary treedef Leaves(root): global sum_of_boundary_nodes if (root != None): Leaves(root.left); # Sum it up if it is a leaf node if ((root.left == None) and (root.right == None)): sum_of_boundary_nodes += root.data; Leaves(root.right); # Function to return the sum of all the# boundary nodes of the given binary treedef sumOfBoundaryNodes(root): global sum_of_boundary_nodes if (root != None): # Root node is also a boundary node sum_of_boundary_nodes = root.data; # Sum up all the left nodes # in TOP DOWN manner LeftBoundary(root.left); # Sum up all the # leaf nodes Leaves(root.left); Leaves(root.right); # Sum up all the right nodes # in BOTTOM UP manner RightBoundary(root.right); # Return the sum of # all the boundary nodes return sum_of_boundary_nodes; return 0; # Driver codeif __name__=="__main__": root = newNode(10); root.left = newNode(2); root.right = newNode(5); root.left.left = newNode(8); root.left.right = newNode(14); root.right.left = newNode(11); root.right.right = newNode(3); root.left.right.left = newNode(12); root.right.left.right = newNode(1); root.right.left.left = newNode(7); print(sumOfBoundaryNodes(root)); # This code is contributed by rutvik_56 // C# implementation of the approachusing System;class GFG{static int sum_of_boundary_nodes = 0; // A binary tree node has data,// pointer to left childpublic class Node{ public int data; public Node left; public Node right;}; // Utility function to create a nodestatic Node newNode(int data){ Node temp = new Node(); temp.left = null; temp.right = null; temp.data = data; return temp;} // Function to sum up all the left boundary// nodes except the leaf nodesstatic void LeftBoundary(Node root){ if (root != null) { if (root.left != null) { sum_of_boundary_nodes += root.data; LeftBoundary(root.left); } else if (root.right != null) { sum_of_boundary_nodes += root.data; LeftBoundary(root.right); } }} // Function to sum up all the right boundary// nodes except the leaf nodesstatic void RightBoundary(Node root){ if (root != null) { if (root.right != null) { RightBoundary(root.right); sum_of_boundary_nodes += root.data; } else if (root.left != null) { RightBoundary(root.left); sum_of_boundary_nodes += root.data; } }} // Function to sum up all the leaf nodes// of a binary treestatic void Leaves(Node root){ if (root != null) { Leaves(root.left); // Sum it up if it is a leaf node if ((root.left == null) && (root.right == null)) sum_of_boundary_nodes += root.data; Leaves(root.right); }} // Function to return the sum of all the// boundary nodes of the given binary treestatic int sumOfBoundaryNodes(Node root){ if (root != null) { // Root node is also a boundary node sum_of_boundary_nodes = root.data; // Sum up all the left nodes // in TOP DOWN manner LeftBoundary(root.left); // Sum up all the // leaf nodes Leaves(root.left); Leaves(root.right); // Sum up all the right nodes // in BOTTOM UP manner RightBoundary(root.right); // Return the sum of // all the boundary nodes return sum_of_boundary_nodes; } return 0;} // Driver codepublic static void Main(String []args){ Node root = newNode(10); root.left = newNode(2); root.right = newNode(5); root.left.left = newNode(8); root.left.right = newNode(14); root.right.left = newNode(11); root.right.right = newNode(3); root.left.right.left = newNode(12); root.right.left.right = newNode(1); root.right.left.left = newNode(7); Console.WriteLine(sumOfBoundaryNodes(root));}} // This code is contributed by Princi Singh <script> // JavaScript implementation of the approach let sum_of_boundary_nodes=0; // Binary Tree Node class Node { constructor(data) { this.left = null; this.right = null; this.data = data; } } // Utility function to create a node function newNode(data) { let temp = new Node(data); return temp; } // Function to sum up all the left boundary nodes // except the leaf nodes function LeftBoundary(root) { if (root != null) { if (root.left != null) { sum_of_boundary_nodes += root.data; LeftBoundary(root.left); } else if (root.right != null) { sum_of_boundary_nodes += root.data; LeftBoundary(root.right); } } } // Function to sum up all the right boundary nodes // except the leaf nodes function RightBoundary(root) { if (root != null) { if (root.right != null) { RightBoundary(root.right); sum_of_boundary_nodes += root.data; } else if (root.left != null) { RightBoundary(root.left); sum_of_boundary_nodes += root.data; } } } // Function to sum up all the leaf nodes // of a binary tree function Leaves(root) { if (root != null) { Leaves(root.left); // Sum it up if it is a leaf node if ((root.left == null) && (root.right == null)) sum_of_boundary_nodes += root.data; Leaves(root.right); } } // Function to return the sum of all the // boundary nodes of the given binary tree function sumOfBoundaryNodes(root) { if (root != null) { // Root node is also a boundary node sum_of_boundary_nodes = root.data; // Sum up all the left nodes // in TOP DOWN manner LeftBoundary(root.left); // Sum up all the // leaf nodes Leaves(root.left); Leaves(root.right); // Sum up all the right nodes // in BOTTOM UP manner RightBoundary(root.right); // Return the sum of // all the boundary nodes return sum_of_boundary_nodes; } return 0; } let root = newNode(10); root.left = newNode(2); root.right = newNode(5); root.left.left = newNode(8); root.left.right = newNode(14); root.right.left = newNode(11); root.right.right = newNode(3); root.left.right.left = newNode(12); root.right.left.right = newNode(1); root.right.left.left = newNode(7); document.write(sumOfBoundaryNodes(root)); </script> 48 Time Complexity: O(N) where N is the number of nodes in the binary tree. andrew1234 princi singh rutvik_56 mukesh07 Binary Tree tree-traversal Data Structures Tree Data Structures Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Introduction to Tree Data Structure TCS NQT Coding Sheet Program to implement Singly Linked List in C++ using class Hash Functions and list/types of Hash functions Finding in and out degrees of all vertices in a graph Tree Traversals (Inorder, Preorder and Postorder) Binary Tree | Set 1 (Introduction) Level Order Binary Tree Traversal AVL Tree | Set 1 (Insertion) Inorder Tree Traversal without Recursion
[ { "code": null, "e": 24974, "s": 24946, "text": "\n28 Jun, 2021" }, { "code": null, "e": 25064, "s": 24974, "text": "Given a binary tree, the task is to print the sum of all the boundary nodes of the tree. " }, { "code": null, "e": 25075, "s": 25064, "text": "Examples: " }, { "code": null, "e": 25397, "s": 25075, "text": "Input:\n 1\n / \\\n 2 3\n / \\ / \\\n 4 5 6 7\nOutput: 28\n\nInput:\n 1\n / \\\n 2 3\n \\ /\n 4 5\n \\\n 6\n / \\\n 7 8\nOutput: 36" }, { "code": null, "e": 25563, "s": 25397, "text": "Approach: We have already discussed the Boundary Traversal of a Binary tree. Here we will find the sum of the boundary nodes of the given binary tree in four steps: " }, { "code": null, "e": 25606, "s": 25563, "text": "Sum up all the nodes of the left boundary," }, { "code": null, "e": 25654, "s": 25606, "text": "Sum up all the leaf nodes of the left sub-tree," }, { "code": null, "e": 25706, "s": 25654, "text": "Sum up all the leaf nodes of the right sub-tree and" }, { "code": null, "e": 25750, "s": 25706, "text": "Sum up all the nodes of the right boundary." }, { "code": null, "e": 25879, "s": 25750, "text": "We will have to take care of one thing that nodes don’t add up again, i.e. the left most node is also the leaf node of the tree." }, { "code": null, "e": 25931, "s": 25879, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 25935, "s": 25931, "text": "C++" }, { "code": null, "e": 25940, "s": 25935, "text": "Java" }, { "code": null, "e": 25948, "s": 25940, "text": "Python3" }, { "code": null, "e": 25951, "s": 25948, "text": "C#" }, { "code": null, "e": 25962, "s": 25951, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // A binary tree node has data,// pointer to left child// and a pointer to right childstruct Node { int data; struct Node* left; struct Node* right;}; // Utility function to create a nodeNode* newNode(int data){ Node* temp = new Node; temp->left = NULL; temp->right = NULL; temp->data = data; return temp;} // Function to sum up all the left boundary nodes// except the leaf nodesvoid LeftBoundary(Node* root, int& sum_of_boundary_nodes){ if (root) { if (root->left) { sum_of_boundary_nodes += root->data; LeftBoundary(root->left, sum_of_boundary_nodes); } else if (root->right) { sum_of_boundary_nodes += root->data; LeftBoundary(root->right, sum_of_boundary_nodes); } }} // Function to sum up all the right boundary nodes// except the leaf nodesvoid RightBoundary(Node* root, int& sum_of_boundary_nodes){ if (root) { if (root->right) { RightBoundary(root->right, sum_of_boundary_nodes); sum_of_boundary_nodes += root->data; } else if (root->left) { RightBoundary(root->left, sum_of_boundary_nodes); sum_of_boundary_nodes += root->data; } }} // Function to sum up all the leaf nodes// of a binary treevoid Leaves(Node* root, int& sum_of_boundary_nodes){ if (root) { Leaves(root->left, sum_of_boundary_nodes); // Sum it up if it is a leaf node if (!(root->left) && !(root->right)) sum_of_boundary_nodes += root->data; Leaves(root->right, sum_of_boundary_nodes); }} // Function to return the sum of all the// boundary nodes of the given binary treeint sumOfBoundaryNodes(struct Node* root){ if (root) { // Root node is also a boundary node int sum_of_boundary_nodes = root->data; // Sum up all the left nodes // in TOP DOWN manner LeftBoundary(root->left, sum_of_boundary_nodes); // Sum up all the // leaf nodes Leaves(root->left, sum_of_boundary_nodes); Leaves(root->right, sum_of_boundary_nodes); // Sum up all the right nodes // in BOTTOM UP manner RightBoundary(root->right, sum_of_boundary_nodes); // Return the sum of // all the boundary nodes return sum_of_boundary_nodes; } return 0;} // Driver codeint main(){ Node* root = newNode(10); root->left = newNode(2); root->right = newNode(5); root->left->left = newNode(8); root->left->right = newNode(14); root->right->left = newNode(11); root->right->right = newNode(3); root->left->right->left = newNode(12); root->right->left->right = newNode(1); root->right->left->left = newNode(7); cout << sumOfBoundaryNodes(root); return 0;}", "e": 28817, "s": 25962, "text": null }, { "code": "// Java implementation of the approachclass GFG{ static int sum_of_boundary_nodes=0; // A binary tree node has data,// pointer to left childstatic class Node{ int data; Node left; Node right;}; // Utility function to create a nodestatic Node newNode(int data){ Node temp = new Node(); temp.left = null; temp.right = null; temp.data = data; return temp;} // Function to sum up all the left boundary nodes// except the leaf nodesstatic void LeftBoundary(Node root){ if (root != null) { if (root.left != null) { sum_of_boundary_nodes += root.data; LeftBoundary(root.left); } else if (root.right != null) { sum_of_boundary_nodes += root.data; LeftBoundary(root.right); } }} // Function to sum up all the right boundary nodes// except the leaf nodesstatic void RightBoundary(Node root){ if (root != null) { if (root.right != null) { RightBoundary(root.right); sum_of_boundary_nodes += root.data; } else if (root.left != null) { RightBoundary(root.left); sum_of_boundary_nodes += root.data; } }} // Function to sum up all the leaf nodes// of a binary treestatic void Leaves(Node root){ if (root != null) { Leaves(root.left); // Sum it up if it is a leaf node if ((root.left == null) && (root.right == null)) sum_of_boundary_nodes += root.data; Leaves(root.right); }} // Function to return the sum of all the// boundary nodes of the given binary treestatic int sumOfBoundaryNodes( Node root){ if (root != null) { // Root node is also a boundary node sum_of_boundary_nodes = root.data; // Sum up all the left nodes // in TOP DOWN manner LeftBoundary(root.left); // Sum up all the // leaf nodes Leaves(root.left); Leaves(root.right); // Sum up all the right nodes // in BOTTOM UP manner RightBoundary(root.right); // Return the sum of // all the boundary nodes return sum_of_boundary_nodes; } return 0;} // Driver codepublic static void main(String args[]){ Node root = newNode(10); root.left = newNode(2); root.right = newNode(5); root.left.left = newNode(8); root.left.right = newNode(14); root.right.left = newNode(11); root.right.right = newNode(3); root.left.right.left = newNode(12); root.right.left.right = newNode(1); root.right.left.left = newNode(7); System.out.println(sumOfBoundaryNodes(root));}} // This code is contributed by andrew1234", "e": 31485, "s": 28817, "text": null }, { "code": "# Python3 implementation of the approach # A binary tree node has data,# pointer to left child# and a pointer to right childclass Node: def __init__(self): self.left = None self.right = None sum_of_boundary_nodes = 0 # Utility function to create a nodedef newNode(data): temp = Node() temp.data = data; return temp; # Function to sum up all the# left boundary nodes except# the leaf nodesdef LeftBoundary(root): global sum_of_boundary_nodes if (root != None): if (root.left != None): sum_of_boundary_nodes += root.data; LeftBoundary(root.left); elif (root.right != None): sum_of_boundary_nodes += root.data; LeftBoundary(root.right); # Function to sum up all the right# boundary nodes except the leaf nodesdef RightBoundary(root): global sum_of_boundary_nodes if (root != None): if (root.right != None): RightBoundary(root.right); sum_of_boundary_nodes += root.data; elif (root.left != None): RightBoundary(root.left); sum_of_boundary_nodes += root.data; # Function to sum up all the leaf nodes# of a binary treedef Leaves(root): global sum_of_boundary_nodes if (root != None): Leaves(root.left); # Sum it up if it is a leaf node if ((root.left == None) and (root.right == None)): sum_of_boundary_nodes += root.data; Leaves(root.right); # Function to return the sum of all the# boundary nodes of the given binary treedef sumOfBoundaryNodes(root): global sum_of_boundary_nodes if (root != None): # Root node is also a boundary node sum_of_boundary_nodes = root.data; # Sum up all the left nodes # in TOP DOWN manner LeftBoundary(root.left); # Sum up all the # leaf nodes Leaves(root.left); Leaves(root.right); # Sum up all the right nodes # in BOTTOM UP manner RightBoundary(root.right); # Return the sum of # all the boundary nodes return sum_of_boundary_nodes; return 0; # Driver codeif __name__==\"__main__\": root = newNode(10); root.left = newNode(2); root.right = newNode(5); root.left.left = newNode(8); root.left.right = newNode(14); root.right.left = newNode(11); root.right.right = newNode(3); root.left.right.left = newNode(12); root.right.left.right = newNode(1); root.right.left.left = newNode(7); print(sumOfBoundaryNodes(root)); # This code is contributed by rutvik_56", "e": 34149, "s": 31485, "text": null }, { "code": "// C# implementation of the approachusing System;class GFG{static int sum_of_boundary_nodes = 0; // A binary tree node has data,// pointer to left childpublic class Node{ public int data; public Node left; public Node right;}; // Utility function to create a nodestatic Node newNode(int data){ Node temp = new Node(); temp.left = null; temp.right = null; temp.data = data; return temp;} // Function to sum up all the left boundary// nodes except the leaf nodesstatic void LeftBoundary(Node root){ if (root != null) { if (root.left != null) { sum_of_boundary_nodes += root.data; LeftBoundary(root.left); } else if (root.right != null) { sum_of_boundary_nodes += root.data; LeftBoundary(root.right); } }} // Function to sum up all the right boundary// nodes except the leaf nodesstatic void RightBoundary(Node root){ if (root != null) { if (root.right != null) { RightBoundary(root.right); sum_of_boundary_nodes += root.data; } else if (root.left != null) { RightBoundary(root.left); sum_of_boundary_nodes += root.data; } }} // Function to sum up all the leaf nodes// of a binary treestatic void Leaves(Node root){ if (root != null) { Leaves(root.left); // Sum it up if it is a leaf node if ((root.left == null) && (root.right == null)) sum_of_boundary_nodes += root.data; Leaves(root.right); }} // Function to return the sum of all the// boundary nodes of the given binary treestatic int sumOfBoundaryNodes(Node root){ if (root != null) { // Root node is also a boundary node sum_of_boundary_nodes = root.data; // Sum up all the left nodes // in TOP DOWN manner LeftBoundary(root.left); // Sum up all the // leaf nodes Leaves(root.left); Leaves(root.right); // Sum up all the right nodes // in BOTTOM UP manner RightBoundary(root.right); // Return the sum of // all the boundary nodes return sum_of_boundary_nodes; } return 0;} // Driver codepublic static void Main(String []args){ Node root = newNode(10); root.left = newNode(2); root.right = newNode(5); root.left.left = newNode(8); root.left.right = newNode(14); root.right.left = newNode(11); root.right.right = newNode(3); root.left.right.left = newNode(12); root.right.left.right = newNode(1); root.right.left.left = newNode(7); Console.WriteLine(sumOfBoundaryNodes(root));}} // This code is contributed by Princi Singh", "e": 36866, "s": 34149, "text": null }, { "code": "<script> // JavaScript implementation of the approach let sum_of_boundary_nodes=0; // Binary Tree Node class Node { constructor(data) { this.left = null; this.right = null; this.data = data; } } // Utility function to create a node function newNode(data) { let temp = new Node(data); return temp; } // Function to sum up all the left boundary nodes // except the leaf nodes function LeftBoundary(root) { if (root != null) { if (root.left != null) { sum_of_boundary_nodes += root.data; LeftBoundary(root.left); } else if (root.right != null) { sum_of_boundary_nodes += root.data; LeftBoundary(root.right); } } } // Function to sum up all the right boundary nodes // except the leaf nodes function RightBoundary(root) { if (root != null) { if (root.right != null) { RightBoundary(root.right); sum_of_boundary_nodes += root.data; } else if (root.left != null) { RightBoundary(root.left); sum_of_boundary_nodes += root.data; } } } // Function to sum up all the leaf nodes // of a binary tree function Leaves(root) { if (root != null) { Leaves(root.left); // Sum it up if it is a leaf node if ((root.left == null) && (root.right == null)) sum_of_boundary_nodes += root.data; Leaves(root.right); } } // Function to return the sum of all the // boundary nodes of the given binary tree function sumOfBoundaryNodes(root) { if (root != null) { // Root node is also a boundary node sum_of_boundary_nodes = root.data; // Sum up all the left nodes // in TOP DOWN manner LeftBoundary(root.left); // Sum up all the // leaf nodes Leaves(root.left); Leaves(root.right); // Sum up all the right nodes // in BOTTOM UP manner RightBoundary(root.right); // Return the sum of // all the boundary nodes return sum_of_boundary_nodes; } return 0; } let root = newNode(10); root.left = newNode(2); root.right = newNode(5); root.left.left = newNode(8); root.left.right = newNode(14); root.right.left = newNode(11); root.right.right = newNode(3); root.left.right.left = newNode(12); root.right.left.right = newNode(1); root.right.left.left = newNode(7); document.write(sumOfBoundaryNodes(root)); </script>", "e": 39723, "s": 36866, "text": null }, { "code": null, "e": 39726, "s": 39723, "text": "48" }, { "code": null, "e": 39802, "s": 39728, "text": "Time Complexity: O(N) where N is the number of nodes in the binary tree. " }, { "code": null, "e": 39813, "s": 39802, "text": "andrew1234" }, { "code": null, "e": 39826, "s": 39813, "text": "princi singh" }, { "code": null, "e": 39836, "s": 39826, "text": "rutvik_56" }, { "code": null, "e": 39845, "s": 39836, "text": "mukesh07" }, { "code": null, "e": 39857, "s": 39845, "text": "Binary Tree" }, { "code": null, "e": 39872, "s": 39857, "text": "tree-traversal" }, { "code": null, "e": 39888, "s": 39872, "text": "Data Structures" }, { "code": null, "e": 39893, "s": 39888, "text": "Tree" }, { "code": null, "e": 39909, "s": 39893, "text": "Data Structures" }, { "code": null, "e": 39914, "s": 39909, "text": "Tree" }, { "code": null, "e": 40012, "s": 39914, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40021, "s": 40012, "text": "Comments" }, { "code": null, "e": 40034, "s": 40021, "text": "Old Comments" }, { "code": null, "e": 40070, "s": 40034, "text": "Introduction to Tree Data Structure" }, { "code": null, "e": 40091, "s": 40070, "text": "TCS NQT Coding Sheet" }, { "code": null, "e": 40150, "s": 40091, "text": "Program to implement Singly Linked List in C++ using class" }, { "code": null, "e": 40198, "s": 40150, "text": "Hash Functions and list/types of Hash functions" }, { "code": null, "e": 40252, "s": 40198, "text": "Finding in and out degrees of all vertices in a graph" }, { "code": null, "e": 40302, "s": 40252, "text": "Tree Traversals (Inorder, Preorder and Postorder)" }, { "code": null, "e": 40337, "s": 40302, "text": "Binary Tree | Set 1 (Introduction)" }, { "code": null, "e": 40371, "s": 40337, "text": "Level Order Binary Tree Traversal" }, { "code": null, "e": 40400, "s": 40371, "text": "AVL Tree | Set 1 (Insertion)" } ]
Minimize removal or insertions required to make two strings equal - GeeksforGeeks
14 Jun, 2021 Given two strings S and T, both of length N and S is an anagram of string T, the task is to convert string S to T by performing the following operations minimum number of times: Remove a character from either end. Insert a character at any position. Print the count of the minimum number of operations required. Examples: Input: S = “qpmon”, T = “mnopq”Output: 3Explanation: Operation 1: Remove ‘n’ from the end, and insert it at the second last position. The string S modifies to “qpmno”. Operation 2: Remove ‘q’ from the start, and insert it at the last position. The string S modifies to “pmnoq”. Operation 3: Remove ‘p’ from the start, and insert it at the second last position. The string S modifies to “mnopq” which is same as the desired string T. Input: S = “abab”, T = “baba”Output: 1 Approach: The given problem can be solved by the following observation: It is required to find the length of the longest substring of A which is a subsequence in B. Let the length of that sub string be L. Then, the remaining characters can be inserted without disturbing the existing order. To conclude, the optimal answer will be equal to N – L. Therefore, from the above observations, the minimum number of operations required is the difference between N and the length of the longest substring of the string A which is a subsequence in the string B. 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 longest substring// in string A which is a subsequence in Bint findLongestSubstring( int posA, int posB, string& A, string& B, bool canSkip, int n, vector<vector<vector<int> > >& dp){ // If the indices are out of bounds if (posA >= n || posB >= n) { return 0; } // If an already computed subproblem occurred if (dp[posA][posB][canSkip] != -1) { return dp[posA][posB][canSkip]; } // Required answer if the all the // characters of A and B are the same int op1 = 0; // Required answer if there is no // substring A which is a // subsequence in B int op2 = 0; // Required answer if the current // character in B is skipped int op3 = 0; if (A[posA] == B[posB]) { op1 = 1 + findLongestSubstring( posA + 1, posB + 1, A, B, 0, n, dp); } if (canSkip) { op2 = findLongestSubstring( posA + 1, posB, A, B, canSkip, n, dp); } op3 = findLongestSubstring( posA, posB + 1, A, B, canSkip, n, dp); // The answer for the subproblem is // the maximum among the three return dp[posA][posB][canSkip] = max(op1, max(op2, op3));} // Function to return the minimum strings// operations required to make two strings equalvoid minOperations(string A, string B, int N){ // Initialize the dp vector vector<vector<vector<int> > > dp( N, vector<vector<int> >( N, vector<int>(2, -1))); cout << N - findLongestSubstring( 0, 0, A, B, 1, N, dp);} // Driver Codeint main(){ string A = "abab"; string B = "baba"; int N = A.size(); minOperations(A, B, N); return 0;} // Java program for the above approachimport java.io.*;import java.util.*;class GFG { // Function to find the longest substring // in string A which is a subsequence in B static int findLongestSubstring(int posA, int posB, String A, String B, int canSkip, int n, int dp[][][]) { // If the indices are out of bounds if (posA >= n || posB >= n) { return 0; } // If an already computed subproblem occurred if (dp[posA][posB][canSkip] != -1) { return dp[posA][posB][canSkip]; } // Required answer if the all the // characters of A and B are the same int op1 = 0; // Required answer if there is no // substring A which is a // subsequence in B int op2 = 0; // Required answer if the current // character in B is skipped int op3 = 0; if (A.charAt(posA) == B.charAt(posB)) { op1 = 1 + findLongestSubstring(posA + 1, posB + 1, A, B, 0, n, dp); } if (canSkip == 1) { op2 = findLongestSubstring(posA + 1, posB, A, B, canSkip, n, dp); } op3 = findLongestSubstring(posA, posB + 1, A, B, canSkip, n, dp); // The answer for the subproblem is // the maximum among the three return dp[posA][posB][canSkip] = Math.max(op1, Math.max(op2, op3)); } // Function to return the minimum strings // operations required to make two strings equal static void minOperations(String A, String B, int N) { // Initialize the dp vector int[][][] dp = new int[N][N][2]; for(int i = 0; i < N; i++) { for(int j = 0; j < N; j++) { for(int k = 0; k < 2; k++) { dp[i][j][k] = -1; } } } System.out.println( N - findLongestSubstring(0, 0, A, B, 1, N, dp)); } // Driver Code public static void main(String[] args) { String A = "abab"; String B = "baba"; int N = A.length(); minOperations(A, B, N); }} // This code is contributed by Dharanendra L V # Python3 program for the above approach # Function to find the longest substring# in A which is a subsequence in Bdef findLongestSubstring(posA, posB, A, B, canSkip, n): global dp if (posA >= n or posB >= n): return 0 # If an already computed subproblem occurred if (dp[posA][posB][canSkip] != -1): return dp[posA][posB][canSkip] # Required answer if the all the # characters of A and B are the same op1 = 0 # Required answer if there is no # subA which is a # subsequence in B op2 = 0 # Required answer if the current # character in B is skipped op3 = 0 if (A[posA] == B[posB]): op1 = 1 + findLongestSubstring(posA + 1, posB + 1, A, B, 0, n) if (canSkip): op2 = findLongestSubstring(posA + 1, posB, A, B, canSkip, n) op3 = findLongestSubstring(posA, posB + 1, A, B, canSkip, n) # The answer for the subproblem is # the maximum among the three dp[posA][posB][canSkip] = max(op1, max(op2, op3)) return dp[posA][posB][canSkip] # Function to return the minimum strings# operations required to make two strings equaldef minOperations(A, B, N): print(N - findLongestSubstring(0, 0, A, B, 1, N)) # Driver Codeif __name__ == '__main__': A = "abab" B = "baba" dp = [[[-1, -1] for i in range(len(A))] for i in range(len(A))] N = len(A) minOperations(A, B, N) # This code is contributed by mohit kumar 29. // C# program for the above approachusing System;class GFG{ // Function to find the longest substring // in string A which is a subsequence in B static int findLongestSubstring(int posA, int posB, String A, String B, int canSkip, int n, int[, , ] dp) { // If the indices are out of bounds if (posA >= n || posB >= n) { return 0; } // If an already computed subproblem occurred if (dp[posA, posB, canSkip] != -1) { return dp[posA, posB, canSkip]; } // Required answer if the all the // characters of A and B are the same int op1 = 0; // Required answer if there is no // substring A which is a // subsequence in B int op2 = 0; // Required answer if the current // character in B is skipped int op3 = 0; if (A[posA] == B[posB]) { op1 = 1 + findLongestSubstring(posA + 1, posB + 1, A, B, 0, n, dp); } if (canSkip == 1) { op2 = findLongestSubstring(posA + 1, posB, A, B, canSkip, n, dp); } op3 = findLongestSubstring(posA, posB + 1, A, B, canSkip, n, dp); // The answer for the subproblem is // the maximum among the three return dp[posA, posB, canSkip] = Math.Max(op1, Math.Max(op2, op3)); } // Function to return the minimum strings // operations required to make two strings equal static void minOperations(String A, String B, int N) { // Initialize the dp vector int[, , ] dp = new int[N, N, 2]; for(int i = 0; i < N; i++) { for(int j = 0; j < N; j++) { for(int k = 0; k < 2; k++) { dp[i, j, k] = -1; } } } Console.WriteLine( N - findLongestSubstring(0, 0, A, B, 1, N, dp)); } // Driver Code static public void Main () { String A = "abab"; String B = "baba"; int N = A.Length; minOperations(A, B, N); }} // This code is contributed by Dharanendra L V <script> // JavaScript program for the above approach // Function to find the longest substring// in string A which is a subsequence in Bfunction findLongestSubstring( posA, posB, A, B, canSkip, n, dp){ // If the indices are out of bounds if (posA >= n || posB >= n) { return 0; } // If an already computed subproblem occurred if (dp[posA][posB][canSkip] != -1) { return dp[posA][posB][canSkip]; } // Required answer if the all the // characters of A and B are the same var op1 = 0; // Required answer if there is no // substring A which is a // subsequence in B var op2 = 0; // Required answer if the current // character in B is skipped var op3 = 0; if (A[posA] == B[posB]) { op1 = 1 + findLongestSubstring( posA + 1, posB + 1, A, B, 0, n, dp); } if (canSkip) { op2 = findLongestSubstring( posA + 1, posB, A, B, canSkip, n, dp); } op3 = findLongestSubstring( posA, posB + 1, A, B, canSkip, n, dp); // The answer for the subproblem is // the maximum among the three return dp[posA][posB][canSkip] = Math.max(op1, Math.max(op2, op3));} // Function to return the minimum strings// operations required to make two strings equalfunction minOperations(A, B, N){ // Initialize the dp vector var dp = Array.from(Array(N), ()=> Array(N)); for(var i =0; i<N; i++) for(var j =0; j<N; j++) dp[i][j] = new Array(2).fill(-1); document.write( N - findLongestSubstring( 0, 0, A, B, 1, N, dp));} // Driver Codevar A = "abab";var B = "baba";var N = A.length;minOperations(A, B, N); </script> 1 Time Complexity: O(N2 )Space Complexity: O(N2) mohit kumar 29 dharanendralv23 noob2000 subsequence substring Dynamic Programming Pattern Searching Strings Strings Dynamic Programming Pattern Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Optimal Substructure Property in Dynamic Programming | DP-2 Min Cost Path | DP-6 Maximum Subarray Sum using Divide and Conquer algorithm Optimal Binary Search Tree | DP-24 Greedy approach vs Dynamic programming KMP Algorithm for Pattern Searching Rabin-Karp Algorithm for Pattern Searching Naive algorithm for Pattern Searching Boyer Moore Algorithm for Pattern Searching Check if a string is substring of another
[ { "code": null, "e": 24281, "s": 24253, "text": "\n14 Jun, 2021" }, { "code": null, "e": 24459, "s": 24281, "text": "Given two strings S and T, both of length N and S is an anagram of string T, the task is to convert string S to T by performing the following operations minimum number of times:" }, { "code": null, "e": 24495, "s": 24459, "text": "Remove a character from either end." }, { "code": null, "e": 24531, "s": 24495, "text": "Insert a character at any position." }, { "code": null, "e": 24594, "s": 24531, "text": "Print the count of the minimum number of operations required. " }, { "code": null, "e": 24604, "s": 24594, "text": "Examples:" }, { "code": null, "e": 25039, "s": 24606, "text": "Input: S = “qpmon”, T = “mnopq”Output: 3Explanation: Operation 1: Remove ‘n’ from the end, and insert it at the second last position. The string S modifies to “qpmno”. Operation 2: Remove ‘q’ from the start, and insert it at the last position. The string S modifies to “pmnoq”. Operation 3: Remove ‘p’ from the start, and insert it at the second last position. The string S modifies to “mnopq” which is same as the desired string T." }, { "code": null, "e": 25078, "s": 25039, "text": "Input: S = “abab”, T = “baba”Output: 1" }, { "code": null, "e": 25153, "s": 25080, "text": "Approach: The given problem can be solved by the following observation: " }, { "code": null, "e": 25286, "s": 25153, "text": "It is required to find the length of the longest substring of A which is a subsequence in B. Let the length of that sub string be L." }, { "code": null, "e": 25372, "s": 25286, "text": "Then, the remaining characters can be inserted without disturbing the existing order." }, { "code": null, "e": 25428, "s": 25372, "text": "To conclude, the optimal answer will be equal to N – L." }, { "code": null, "e": 25636, "s": 25428, "text": " Therefore, from the above observations, the minimum number of operations required is the difference between N and the length of the longest substring of the string A which is a subsequence in the string B. " }, { "code": null, "e": 25688, "s": 25636, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 25692, "s": 25688, "text": "C++" }, { "code": null, "e": 25697, "s": 25692, "text": "Java" }, { "code": null, "e": 25705, "s": 25697, "text": "Python3" }, { "code": null, "e": 25708, "s": 25705, "text": "C#" }, { "code": null, "e": 25719, "s": 25708, "text": "Javascript" }, { "code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find the longest substring// in string A which is a subsequence in Bint findLongestSubstring( int posA, int posB, string& A, string& B, bool canSkip, int n, vector<vector<vector<int> > >& dp){ // If the indices are out of bounds if (posA >= n || posB >= n) { return 0; } // If an already computed subproblem occurred if (dp[posA][posB][canSkip] != -1) { return dp[posA][posB][canSkip]; } // Required answer if the all the // characters of A and B are the same int op1 = 0; // Required answer if there is no // substring A which is a // subsequence in B int op2 = 0; // Required answer if the current // character in B is skipped int op3 = 0; if (A[posA] == B[posB]) { op1 = 1 + findLongestSubstring( posA + 1, posB + 1, A, B, 0, n, dp); } if (canSkip) { op2 = findLongestSubstring( posA + 1, posB, A, B, canSkip, n, dp); } op3 = findLongestSubstring( posA, posB + 1, A, B, canSkip, n, dp); // The answer for the subproblem is // the maximum among the three return dp[posA][posB][canSkip] = max(op1, max(op2, op3));} // Function to return the minimum strings// operations required to make two strings equalvoid minOperations(string A, string B, int N){ // Initialize the dp vector vector<vector<vector<int> > > dp( N, vector<vector<int> >( N, vector<int>(2, -1))); cout << N - findLongestSubstring( 0, 0, A, B, 1, N, dp);} // Driver Codeint main(){ string A = \"abab\"; string B = \"baba\"; int N = A.size(); minOperations(A, B, N); return 0;}", "e": 27529, "s": 25719, "text": null }, { "code": "// Java program for the above approachimport java.io.*;import java.util.*;class GFG { // Function to find the longest substring // in string A which is a subsequence in B static int findLongestSubstring(int posA, int posB, String A, String B, int canSkip, int n, int dp[][][]) { // If the indices are out of bounds if (posA >= n || posB >= n) { return 0; } // If an already computed subproblem occurred if (dp[posA][posB][canSkip] != -1) { return dp[posA][posB][canSkip]; } // Required answer if the all the // characters of A and B are the same int op1 = 0; // Required answer if there is no // substring A which is a // subsequence in B int op2 = 0; // Required answer if the current // character in B is skipped int op3 = 0; if (A.charAt(posA) == B.charAt(posB)) { op1 = 1 + findLongestSubstring(posA + 1, posB + 1, A, B, 0, n, dp); } if (canSkip == 1) { op2 = findLongestSubstring(posA + 1, posB, A, B, canSkip, n, dp); } op3 = findLongestSubstring(posA, posB + 1, A, B, canSkip, n, dp); // The answer for the subproblem is // the maximum among the three return dp[posA][posB][canSkip] = Math.max(op1, Math.max(op2, op3)); } // Function to return the minimum strings // operations required to make two strings equal static void minOperations(String A, String B, int N) { // Initialize the dp vector int[][][] dp = new int[N][N][2]; for(int i = 0; i < N; i++) { for(int j = 0; j < N; j++) { for(int k = 0; k < 2; k++) { dp[i][j][k] = -1; } } } System.out.println( N - findLongestSubstring(0, 0, A, B, 1, N, dp)); } // Driver Code public static void main(String[] args) { String A = \"abab\"; String B = \"baba\"; int N = A.length(); minOperations(A, B, N); }} // This code is contributed by Dharanendra L V", "e": 29609, "s": 27529, "text": null }, { "code": "# Python3 program for the above approach # Function to find the longest substring# in A which is a subsequence in Bdef findLongestSubstring(posA, posB, A, B, canSkip, n): global dp if (posA >= n or posB >= n): return 0 # If an already computed subproblem occurred if (dp[posA][posB][canSkip] != -1): return dp[posA][posB][canSkip] # Required answer if the all the # characters of A and B are the same op1 = 0 # Required answer if there is no # subA which is a # subsequence in B op2 = 0 # Required answer if the current # character in B is skipped op3 = 0 if (A[posA] == B[posB]): op1 = 1 + findLongestSubstring(posA + 1, posB + 1, A, B, 0, n) if (canSkip): op2 = findLongestSubstring(posA + 1, posB, A, B, canSkip, n) op3 = findLongestSubstring(posA, posB + 1, A, B, canSkip, n) # The answer for the subproblem is # the maximum among the three dp[posA][posB][canSkip] = max(op1, max(op2, op3)) return dp[posA][posB][canSkip] # Function to return the minimum strings# operations required to make two strings equaldef minOperations(A, B, N): print(N - findLongestSubstring(0, 0, A, B, 1, N)) # Driver Codeif __name__ == '__main__': A = \"abab\" B = \"baba\" dp = [[[-1, -1] for i in range(len(A))] for i in range(len(A))] N = len(A) minOperations(A, B, N) # This code is contributed by mohit kumar 29.", "e": 31026, "s": 29609, "text": null }, { "code": "// C# program for the above approachusing System;class GFG{ // Function to find the longest substring // in string A which is a subsequence in B static int findLongestSubstring(int posA, int posB, String A, String B, int canSkip, int n, int[, , ] dp) { // If the indices are out of bounds if (posA >= n || posB >= n) { return 0; } // If an already computed subproblem occurred if (dp[posA, posB, canSkip] != -1) { return dp[posA, posB, canSkip]; } // Required answer if the all the // characters of A and B are the same int op1 = 0; // Required answer if there is no // substring A which is a // subsequence in B int op2 = 0; // Required answer if the current // character in B is skipped int op3 = 0; if (A[posA] == B[posB]) { op1 = 1 + findLongestSubstring(posA + 1, posB + 1, A, B, 0, n, dp); } if (canSkip == 1) { op2 = findLongestSubstring(posA + 1, posB, A, B, canSkip, n, dp); } op3 = findLongestSubstring(posA, posB + 1, A, B, canSkip, n, dp); // The answer for the subproblem is // the maximum among the three return dp[posA, posB, canSkip] = Math.Max(op1, Math.Max(op2, op3)); } // Function to return the minimum strings // operations required to make two strings equal static void minOperations(String A, String B, int N) { // Initialize the dp vector int[, , ] dp = new int[N, N, 2]; for(int i = 0; i < N; i++) { for(int j = 0; j < N; j++) { for(int k = 0; k < 2; k++) { dp[i, j, k] = -1; } } } Console.WriteLine( N - findLongestSubstring(0, 0, A, B, 1, N, dp)); } // Driver Code static public void Main () { String A = \"abab\"; String B = \"baba\"; int N = A.Length; minOperations(A, B, N); }} // This code is contributed by Dharanendra L V", "e": 33357, "s": 31026, "text": null }, { "code": "<script> // JavaScript program for the above approach // Function to find the longest substring// in string A which is a subsequence in Bfunction findLongestSubstring( posA, posB, A, B, canSkip, n, dp){ // If the indices are out of bounds if (posA >= n || posB >= n) { return 0; } // If an already computed subproblem occurred if (dp[posA][posB][canSkip] != -1) { return dp[posA][posB][canSkip]; } // Required answer if the all the // characters of A and B are the same var op1 = 0; // Required answer if there is no // substring A which is a // subsequence in B var op2 = 0; // Required answer if the current // character in B is skipped var op3 = 0; if (A[posA] == B[posB]) { op1 = 1 + findLongestSubstring( posA + 1, posB + 1, A, B, 0, n, dp); } if (canSkip) { op2 = findLongestSubstring( posA + 1, posB, A, B, canSkip, n, dp); } op3 = findLongestSubstring( posA, posB + 1, A, B, canSkip, n, dp); // The answer for the subproblem is // the maximum among the three return dp[posA][posB][canSkip] = Math.max(op1, Math.max(op2, op3));} // Function to return the minimum strings// operations required to make two strings equalfunction minOperations(A, B, N){ // Initialize the dp vector var dp = Array.from(Array(N), ()=> Array(N)); for(var i =0; i<N; i++) for(var j =0; j<N; j++) dp[i][j] = new Array(2).fill(-1); document.write( N - findLongestSubstring( 0, 0, A, B, 1, N, dp));} // Driver Codevar A = \"abab\";var B = \"baba\";var N = A.length;minOperations(A, B, N); </script>", "e": 35090, "s": 33357, "text": null }, { "code": null, "e": 35092, "s": 35090, "text": "1" }, { "code": null, "e": 35141, "s": 35094, "text": "Time Complexity: O(N2 )Space Complexity: O(N2)" }, { "code": null, "e": 35156, "s": 35141, "text": "mohit kumar 29" }, { "code": null, "e": 35172, "s": 35156, "text": "dharanendralv23" }, { "code": null, "e": 35181, "s": 35172, "text": "noob2000" }, { "code": null, "e": 35193, "s": 35181, "text": "subsequence" }, { "code": null, "e": 35203, "s": 35193, "text": "substring" }, { "code": null, "e": 35223, "s": 35203, "text": "Dynamic Programming" }, { "code": null, "e": 35241, "s": 35223, "text": "Pattern Searching" }, { "code": null, "e": 35249, "s": 35241, "text": "Strings" }, { "code": null, "e": 35257, "s": 35249, "text": "Strings" }, { "code": null, "e": 35277, "s": 35257, "text": "Dynamic Programming" }, { "code": null, "e": 35295, "s": 35277, "text": "Pattern Searching" }, { "code": null, "e": 35393, "s": 35295, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35402, "s": 35393, "text": "Comments" }, { "code": null, "e": 35415, "s": 35402, "text": "Old Comments" }, { "code": null, "e": 35475, "s": 35415, "text": "Optimal Substructure Property in Dynamic Programming | DP-2" }, { "code": null, "e": 35496, "s": 35475, "text": "Min Cost Path | DP-6" }, { "code": null, "e": 35552, "s": 35496, "text": "Maximum Subarray Sum using Divide and Conquer algorithm" }, { "code": null, "e": 35587, "s": 35552, "text": "Optimal Binary Search Tree | DP-24" }, { "code": null, "e": 35626, "s": 35587, "text": "Greedy approach vs Dynamic programming" }, { "code": null, "e": 35662, "s": 35626, "text": "KMP Algorithm for Pattern Searching" }, { "code": null, "e": 35705, "s": 35662, "text": "Rabin-Karp Algorithm for Pattern Searching" }, { "code": null, "e": 35743, "s": 35705, "text": "Naive algorithm for Pattern Searching" }, { "code": null, "e": 35787, "s": 35743, "text": "Boyer Moore Algorithm for Pattern Searching" } ]
How to find the rank of a matrix in R?
The rank of a matrix is defined as the maximum number of linearly independent vectors in rows or columns. If we have a matrix with dimensions R x C, having R number of rows and C number of columns, and if R is less than C then the rank of the matrix would be R. To find the rank of a matrix in R, we can use rankMatrix function in Matrix package. Loading Matrix package − library(Matrix) Live Demo M1<-matrix(1:9,ncol=3) M1 [,1] [,2] [,3] [1,] 1 4 7 [2,] 2 5 8 [3,] 3 6 9 rankMatrix(M1) [1] [1] 2 Live Demo M2<-matrix(1:36,nrow=6) M2 [,1] [,2] [,3] [,4] [,5] [,6] [1,] 1 7 13 19 25 31 [2,] 2 8 14 20 26 32 [3,] 3 9 15 21 27 33 [4,] 4 10 16 22 28 34 [5,] 5 11 18 24 30 36 rankMatrix(M2) [1] [1] 2 Live Demo M3<-matrix(sample(0:9,100,replace=TRUE),nrow=20) M3 [,1] [,2] [,3] [,4] [,5] [1,] 9 8 1 4 1 [2,] 5 3 0 6 1 [3,] 2 6 5 5 4 [4,] 5 8 3 7 5 [5,] 3 1 4 0 3 [6,] 1 5 5 3 5 [7,] 0 3 0 3 5 [8,] 1 9 4 0 4 [9,] 1 4 3 7 6 [10,] 1 3 6 1 4 [11,] 6 9 2 5 9 [12,] 7 0 2 8 1 [13,] 5 9 4 1 1 [14,] 9 1 1 6 4 [15,] 1 4 4 0 7 [16,] 6 0 9 2 7 [17,] 9 3 0 2 1 [18,] 9 6 0 7 2 [19,] 5 2 0 8 5 [20,] 8 8 4 0 4 rankMatrix(M3) [1] [1] 5 Live Demo M4<-matrix(sample(21:50,160,replace=TRUE),nrow=20) M4 [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [1,] 49 35 25 36 31 22 49 42 [2,] 45 33 21 39 37 26 41 37 [3,] 36 30 46 50 26 32 24 49 [4,] 33 39 31 39 37 50 50 32 [5,] 41 38 39 38 40 25 42 30 [6,] 34 49 26 34 24 34 42 26 [7,] 40 44 30 21 27 47 32 47 [8,] 35 27 21 25 37 28 48 27 [9,] 34 50 41 38 39 27 43 40 [10,] 21 41 50 28 32 38 22 25 [11,] 26 46 34 29 24 38 28 39 [12,] 36 41 36 47 49 48 49 31 [13,] 44 50 37 38 33 26 37 45 [14,] 31 22 47 37 47 41 23 45 [15,] 42 39 38 26 35 21 31 31 [16,] 50 29 40 47 48 34 23 29 [17,] 49 21 30 47 24 21 43 47 [18,] 27 22 25 34 45 28 49 45 [19,] 38 39 32 31 29 23 34 45 [20,] 45 37 31 43 40 27 29 36 rankMatrix(M4) [1] [1] 8 Live Demo M5<-matrix(sample(rnorm(20),25,replace=TRUE),nrow=5) M5 [,1] [,2] [,3] [,4] [,5] [1,] 0.73475325 -1.2186186 -0.21496111 1.8642877 1.1133489 [2,] -0.09091262 -0.4513579 0.18346741 0.1834674 -0.4513579 [3,] 1.55003168 -0.1454168 0.28244025 0.5674004 1.5706586 [4,] -0.90693971 -1.2186186 -0.09091262 -0.1454168 1.0289755 [5,] -0.45135792 0.5674004 0.28244025 -0.2149611 1.5500317 rankMatrix(M5) [1] [1] 5 Live Demo M6<-matrix(sample(rexp(5,2),20,replace=TRUE),nrow=10) M6 [,1] [,2] [1,] 0.2969787 3.5003481 [2,] 0.5462926 3.5003481 [3,] 1.0018821 0.5462926 [4,] 3.5003481 0.2969787 [5,] 1.0018821 0.2969787 [6,] 1.0018821 0.2969787 [7,] 1.0018821 0.5462926 [8,] 0.2133455 0.2133455 [9,] 0.5462926 3.5003481 [10,] 0.2969787 0.2133455 rankMatrix(M6) [1] [1] 2
[ { "code": null, "e": 1409, "s": 1062, "text": "The rank of a matrix is defined as the maximum number of linearly independent vectors in rows or columns. If we have a matrix with dimensions R x C, having R number of rows and C number of columns, and if R is less than C then the rank of the matrix would be R. To find the rank of a matrix in R, we can use rankMatrix function in Matrix package." }, { "code": null, "e": 1434, "s": 1409, "text": "Loading Matrix package −" }, { "code": null, "e": 1450, "s": 1434, "text": "library(Matrix)" }, { "code": null, "e": 1461, "s": 1450, "text": " Live Demo" }, { "code": null, "e": 1487, "s": 1461, "text": "M1<-matrix(1:9,ncol=3)\nM1" }, { "code": null, "e": 1535, "s": 1487, "text": "[,1] [,2] [,3]\n[1,] 1 4 7\n[2,] 2 5 8\n[3,] 3 6 9" }, { "code": null, "e": 1560, "s": 1535, "text": "rankMatrix(M1)\n[1] [1] 2" }, { "code": null, "e": 1571, "s": 1560, "text": " Live Demo" }, { "code": null, "e": 1598, "s": 1571, "text": "M2<-matrix(1:36,nrow=6)\nM2" }, { "code": null, "e": 1797, "s": 1598, "text": " [,1] [,2] [,3] [,4] [,5] [,6]\n[1,] 1 7 13 19 25 31\n[2,] 2 8 14 20 26 32\n[3,] 3 9 15 21 27 33\n[4,] 4 10 16 22 28 34\n[5,] 5 11 18 24 30 36" }, { "code": null, "e": 1822, "s": 1797, "text": "rankMatrix(M2)\n[1] [1] 2" }, { "code": null, "e": 1833, "s": 1822, "text": " Live Demo" }, { "code": null, "e": 1885, "s": 1833, "text": "M3<-matrix(sample(0:9,100,replace=TRUE),nrow=20)\nM3" }, { "code": null, "e": 2221, "s": 1885, "text": "[,1] [,2] [,3] [,4] [,5]\n[1,] 9 8 1 4 1\n[2,] 5 3 0 6 1\n[3,] 2 6 5 5 4\n[4,] 5 8 3 7 5\n[5,] 3 1 4 0 3\n[6,] 1 5 5 3 5\n[7,] 0 3 0 3 5\n[8,] 1 9 4 0 4\n[9,] 1 4 3 7 6\n[10,] 1 3 6 1 4\n[11,] 6 9 2 5 9\n[12,] 7 0 2 8 1\n[13,] 5 9 4 1 1\n[14,] 9 1 1 6 4\n[15,] 1 4 4 0 7\n[16,] 6 0 9 2 7\n[17,] 9 3 0 2 1\n[18,] 9 6 0 7 2\n[19,] 5 2 0 8 5\n[20,] 8 8 4 0 4" }, { "code": null, "e": 2246, "s": 2221, "text": "rankMatrix(M3)\n[1] [1] 5" }, { "code": null, "e": 2257, "s": 2246, "text": " Live Demo" }, { "code": null, "e": 2311, "s": 2257, "text": "M4<-matrix(sample(21:50,160,replace=TRUE),nrow=20)\nM4" }, { "code": null, "e": 2992, "s": 2311, "text": " [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]\n[1,] 49 35 25 36 31 22 49 42\n[2,] 45 33 21 39 37 26 41 37\n[3,] 36 30 46 50 26 32 24 49\n[4,] 33 39 31 39 37 50 50 32\n[5,] 41 38 39 38 40 25 42 30\n[6,] 34 49 26 34 24 34 42 26\n[7,] 40 44 30 21 27 47 32 47\n[8,] 35 27 21 25 37 28 48 27\n[9,] 34 50 41 38 39 27 43 40\n[10,] 21 41 50 28 32 38 22 25\n[11,] 26 46 34 29 24 38 28 39\n[12,] 36 41 36 47 49 48 49 31\n[13,] 44 50 37 38 33 26 37 45\n[14,] 31 22 47 37 47 41 23 45\n[15,] 42 39 38 26 35 21 31 31\n[16,] 50 29 40 47 48 34 23 29\n[17,] 49 21 30 47 24 21 43 47\n[18,] 27 22 25 34 45 28 49 45\n[19,] 38 39 32 31 29 23 34 45\n[20,] 45 37 31 43 40 27 29 36" }, { "code": null, "e": 3017, "s": 2992, "text": "rankMatrix(M4)\n[1] [1] 8" }, { "code": null, "e": 3028, "s": 3017, "text": " Live Demo" }, { "code": null, "e": 3084, "s": 3028, "text": "M5<-matrix(sample(rnorm(20),25,replace=TRUE),nrow=5)\nM5" }, { "code": null, "e": 3406, "s": 3084, "text": "[,1] [,2] [,3] [,4] [,5]\n[1,] 0.73475325 -1.2186186 -0.21496111 1.8642877 1.1133489\n[2,] -0.09091262 -0.4513579 0.18346741 0.1834674 -0.4513579\n[3,] 1.55003168 -0.1454168 0.28244025 0.5674004 1.5706586\n[4,] -0.90693971 -1.2186186 -0.09091262 -0.1454168 1.0289755\n[5,] -0.45135792 0.5674004 0.28244025 -0.2149611 1.5500317" }, { "code": null, "e": 3431, "s": 3406, "text": "rankMatrix(M5)\n[1] [1] 5" }, { "code": null, "e": 3442, "s": 3431, "text": " Live Demo" }, { "code": null, "e": 3499, "s": 3442, "text": "M6<-matrix(sample(rexp(5,2),20,replace=TRUE),nrow=10)\nM6" }, { "code": null, "e": 3760, "s": 3499, "text": "[,1] [,2]\n[1,] 0.2969787 3.5003481\n[2,] 0.5462926 3.5003481\n[3,] 1.0018821 0.5462926\n[4,] 3.5003481 0.2969787\n[5,] 1.0018821 0.2969787\n[6,] 1.0018821 0.2969787\n[7,] 1.0018821 0.5462926\n[8,] 0.2133455 0.2133455\n[9,] 0.5462926 3.5003481\n[10,] 0.2969787 0.2133455" }, { "code": null, "e": 3785, "s": 3760, "text": "rankMatrix(M6)\n[1] [1] 2" } ]
Does Java support multiple inheritance? Why? How can we resolve this?
Whenever, you extend a class a copy of superclass’s members is available to the subclass object and, when you can call the method of the superclass using the object of the subclass. In the following example, we have a class named SuperClass with a method with name demo(). We are extending this class with another class (SubClass). Now, you create an object of the subclass and call the method demo(). Live Demo class SuperClass{ public void demo() { System.out.println("demo method"); } } public class SubClass extends SuperClass { public static void main(String args[]) { SubClass obj = new SubClass(); obj.demo(); } } demo method For suppose, if we have two classes namely, SuperClass1 and SuperClass2 with the same method say demo() (including parameters) as shown below − class SuperClass1{ public void demo() { System.out.println("demo method"); } } class SuperClass2{ public void demo() { System.out.println("demo method"); } } Now, from another class, if extend both the classes as − public class SubClass extends SuperClass1, SuperClass2 { public static void main(String args[]) { SubClass obj = new SubClass(); obj.demo(); } } According to the basic rule of inheritance, a copy of both demo() methods should be created in the subclass object which leaves the subclass with two methods with the same prototype. Then, if you call the demo() method using the object of the subclass compiler faces an ambiguous situation not knowing which method to call. Therefore, in Java multiple inheritance is not allowed and, you cannot extend more than one other class. Still, if you try to do so, a compile-time error is generated. On compiling, the above program generates the following error − MultipleInheritanceExample.java:9: error: '{' expected public class MultipleInheritanceExample extends MyInterface1, MyInterface2{ ^ 1 error In case of multiple interfaces with the same default method. In the concrete class implementing both interfaces, you can implement the common method and call both super methods. thus You can achieve multiple inheritance in Java using interfaces. Live Demo interface MyInterface1{ public static int num = 100; public default void display() { System.out.println("display method of MyInterface1"); } } interface MyInterface2{ public static int num = 1000; public default void display() { System.out.println("display method of MyInterface2"); } } public class InterfaceExample implements MyInterface1, MyInterface2{ public void display() { System.out.println("This is the implementation of the display method"); } public void show() { MyInterface1.super.display(); MyInterface2.super.display(); } public static void main(String args[]) { InterfaceExample obj = new InterfaceExample(); obj.show(); } } display method of MyInterface1 display method of MyInterface2
[ { "code": null, "e": 1244, "s": 1062, "text": "Whenever, you extend a class a copy of superclass’s members is available to the subclass object and, when you can call the method of the superclass using the object of the subclass." }, { "code": null, "e": 1394, "s": 1244, "text": "In the following example, we have a class named SuperClass with a method with name demo(). We are extending this class with another class (SubClass)." }, { "code": null, "e": 1464, "s": 1394, "text": "Now, you create an object of the subclass and call the method demo()." }, { "code": null, "e": 1475, "s": 1464, "text": " Live Demo" }, { "code": null, "e": 1714, "s": 1475, "text": "class SuperClass{\n public void demo() {\n System.out.println(\"demo method\");\n }\n}\npublic class SubClass extends SuperClass {\n public static void main(String args[]) {\n SubClass obj = new SubClass();\n obj.demo();\n }\n}" }, { "code": null, "e": 1726, "s": 1714, "text": "demo method" }, { "code": null, "e": 1870, "s": 1726, "text": "For suppose, if we have two classes namely, SuperClass1 and SuperClass2 with the same method say demo() (including parameters) as shown below −" }, { "code": null, "e": 2052, "s": 1870, "text": "class SuperClass1{\n public void demo() {\n System.out.println(\"demo method\");\n }\n}\nclass SuperClass2{\n public void demo() {\n System.out.println(\"demo method\");\n }\n}" }, { "code": null, "e": 2109, "s": 2052, "text": "Now, from another class, if extend both the classes as −" }, { "code": null, "e": 2272, "s": 2109, "text": "public class SubClass extends SuperClass1, SuperClass2 {\n public static void main(String args[]) {\n SubClass obj = new SubClass();\n obj.demo();\n }\n}" }, { "code": null, "e": 2596, "s": 2272, "text": "According to the basic rule of inheritance, a copy of both demo() methods should be created in the subclass object which leaves the subclass with two methods with the same prototype. Then, if you call the demo() method using the object of the subclass compiler faces an ambiguous situation not knowing which method to call." }, { "code": null, "e": 2764, "s": 2596, "text": "Therefore, in Java multiple inheritance is not allowed and, you cannot extend more than one other class. Still, if you try to do so, a compile-time error is generated." }, { "code": null, "e": 2828, "s": 2764, "text": "On compiling, the above program generates the following error −" }, { "code": null, "e": 3032, "s": 2828, "text": "MultipleInheritanceExample.java:9: error: '{' expected\npublic class MultipleInheritanceExample extends MyInterface1, MyInterface2{\n ^\n1 error" }, { "code": null, "e": 3278, "s": 3032, "text": "In case of multiple interfaces with the same default method. In the concrete class implementing both interfaces, you can implement the common method and call both super methods. thus You can achieve multiple inheritance in Java using interfaces." }, { "code": null, "e": 3289, "s": 3278, "text": " Live Demo" }, { "code": null, "e": 4010, "s": 3289, "text": "interface MyInterface1{\n public static int num = 100;\n public default void display() {\n System.out.println(\"display method of MyInterface1\");\n }\n}\ninterface MyInterface2{\n public static int num = 1000;\n public default void display() {\n System.out.println(\"display method of MyInterface2\");\n }\n}\n\npublic class InterfaceExample implements MyInterface1, MyInterface2{\n public void display() {\n System.out.println(\"This is the implementation of the display method\");\n }\n public void show() {\n MyInterface1.super.display();\n MyInterface2.super.display();\n }\n\n public static void main(String args[]) {\n InterfaceExample obj = new InterfaceExample();\n obj.show();\n }\n}" }, { "code": null, "e": 4072, "s": 4010, "text": "display method of MyInterface1\ndisplay method of MyInterface2" } ]
Find two numbers with sum and product both same as N - GeeksforGeeks
10 May, 2021 Given an integer N, the task is to find two numbers a and b such that a * b = N and a + b = N. Print “NO” if no such numbers are possible. Examples: Input: N = 69 Output: a = 67.9851 b = 1.01493Input: N = 1 Output: NO Approach: If observed carefully, we are given with sum and product of roots of a quadratic equation. If N2 – 4*N < 0 then only imaginary roots are possible for the equation, hence “NO” will be the answer. Else a and b will be: a = ( N + sqrt( N2 – 4*N ) ) / 2 b = ( N – sqrt( N2 – 4*N ) ) / 2 Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ program to find a and b// such that a*b=N and a+b=N#include <bits/stdc++.h>using namespace std; // Function to return the smallest stringvoid findAandB(double N){ double val = N * N - 4.0 * N; // Not possible if (val < 0) { cout << "NO"; return; } // find a and b double a = (N + sqrt(val)) / 2.0; double b = (N - sqrt(val)) / 2.0; cout << "a = " << a << endl; cout << "b = " << b << endl;} // Driver Codeint main(){ double N = 69.0; findAandB(N); return 0;} // Java program to find a and b// such that a*b=N and a+b=N class GFG{// Function to return the smallest stringstatic void findAandB(double N){ double val = N * N - 4.0 * N; // Not possible if (val < 0) { System.out.println("NO"); return; } // find a and b double a = (N + Math.sqrt(val)) / 2.0; double b = (N - Math.sqrt(val)) / 2.0; System.out.println("a = "+a); System.out.println("b = "+b);} // Driver Codepublic static void main(String[] args){ double N = 69.0; findAandB(N);}}// This Code is contributed by mits # Python 3 program to find a and b# such that a*b=N and a+b=Nfrom math import sqrt # Function to return the# smallest stringdef findAandB(N): val = N * N - 4.0 * N # Not possible if (val < 0): print("NO") return # find a and b a = (N + sqrt(val)) / 2.0 b = (N - sqrt(val)) / 2.0 print("a =", '{0:.6}' . format(a)) print("b =", '{0:.6}' . format(b)) # Driver Codeif __name__ == '__main__': N = 69.0 findAandB(N) # This code is contributed# by SURENDRA_GANGWAR // C# program to find a and b// such that a*b=N and a+b=N using System;class GFG{// Function to return the smallest stringstatic void findAandB(double N){double val = N * N - 4.0 * N; // Not possibleif (val < 0) {Console.WriteLine("NO");return;} // find a and bdouble a = (N + Math.Sqrt(val)) / 2.0;double b = (N - Math.Sqrt(val)) / 2.0; Console.WriteLine("a = "+a);Console.WriteLine("b = "+b);} // Driver Codestatic void Main(){double N = 69.0;findAandB(N);}// This code is contributed by ANKITRAI1} <?php// PHP program to find a and b// such that a*b=N and a+b=N // Function to return the// smallest stringfunction findAandB($N){ $val = $N * $N - 4.0 * $N; // Not possible if ($val < 0) { echo "NO"; return; } // find a and b $a = ($N + sqrt($val)) / 2.0; $b = ($N - sqrt($val)) / 2.0; echo "a = " , $a, "\n"; echo "b = " , $b, "\n";} // Driver Code$N = 69.0;findAandB($N); // This code is contributed by ajit?> <script> // Javascript program to find a and b // such that a*b=N and a+b=N // Function to return the smallest string function findAandB(N) { let val = N * N - 4.0 * N; // Not possible if (val < 0) { document.write("NO"); return; } // find a and b let a = (N + Math.sqrt(val)) / 2.0; let b = (N - Math.sqrt(val)) / 2.0; document.write("a = "+a.toFixed(4) + "</br>"); document.write("b = "+b.toFixed(5)); } let N = 69.0; findAandB(N); </script> a = 67.9851 b = 1.01493 Mithun Kumar ankthon jit_t SURENDRA_GANGWAR divyesh072019 Algebra Competitive Programming Mathematical School Programming Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Pairs with same Manhattan and Euclidean distance Remove all occurrences of a character in a string | Recursive approach Breadth First Traversal ( BFS ) on a 2D array Most important type of Algorithms Sequence Alignment problem 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) Program to find sum of elements in a given array
[ { "code": null, "e": 24711, "s": 24683, "text": "\n10 May, 2021" }, { "code": null, "e": 24862, "s": 24711, "text": "Given an integer N, the task is to find two numbers a and b such that a * b = N and a + b = N. Print “NO” if no such numbers are possible. Examples: " }, { "code": null, "e": 24933, "s": 24862, "text": "Input: N = 69 Output: a = 67.9851 b = 1.01493Input: N = 1 Output: NO " }, { "code": null, "e": 25164, "s": 24935, "text": "Approach: If observed carefully, we are given with sum and product of roots of a quadratic equation. If N2 – 4*N < 0 then only imaginary roots are possible for the equation, hence “NO” will be the answer. Else a and b will be: " }, { "code": null, "e": 25232, "s": 25164, "text": "a = ( N + sqrt( N2 – 4*N ) ) / 2 b = ( N – sqrt( N2 – 4*N ) ) / 2 " }, { "code": null, "e": 25285, "s": 25232, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 25289, "s": 25285, "text": "C++" }, { "code": null, "e": 25294, "s": 25289, "text": "Java" }, { "code": null, "e": 25302, "s": 25294, "text": "Python3" }, { "code": null, "e": 25305, "s": 25302, "text": "C#" }, { "code": null, "e": 25309, "s": 25305, "text": "PHP" }, { "code": null, "e": 25320, "s": 25309, "text": "Javascript" }, { "code": "// C++ program to find a and b// such that a*b=N and a+b=N#include <bits/stdc++.h>using namespace std; // Function to return the smallest stringvoid findAandB(double N){ double val = N * N - 4.0 * N; // Not possible if (val < 0) { cout << \"NO\"; return; } // find a and b double a = (N + sqrt(val)) / 2.0; double b = (N - sqrt(val)) / 2.0; cout << \"a = \" << a << endl; cout << \"b = \" << b << endl;} // Driver Codeint main(){ double N = 69.0; findAandB(N); return 0;}", "e": 25839, "s": 25320, "text": null }, { "code": "// Java program to find a and b// such that a*b=N and a+b=N class GFG{// Function to return the smallest stringstatic void findAandB(double N){ double val = N * N - 4.0 * N; // Not possible if (val < 0) { System.out.println(\"NO\"); return; } // find a and b double a = (N + Math.sqrt(val)) / 2.0; double b = (N - Math.sqrt(val)) / 2.0; System.out.println(\"a = \"+a); System.out.println(\"b = \"+b);} // Driver Codepublic static void main(String[] args){ double N = 69.0; findAandB(N);}}// This Code is contributed by mits", "e": 26407, "s": 25839, "text": null }, { "code": "# Python 3 program to find a and b# such that a*b=N and a+b=Nfrom math import sqrt # Function to return the# smallest stringdef findAandB(N): val = N * N - 4.0 * N # Not possible if (val < 0): print(\"NO\") return # find a and b a = (N + sqrt(val)) / 2.0 b = (N - sqrt(val)) / 2.0 print(\"a =\", '{0:.6}' . format(a)) print(\"b =\", '{0:.6}' . format(b)) # Driver Codeif __name__ == '__main__': N = 69.0 findAandB(N) # This code is contributed# by SURENDRA_GANGWAR ", "e": 26924, "s": 26407, "text": null }, { "code": "// C# program to find a and b// such that a*b=N and a+b=N using System;class GFG{// Function to return the smallest stringstatic void findAandB(double N){double val = N * N - 4.0 * N; // Not possibleif (val < 0) {Console.WriteLine(\"NO\");return;} // find a and bdouble a = (N + Math.Sqrt(val)) / 2.0;double b = (N - Math.Sqrt(val)) / 2.0; Console.WriteLine(\"a = \"+a);Console.WriteLine(\"b = \"+b);} // Driver Codestatic void Main(){double N = 69.0;findAandB(N);}// This code is contributed by ANKITRAI1}", "e": 27425, "s": 26924, "text": null }, { "code": "<?php// PHP program to find a and b// such that a*b=N and a+b=N // Function to return the// smallest stringfunction findAandB($N){ $val = $N * $N - 4.0 * $N; // Not possible if ($val < 0) { echo \"NO\"; return; } // find a and b $a = ($N + sqrt($val)) / 2.0; $b = ($N - sqrt($val)) / 2.0; echo \"a = \" , $a, \"\\n\"; echo \"b = \" , $b, \"\\n\";} // Driver Code$N = 69.0;findAandB($N); // This code is contributed by ajit?>", "e": 27885, "s": 27425, "text": null }, { "code": "<script> // Javascript program to find a and b // such that a*b=N and a+b=N // Function to return the smallest string function findAandB(N) { let val = N * N - 4.0 * N; // Not possible if (val < 0) { document.write(\"NO\"); return; } // find a and b let a = (N + Math.sqrt(val)) / 2.0; let b = (N - Math.sqrt(val)) / 2.0; document.write(\"a = \"+a.toFixed(4) + \"</br>\"); document.write(\"b = \"+b.toFixed(5)); } let N = 69.0; findAandB(N); </script>", "e": 28433, "s": 27885, "text": null }, { "code": null, "e": 28457, "s": 28433, "text": "a = 67.9851\nb = 1.01493" }, { "code": null, "e": 28472, "s": 28459, "text": "Mithun Kumar" }, { "code": null, "e": 28480, "s": 28472, "text": "ankthon" }, { "code": null, "e": 28486, "s": 28480, "text": "jit_t" }, { "code": null, "e": 28503, "s": 28486, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 28517, "s": 28503, "text": "divyesh072019" }, { "code": null, "e": 28525, "s": 28517, "text": "Algebra" }, { "code": null, "e": 28549, "s": 28525, "text": "Competitive Programming" }, { "code": null, "e": 28562, "s": 28549, "text": "Mathematical" }, { "code": null, "e": 28581, "s": 28562, "text": "School Programming" }, { "code": null, "e": 28594, "s": 28581, "text": "Mathematical" }, { "code": null, "e": 28692, "s": 28594, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28701, "s": 28692, "text": "Comments" }, { "code": null, "e": 28714, "s": 28701, "text": "Old Comments" }, { "code": null, "e": 28763, "s": 28714, "text": "Pairs with same Manhattan and Euclidean distance" }, { "code": null, "e": 28834, "s": 28763, "text": "Remove all occurrences of a character in a string | Recursive approach" }, { "code": null, "e": 28880, "s": 28834, "text": "Breadth First Traversal ( BFS ) on a 2D array" }, { "code": null, "e": 28914, "s": 28880, "text": "Most important type of Algorithms" }, { "code": null, "e": 28941, "s": 28914, "text": "Sequence Alignment problem" }, { "code": null, "e": 28971, "s": 28941, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 29031, "s": 28971, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 29046, "s": 29031, "text": "C++ Data Types" }, { "code": null, "e": 29089, "s": 29046, "text": "Set in C++ Standard Template Library (STL)" } ]
Fill between two vertical lines in matplotlib
To fill color between two vertical lines, use the following steps − Using plt.subplots() method, create a figure and a set of subplots. This utility wrapper makes it convenient to create common layouts of subplots, including the enclosing figure object, in a single call. Using plt.subplots() method, create a figure and a set of subplots. This utility wrapper makes it convenient to create common layouts of subplots, including the enclosing figure object, in a single call. To draw two vertical lines, initialize x = 3 and x = 5. To draw two vertical lines, initialize x = 3 and x = 5. Using the created ax, axvspan would help to add vertical span(rectangle) across the axes.This rectangle spans from xmin to xmax horizontally, and, by default, the whole Y-axis vertically. Using the created ax, axvspan would help to add vertical span(rectangle) across the axes. This rectangle spans from xmin to xmax horizontally, and, by default, the whole Y-axis vertically. To show the figure, use the plt.show() method. To show the figure, use the plt.show() method. import matplotlib.pyplot as plt fig, ax = plt.subplots() line1 = 3 # vertical x = 3 line2 = 5 # vertical x = 5 ax.axvspan(line1, line2, alpha=.5, color='green') plt.show()
[ { "code": null, "e": 1130, "s": 1062, "text": "To fill color between two vertical lines, use the following steps −" }, { "code": null, "e": 1334, "s": 1130, "text": "Using plt.subplots() method, create a figure and a set of subplots. This utility wrapper makes it convenient to create common layouts of subplots, including the enclosing figure object, in a single call." }, { "code": null, "e": 1538, "s": 1334, "text": "Using plt.subplots() method, create a figure and a set of subplots. This utility wrapper makes it convenient to create common layouts of subplots, including the enclosing figure object, in a single call." }, { "code": null, "e": 1594, "s": 1538, "text": "To draw two vertical lines, initialize x = 3 and x = 5." }, { "code": null, "e": 1650, "s": 1594, "text": "To draw two vertical lines, initialize x = 3 and x = 5." }, { "code": null, "e": 1838, "s": 1650, "text": "Using the created ax, axvspan would help to add vertical span(rectangle) across the axes.This rectangle spans from xmin to xmax horizontally, and, by default, the whole Y-axis vertically." }, { "code": null, "e": 1928, "s": 1838, "text": "Using the created ax, axvspan would help to add vertical span(rectangle) across the axes." }, { "code": null, "e": 2027, "s": 1928, "text": "This rectangle spans from xmin to xmax horizontally, and, by default, the whole Y-axis vertically." }, { "code": null, "e": 2074, "s": 2027, "text": "To show the figure, use the plt.show() method." }, { "code": null, "e": 2121, "s": 2074, "text": "To show the figure, use the plt.show() method." }, { "code": null, "e": 2297, "s": 2121, "text": "import matplotlib.pyplot as plt\n\nfig, ax = plt.subplots()\n\nline1 = 3 # vertical x = 3\nline2 = 5 # vertical x = 5\n\nax.axvspan(line1, line2, alpha=.5, color='green')\n\nplt.show()" } ]
The Python Debugger (pdb)
In software development jargon, 'debugging' term is popularly used to process of locating and rectifying errors in a program. Python's standard library contains pdb module which is a set of utilities for debugging of Python programs. The debugging functionality is defined in a Pdb class. The module internally makes used of bdb and cmd modules. The pdb module has a very convenient command line interface. It is imported at the time of execution of Python script by using –m switch python –m pdb script.py In order to find more about how the debugger works, let us first write a Python module (fact.py) as follows − def fact(x): f = 1 for i in range(1,x+1): print (i) f = f * i return f if __name__=="__main__": print ("factorial of 3=",fact(3)) Start debugging this module from command line. In this case the execution halts at first line in the code by showing arrow (->) to its left, and producing debugger prompt (Pdb) C:\python36>python -m pdb fact.py > c:\python36\fact.py(1)<module>() -> def fact(x): (Pdb) To see list of all debugger commands type 'help' in front of the debugger prompt. To know more about any command use 'help <command>' syntax. The list command lists entire code with -> symbol to the left of a line at which program has halted. (Pdb) list 1 -> def fact(x): 2 f = 1 3 for i in range(1,x+1): 4 print (i) 5 f = f * i 6 return f 7 if __name__=="__main__": 8 print ("factorial of 3 = ", fact(3)) To move through the program line by line use step or next command. (Pdb) step > c:\python36\fact.py(7)<module>() -> if __name__=="__main__": (Pdb) next > c:\python36\fact.py(8)<module>() -> print ("factorial of 3 = ", fact(3)) (Pdb) next 1 2 3 factorial of 3= 6 --Return-- > c:\python36\fact.py(8)<module>()->None -> print ("factorial of 3 = ", fact(3)) Major difference between step and next command is that step command will cause a program to stop within a function while next command executes a called function and stops after it. C:\python36>python -m pdb fact.py > c:\python36\fact.py(1)<module>() -> def fact(x): (Pdb) s > c:\python36\fact.py(7)<module>() -> if __name__=="__main__": (Pdb) n > c:\python36\fact.py(8)<module>() -> print ("factorial of 3=",fact(3)) (Pdb) s --Call-- > c:\python36\fact.py(1)fact() -> def fact(x): (Pdb) n > c:\python36\fact.py(2)fact() -> f = 1 (Pdb) n > c:\python36\fact.py(3)fact() -> for i in range(1,x+1): (Pdb) n > c:\python36\fact.py(4)fact() -> print (i) (Pdb) n 1 > c:\python36\fact.py(5)fact() -> f = f * i (Pdb) n > c:\python36\fact.py(3)fact() -> for i in range(1, x + 1): (Pdb) n > c:\python36\fact.py(4)fact() -> print (i) (Pdb) f,i (1, 2) (Pdb) The step command also shows --call—indication when a program encounters a call to function and --return--- when a function is over. At any point of time, we can check the value of a certain variable by just entering its name. You can set breakpoints within a program by break command. The line number (at which breakpoint should be set)must be given. For example 'break 5' will set a breakpoint at line 5 of a current program. (Pdb) list 2 f = 1 3 for i in range(1, x + 1): 4 print (i) 5 f = f * i 6 return f 7 -> if __name__=="__main__": 8 print ("factorial of 3=",fact(3)) [EOF] (Pdb) break 5 Breakpoint 1 at c:\python36\fact.py:5 (Pdb) continue 1 > c:\python36\fact.py(5)fact() -> f = f * i (Pdb) break Num Type Disp Enb Where 1 breakpoint keep yes at c:\python36\fact.py:5 breakpoint already hit 1 time (Pdb) continue 2 > c:\python36\fact.py(5)fact() -> f = f * i (Pdb) b Num Type Disp Enb Where 1 breakpoint keep yes at c:\python36\fact.py:5 breakpoint already hit 2 times When 'continue' command is issued, program execution will proceed till it encounters a breakpoint. To display all breakpoints, simple issue break command without a line number. Any breakpoint can be disabled/enabled by disable/enable command or cleared altogether by clear command. (Pdb) disable 1 Disabled breakpoint 1 at c:\python36\fact.py:5 (Pdb) b Num Type Disp Enb Where 1 breakpoint keep no at c:\python36\fact.py:5 breakpoint already hit 2 times The Pdb debugger can be used from within Python script also. To do so, import pdb at the top of the script and use set_trace() method inside the program. import pdb def fact(x): f = 1 for i in range(1,x+1): pdb.set_trace() print (i) f = f * i return f if __name__=="__main__": print ("factorial of 3=",fact(3)) The behavior of the debugger will be exactly the same as we find it in a command line environment.
[ { "code": null, "e": 1296, "s": 1062, "text": "In software development jargon, 'debugging' term is popularly used to process of locating and rectifying errors in a program. Python's standard library contains pdb module which is a set of utilities for debugging of Python programs." }, { "code": null, "e": 1408, "s": 1296, "text": "The debugging functionality is defined in a Pdb class. The module internally makes used of bdb and cmd modules." }, { "code": null, "e": 1545, "s": 1408, "text": "The pdb module has a very convenient command line interface. It is imported at the time of execution of Python script by using –m switch" }, { "code": null, "e": 1569, "s": 1545, "text": "python –m pdb script.py" }, { "code": null, "e": 1679, "s": 1569, "text": "In order to find more about how the debugger works, let us first write a Python module (fact.py) as follows −" }, { "code": null, "e": 1833, "s": 1679, "text": "def fact(x):\n f = 1\n for i in range(1,x+1):\n print (i)\n f = f * i\n return f\nif __name__==\"__main__\":\n print (\"factorial of 3=\",fact(3))" }, { "code": null, "e": 2010, "s": 1833, "text": "Start debugging this module from command line. In this case the execution halts at first line in the code by showing arrow (->) to its left, and producing debugger prompt (Pdb)" }, { "code": null, "e": 2101, "s": 2010, "text": "C:\\python36>python -m pdb fact.py\n> c:\\python36\\fact.py(1)<module>()\n-> def fact(x):\n(Pdb)" }, { "code": null, "e": 2243, "s": 2101, "text": "To see list of all debugger commands type 'help' in front of the debugger prompt. To know more about any command use 'help <command>' syntax." }, { "code": null, "e": 2344, "s": 2243, "text": "The list command lists entire code with -> symbol to the left of a line at which program has halted." }, { "code": null, "e": 2513, "s": 2344, "text": "(Pdb) list\n1 -> def fact(x):\n2 f = 1\n3 for i in range(1,x+1):\n4 print (i)\n5 f = f * i\n6 return f\n7 if __name__==\"__main__\":\n8 print (\"factorial of 3 = \", fact(3))" }, { "code": null, "e": 2580, "s": 2513, "text": "To move through the program line by line use step or next command." }, { "code": null, "e": 2867, "s": 2580, "text": "(Pdb) step\n> c:\\python36\\fact.py(7)<module>()\n-> if __name__==\"__main__\":\n(Pdb) next\n> c:\\python36\\fact.py(8)<module>()\n-> print (\"factorial of 3 = \", fact(3))\n(Pdb) next\n1\n2\n3\nfactorial of 3= 6\n--Return--\n> c:\\python36\\fact.py(8)<module>()->None\n-> print (\"factorial of 3 = \", fact(3))" }, { "code": null, "e": 3048, "s": 2867, "text": "Major difference between step and next command is that step command will cause a program to stop within a function while next command executes a called function and stops after it." }, { "code": null, "e": 3710, "s": 3048, "text": "C:\\python36>python -m pdb fact.py\n> c:\\python36\\fact.py(1)<module>()\n-> def fact(x):\n(Pdb) s\n> c:\\python36\\fact.py(7)<module>()\n-> if __name__==\"__main__\":\n(Pdb) n\n> c:\\python36\\fact.py(8)<module>()\n-> print (\"factorial of 3=\",fact(3))\n(Pdb) s\n--Call--\n> c:\\python36\\fact.py(1)fact()\n-> def fact(x):\n(Pdb) n\n> c:\\python36\\fact.py(2)fact()\n-> f = 1\n(Pdb) n\n> c:\\python36\\fact.py(3)fact()\n-> for i in range(1,x+1):\n(Pdb) n\n> c:\\python36\\fact.py(4)fact()\n-> print (i)\n(Pdb) n\n1\n> c:\\python36\\fact.py(5)fact()\n-> f = f * i\n(Pdb) n\n> c:\\python36\\fact.py(3)fact()\n-> for i in range(1, x + 1):\n(Pdb) n\n> c:\\python36\\fact.py(4)fact()\n-> print (i)\n(Pdb) f,i\n(1, 2)\n(Pdb)" }, { "code": null, "e": 3936, "s": 3710, "text": "The step command also shows --call—indication when a program encounters a call to function and --return--- when a function is over. At any point of time, we can check the value of a certain variable by just entering its name." }, { "code": null, "e": 4137, "s": 3936, "text": "You can set breakpoints within a program by break command. The line number (at which breakpoint should be set)must be given. For example 'break 5' will set a breakpoint at line 5 of a current program." }, { "code": null, "e": 4688, "s": 4137, "text": "(Pdb) list\n2 f = 1\n3 for i in range(1, x + 1):\n4 print (i)\n5 f = f * i\n6 return f\n7 -> if __name__==\"__main__\":\n8 print (\"factorial of 3=\",fact(3))\n[EOF]\n(Pdb) break 5\nBreakpoint 1 at c:\\python36\\fact.py:5\n(Pdb) continue\n1\n> c:\\python36\\fact.py(5)fact()\n-> f = f * i\n(Pdb) break\nNum Type Disp Enb Where\n1 breakpoint keep yes at c:\\python36\\fact.py:5\nbreakpoint already hit 1 time\n(Pdb) continue\n2\n> c:\\python36\\fact.py(5)fact()\n-> f = f * i\n(Pdb) b\nNum Type Disp Enb Where\n1 breakpoint keep yes at c:\\python36\\fact.py:5\nbreakpoint already hit 2 times" }, { "code": null, "e": 4865, "s": 4688, "text": "When 'continue' command is issued, program execution will proceed till it encounters a breakpoint. To display all breakpoints, simple issue break command without a line number." }, { "code": null, "e": 4970, "s": 4865, "text": "Any breakpoint can be disabled/enabled by disable/enable command or cleared altogether by clear command." }, { "code": null, "e": 5142, "s": 4970, "text": "(Pdb) disable 1\nDisabled breakpoint 1 at c:\\python36\\fact.py:5\n(Pdb) b\nNum Type Disp Enb Where\n1 breakpoint keep no at c:\\python36\\fact.py:5\nbreakpoint already hit 2 times" }, { "code": null, "e": 5296, "s": 5142, "text": "The Pdb debugger can be used from within Python script also. To do so, import pdb at the top of the script and use set_trace() method inside the program." }, { "code": null, "e": 5453, "s": 5296, "text": "import pdb\ndef fact(x):\nf = 1\nfor i in range(1,x+1):\npdb.set_trace()\nprint (i)\nf = f * i\nreturn f\nif __name__==\"__main__\":\nprint (\"factorial of 3=\",fact(3))" }, { "code": null, "e": 5552, "s": 5453, "text": "The behavior of the debugger will be exactly the same as we find it in a command line environment." } ]
C++ program to append content of one text file to another
This is a C++ program to append the content of one text file to another. a.txt file contains “Tutorials” a1.txt file contains “point” Tutorialspoint Begin Define a fstream class object as fin. Open a input file a.txt with input file stream class object fin. Open a output file a1.txt with output file stream class object fout in append mode. Check if the file is not existing then Print “File not found”. Else append content from fin to fout. Open the destination file in read mode. Display its content as output. End. Live Demo #include <bits/stdc++.h> #include<fstream> using namespace std; int main() { fstream f; ifstream fin; fin.open("a.txt"); ofstream fout; fout.open("a1.txt", ios::app); if (!fin.is_open()) { cout << "Tutorialspoint"; } else { fout << fin.rdbuf(); } string word; f.open("a1.txt"); while (f >> word) { cout << word << " "; } return 0; } Tutorialspoint
[ { "code": null, "e": 1135, "s": 1062, "text": "This is a C++ program to append the content of one text file to another." }, { "code": null, "e": 1196, "s": 1135, "text": "a.txt file contains “Tutorials”\na1.txt file contains “point”" }, { "code": null, "e": 1211, "s": 1196, "text": "Tutorialspoint" }, { "code": null, "e": 1612, "s": 1211, "text": "Begin\n Define a fstream class object as fin.\n Open a input file a.txt with input file stream class object fin.\n Open a output file a1.txt with output file stream class object fout\n in append mode.\n Check if the file is not existing then\n Print “File not found”.\n Else append content from fin to fout.\n Open the destination file in read mode.\n Display its content as output. \nEnd." }, { "code": null, "e": 1623, "s": 1612, "text": " Live Demo" }, { "code": null, "e": 2022, "s": 1623, "text": "#include <bits/stdc++.h>\n#include<fstream>\nusing namespace std;\nint main() {\n fstream f;\n ifstream fin;\n fin.open(\"a.txt\");\n ofstream fout;\n fout.open(\"a1.txt\", ios::app);\n if (!fin.is_open()) {\n cout << \"Tutorialspoint\";\n } else {\n fout << fin.rdbuf();\n }\n string word;\n f.open(\"a1.txt\");\n while (f >> word) {\n cout << word << \" \";\n }\n return 0;\n}" }, { "code": null, "e": 2037, "s": 2022, "text": "Tutorialspoint" } ]
How to use enums in C/C++?
Enumeration is a user defined datatype in C language. It is used to assign names to the integral constants, which makes a program easy to read and maintain. The keyword “enum” is used to declare an enumeration. Here is the syntax of enum in C language, enum enum_name{const1, const2, ....... }; The enum keyword is also used to define the variables of enum type. There are two ways to define the variables of enum type as follows. enum week{sunday, monday, tuesday, wednesday, thursday, friday, saturday}; enum week day; Here is an example of enum in C language, #include<stdio.h> enum week{Mon=10, Tue, Wed, Thur, Fri=10, Sat=16, Sun}; enum day{Mond, Tues, Wedn, Thurs, Frid=18, Satu=11, Sund}; int main() { printf("The value of enum week: %d\t%d\t%d\t%d\t%d\t%d\t%d\n\n",Mon , Tue, Wed, Thur, Fri, Sat, Sun); printf("The default value of enum day: %d\t%d\t%d\t%d\t%d\t%d\t%d",Mond , Tues, Wedn, Thurs, Frid, Satu, Sund); return 0; } The value of enum week: 10111213101617 The default value of enum day: 0123181112
[ { "code": null, "e": 1273, "s": 1062, "text": "Enumeration is a user defined datatype in C language. It is used to assign names to the integral constants, which makes a program easy to read and maintain. The keyword “enum” is used to declare an enumeration." }, { "code": null, "e": 1315, "s": 1273, "text": "Here is the syntax of enum in C language," }, { "code": null, "e": 1357, "s": 1315, "text": "enum enum_name{const1, const2, ....... };" }, { "code": null, "e": 1493, "s": 1357, "text": "The enum keyword is also used to define the variables of enum type. There are two ways to define the variables of enum type as follows." }, { "code": null, "e": 1583, "s": 1493, "text": "enum week{sunday, monday, tuesday, wednesday, thursday, friday, saturday};\nenum week day;" }, { "code": null, "e": 1625, "s": 1583, "text": "Here is an example of enum in C language," }, { "code": null, "e": 2012, "s": 1625, "text": "#include<stdio.h>\nenum week{Mon=10, Tue, Wed, Thur, Fri=10, Sat=16, Sun};\nenum day{Mond, Tues, Wedn, Thurs, Frid=18, Satu=11, Sund};\nint main() {\n printf(\"The value of enum week: %d\\t%d\\t%d\\t%d\\t%d\\t%d\\t%d\\n\\n\",Mon , Tue, Wed, Thur, Fri, Sat, Sun);\n printf(\"The default value of enum day: %d\\t%d\\t%d\\t%d\\t%d\\t%d\\t%d\",Mond , Tues, Wedn, Thurs, Frid, Satu, Sund);\n return 0;\n}" }, { "code": null, "e": 2093, "s": 2012, "text": "The value of enum week: 10111213101617\nThe default value of enum day: 0123181112" } ]
Split numeric, alphabetic and special symbols from a String - GeeksforGeeks
16 Jun, 2021 Given string str, divide the string into three parts one containing a numeric part, one containing alphabetic, and one containing special characters. Examples: Input : geeks01for02geeks03!!! Output :geeksforgeeks 010203 !!! Here str = "Geeks01for02Geeks03!!!", we scan every character and append in res1, res2 and res3 string accordingly. Input : **Docoding123456789everyday## Output :Docodingeveryday 123456789 **## Steps : Calculate the length of the string.Scan every character(ch) of a string one by oneif (ch is a digit) then append it in res1 string.else if (ch is alphabet) append in string res2.else append in string res3.Print all the strings, we will have one string containing a numeric part, other non-numeric part, and the last one contains special characters. Calculate the length of the string. Scan every character(ch) of a string one by oneif (ch is a digit) then append it in res1 string.else if (ch is alphabet) append in string res2.else append in string res3. if (ch is a digit) then append it in res1 string. else if (ch is alphabet) append in string res2. else append in string res3. Print all the strings, we will have one string containing a numeric part, other non-numeric part, and the last one contains special characters. C++ Java Python3 C# Javascript // CPP program to split an alphanumeric// string using STL#include<bits/stdc++.h>using namespace std; void splitString(string str){ string alpha, num, special; for (int i=0; i<str.length(); i++) { if (isdigit(str[i])) num.push_back(str[i]); else if((str[i] >= 'A' && str[i] <= 'Z') || (str[i] >= 'a' && str[i] <= 'z')) alpha.push_back(str[i]); else special.push_back(str[i]); } cout << alpha << endl; cout << num << endl; cout << special << endl;} // Driver codeint main(){ string str = "geeks01$$for02geeks03!@!!"; splitString(str); return 0;} // java program to split an alphanumeric// string using stringbuffer class Test{ static void splitString(String str) { StringBuffer alpha = new StringBuffer(), num = new StringBuffer(), special = new StringBuffer(); for (int i=0; i<str.length(); i++) { if (Character.isDigit(str.charAt(i))) num.append(str.charAt(i)); else if(Character.isAlphabetic(str.charAt(i))) alpha.append(str.charAt(i)); else special.append(str.charAt(i)); } System.out.println(alpha); System.out.println(num); System.out.println(special); } // Driver method public static void main(String args[]) { String str = "geeks01$$for02geeks03!@!!"; splitString(str); }} # Python 3 program to split an alphanumeric# string using STLdef splitString(str): alpha = "" num = "" special = "" for i in range(len(str)): if (str[i].isdigit()): num = num+ str[i] elif((str[i] >= 'A' and str[i] <= 'Z') or (str[i] >= 'a' and str[i] <= 'z')): alpha += str[i] else: special += str[i] print(alpha) print(num ) print(special) # Driver codeif __name__ == "__main__": str = "geeks01$$for02geeks03!@!!" splitString(str) # This code is contributed by ita_c // C# program to split an alphanumeric// string using stringbufferusing System;using System.Text; class GFG { // Function ot split string static void splitString(string str) { StringBuilder alpha = new StringBuilder(); StringBuilder num = new StringBuilder(); StringBuilder special = new StringBuilder(); for (int i = 0; i < str.Length; i++) { if (Char.IsDigit(str[i])) num.Append(str[i]); else if((str[i] >= 'A' && str[i] <= 'Z') || (str[i] >= 'a' && str[i] <= 'z')) alpha.Append(str[i]); else special.Append(str[i]); } Console.WriteLine(alpha); Console.WriteLine(num); Console.WriteLine(special); } // Driver code public static void Main() { string str = "geeks01$$for02geeks03!@!!"; splitString(str); }} // This code is contributed by Sam007 <script>// Javascript program to split an alphanumeric// string using stringbuffer function splitString(str) { let alpha = ""; let num = ""; let special = ""; for (let i=0; i<str.length; i++) { if (!isNaN(String(str[i]) * 1)) num+=str[i]; else if((str[i] >= 'A' && str[i] <= 'Z') || (str[i] >= 'a' && str[i] <= 'z')) alpha+=str[i]; else special+=str[i]; } document.write(alpha+"<br>"); document.write(num+"<br>"); document.write(special+"<br>"); } // Driver method let str = "geeks01$$for02geeks03!@!!"; splitString(str); // This code is contributed by avanitrachhadiya2155</script> Output: geeksforgeeks 010203 $$!@!! The time complexity of the above solution is O(n) where n is the length of the string. Sam007 ukasp Akanksha_Rai avanitrachhadiya2155 bunnyram19 C++ School Programming Strings Strings CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Constructors in C++ Socket Programming in C/C++ Operator Overloading in C++ Multidimensional Arrays in C / C++ Copy Constructor in C++ Python Dictionary Reverse a string in Java Constructors in C++ Interfaces in Java Operator Overloading in C++
[ { "code": null, "e": 24655, "s": 24627, "text": "\n16 Jun, 2021" }, { "code": null, "e": 24806, "s": 24655, "text": "Given string str, divide the string into three parts one containing a numeric part, one containing alphabetic, and one containing special characters. " }, { "code": null, "e": 24817, "s": 24806, "text": "Examples: " }, { "code": null, "e": 25108, "s": 24817, "text": "Input : geeks01for02geeks03!!!\nOutput :geeksforgeeks\n 010203\n !!!\nHere str = \"Geeks01for02Geeks03!!!\", we scan every character and \nappend in res1, res2 and res3 string accordingly.\n\nInput : **Docoding123456789everyday##\nOutput :Docodingeveryday\n 123456789\n **##" }, { "code": null, "e": 25117, "s": 25108, "text": "Steps : " }, { "code": null, "e": 25466, "s": 25117, "text": "Calculate the length of the string.Scan every character(ch) of a string one by oneif (ch is a digit) then append it in res1 string.else if (ch is alphabet) append in string res2.else append in string res3.Print all the strings, we will have one string containing a numeric part, other non-numeric part, and the last one contains special characters." }, { "code": null, "e": 25502, "s": 25466, "text": "Calculate the length of the string." }, { "code": null, "e": 25673, "s": 25502, "text": "Scan every character(ch) of a string one by oneif (ch is a digit) then append it in res1 string.else if (ch is alphabet) append in string res2.else append in string res3." }, { "code": null, "e": 25723, "s": 25673, "text": "if (ch is a digit) then append it in res1 string." }, { "code": null, "e": 25771, "s": 25723, "text": "else if (ch is alphabet) append in string res2." }, { "code": null, "e": 25799, "s": 25771, "text": "else append in string res3." }, { "code": null, "e": 25943, "s": 25799, "text": "Print all the strings, we will have one string containing a numeric part, other non-numeric part, and the last one contains special characters." }, { "code": null, "e": 25947, "s": 25943, "text": "C++" }, { "code": null, "e": 25952, "s": 25947, "text": "Java" }, { "code": null, "e": 25960, "s": 25952, "text": "Python3" }, { "code": null, "e": 25963, "s": 25960, "text": "C#" }, { "code": null, "e": 25974, "s": 25963, "text": "Javascript" }, { "code": "// CPP program to split an alphanumeric// string using STL#include<bits/stdc++.h>using namespace std; void splitString(string str){ string alpha, num, special; for (int i=0; i<str.length(); i++) { if (isdigit(str[i])) num.push_back(str[i]); else if((str[i] >= 'A' && str[i] <= 'Z') || (str[i] >= 'a' && str[i] <= 'z')) alpha.push_back(str[i]); else special.push_back(str[i]); } cout << alpha << endl; cout << num << endl; cout << special << endl;} // Driver codeint main(){ string str = \"geeks01$$for02geeks03!@!!\"; splitString(str); return 0;}", "e": 26619, "s": 25974, "text": null }, { "code": "// java program to split an alphanumeric// string using stringbuffer class Test{ static void splitString(String str) { StringBuffer alpha = new StringBuffer(), num = new StringBuffer(), special = new StringBuffer(); for (int i=0; i<str.length(); i++) { if (Character.isDigit(str.charAt(i))) num.append(str.charAt(i)); else if(Character.isAlphabetic(str.charAt(i))) alpha.append(str.charAt(i)); else special.append(str.charAt(i)); } System.out.println(alpha); System.out.println(num); System.out.println(special); } // Driver method public static void main(String args[]) { String str = \"geeks01$$for02geeks03!@!!\"; splitString(str); }}", "e": 27444, "s": 26619, "text": null }, { "code": "# Python 3 program to split an alphanumeric# string using STLdef splitString(str): alpha = \"\" num = \"\" special = \"\" for i in range(len(str)): if (str[i].isdigit()): num = num+ str[i] elif((str[i] >= 'A' and str[i] <= 'Z') or (str[i] >= 'a' and str[i] <= 'z')): alpha += str[i] else: special += str[i] print(alpha) print(num ) print(special) # Driver codeif __name__ == \"__main__\": str = \"geeks01$$for02geeks03!@!!\" splitString(str) # This code is contributed by ita_c", "e": 28012, "s": 27444, "text": null }, { "code": "// C# program to split an alphanumeric// string using stringbufferusing System;using System.Text; class GFG { // Function ot split string static void splitString(string str) { StringBuilder alpha = new StringBuilder(); StringBuilder num = new StringBuilder(); StringBuilder special = new StringBuilder(); for (int i = 0; i < str.Length; i++) { if (Char.IsDigit(str[i])) num.Append(str[i]); else if((str[i] >= 'A' && str[i] <= 'Z') || (str[i] >= 'a' && str[i] <= 'z')) alpha.Append(str[i]); else special.Append(str[i]); } Console.WriteLine(alpha); Console.WriteLine(num); Console.WriteLine(special); } // Driver code public static void Main() { string str = \"geeks01$$for02geeks03!@!!\"; splitString(str); }} // This code is contributed by Sam007", "e": 29066, "s": 28012, "text": null }, { "code": "<script>// Javascript program to split an alphanumeric// string using stringbuffer function splitString(str) { let alpha = \"\"; let num = \"\"; let special = \"\"; for (let i=0; i<str.length; i++) { if (!isNaN(String(str[i]) * 1)) num+=str[i]; else if((str[i] >= 'A' && str[i] <= 'Z') || (str[i] >= 'a' && str[i] <= 'z')) alpha+=str[i]; else special+=str[i]; } document.write(alpha+\"<br>\"); document.write(num+\"<br>\"); document.write(special+\"<br>\"); } // Driver method let str = \"geeks01$$for02geeks03!@!!\"; splitString(str); // This code is contributed by avanitrachhadiya2155</script>", "e": 29849, "s": 29066, "text": null }, { "code": null, "e": 29858, "s": 29849, "text": "Output: " }, { "code": null, "e": 29886, "s": 29858, "text": "geeksforgeeks\n010203\n$$!@!!" }, { "code": null, "e": 29974, "s": 29886, "text": "The time complexity of the above solution is O(n) where n is the length of the string. " }, { "code": null, "e": 29981, "s": 29974, "text": "Sam007" }, { "code": null, "e": 29987, "s": 29981, "text": "ukasp" }, { "code": null, "e": 30000, "s": 29987, "text": "Akanksha_Rai" }, { "code": null, "e": 30021, "s": 30000, "text": "avanitrachhadiya2155" }, { "code": null, "e": 30032, "s": 30021, "text": "bunnyram19" }, { "code": null, "e": 30036, "s": 30032, "text": "C++" }, { "code": null, "e": 30055, "s": 30036, "text": "School Programming" }, { "code": null, "e": 30063, "s": 30055, "text": "Strings" }, { "code": null, "e": 30071, "s": 30063, "text": "Strings" }, { "code": null, "e": 30075, "s": 30071, "text": "CPP" }, { "code": null, "e": 30173, "s": 30075, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30182, "s": 30173, "text": "Comments" }, { "code": null, "e": 30195, "s": 30182, "text": "Old Comments" }, { "code": null, "e": 30215, "s": 30195, "text": "Constructors in C++" }, { "code": null, "e": 30243, "s": 30215, "text": "Socket Programming in C/C++" }, { "code": null, "e": 30271, "s": 30243, "text": "Operator Overloading in C++" }, { "code": null, "e": 30306, "s": 30271, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 30330, "s": 30306, "text": "Copy Constructor in C++" }, { "code": null, "e": 30348, "s": 30330, "text": "Python Dictionary" }, { "code": null, "e": 30373, "s": 30348, "text": "Reverse a string in Java" }, { "code": null, "e": 30393, "s": 30373, "text": "Constructors in C++" }, { "code": null, "e": 30412, "s": 30393, "text": "Interfaces in Java" } ]
ES6 - Number.MAX_VALUE
The Number.MAX_VALUE property belongs to the static Number object. It represents constants for the largest possible positive numbers that JavaScript can work with. The actual value of this constant is 1.7976931348623157 x 10308 var val = Number.MAX_VALUE; var val = Number.MAX_VALUE; console.log("Value of Number.MAX_VALUE : " + val ); Value of Number.MAX_VALUE : 1.7976931348623157e+308 32 Lectures 3.5 hours Sharad Kumar 40 Lectures 5 hours Richa Maheshwari 16 Lectures 1 hours Anadi Sharma 50 Lectures 6.5 hours Gowthami Swarna 14 Lectures 1 hours Deepti Trivedi 31 Lectures 1.5 hours Shweta Print Add Notes Bookmark this page
[ { "code": null, "e": 2441, "s": 2277, "text": "The Number.MAX_VALUE property belongs to the static Number object. It represents constants for the largest possible positive numbers that JavaScript can work with." }, { "code": null, "e": 2505, "s": 2441, "text": "The actual value of this constant is 1.7976931348623157 x 10308" }, { "code": null, "e": 2534, "s": 2505, "text": "var val = Number.MAX_VALUE;\n" }, { "code": null, "e": 2614, "s": 2534, "text": "var val = Number.MAX_VALUE;\nconsole.log(\"Value of Number.MAX_VALUE : \" + val );" }, { "code": null, "e": 2667, "s": 2614, "text": "Value of Number.MAX_VALUE : 1.7976931348623157e+308\n" }, { "code": null, "e": 2702, "s": 2667, "text": "\n 32 Lectures \n 3.5 hours \n" }, { "code": null, "e": 2716, "s": 2702, "text": " Sharad Kumar" }, { "code": null, "e": 2749, "s": 2716, "text": "\n 40 Lectures \n 5 hours \n" }, { "code": null, "e": 2767, "s": 2749, "text": " Richa Maheshwari" }, { "code": null, "e": 2800, "s": 2767, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 2814, "s": 2800, "text": " Anadi Sharma" }, { "code": null, "e": 2849, "s": 2814, "text": "\n 50 Lectures \n 6.5 hours \n" }, { "code": null, "e": 2866, "s": 2849, "text": " Gowthami Swarna" }, { "code": null, "e": 2899, "s": 2866, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 2915, "s": 2899, "text": " Deepti Trivedi" }, { "code": null, "e": 2950, "s": 2915, "text": "\n 31 Lectures \n 1.5 hours \n" }, { "code": null, "e": 2958, "s": 2950, "text": " Shweta" }, { "code": null, "e": 2965, "s": 2958, "text": " Print" }, { "code": null, "e": 2976, "s": 2965, "text": " Add Notes" } ]
How to Run Synchronous Queries using sync-sql Module in Node.js ?
28 Apr, 2020 The sync-sql module is designed to make synchronous queries to the database. Since normal SQL queries are asynchronous in node.js but if you want to run it synchronously, then it is possible using this module. In synchronized SQL, the result set is returned when the query is executed. Note: Do not use this module in production mode as node.js is designed to be asynchronous. Installation of sync-sql module: You can visit the link Install sync-sql module. You can install this package by using this command.npm install sync-sqlAfter installing sync-sql you can check your sync-sql version in command prompt using the command.npm version sync-sqlAfter that, you can just create a folder and add a file for example index.js, To run this file you need to run the following command.node index.jsNow open MySQL and create a database for example ‘demo’. You can visit the link Install sync-sql module. You can install this package by using this command.npm install sync-sql npm install sync-sql After installing sync-sql you can check your sync-sql version in command prompt using the command.npm version sync-sql npm version sync-sql After that, you can just create a folder and add a file for example index.js, To run this file you need to run the following command.node index.js node index.js Now open MySQL and create a database for example ‘demo’. Filename: index.js const Mysql = require('sync-mysql') const connection = new Mysql({ host:'localhost', user:'root', password:'password', database:'demo'}) var result = connection.query('SELECT NOW()')console.log(result) Steps to run the program: The project structure will look like this:Make sure you install sync-sql using following commands:npm install sync-sqlRun index.js file using below command:node index.js The project structure will look like this: Make sure you install sync-sql using following commands:npm install sync-sql npm install sync-sql Run index.js file using below command:node index.js node index.js So this is how you can run synchronized SQL queries in node js using sync-sql package. Node.js-Misc Node.js Web Technologies Web technologies Questions Write From Home Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between promise and async await in Node.js Mongoose | findByIdAndUpdate() Function Installation of Node.js on Windows JWT Authentication with Node.js How to use an ES6 import in Node.js? Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React
[ { "code": null, "e": 54, "s": 26, "text": "\n28 Apr, 2020" }, { "code": null, "e": 340, "s": 54, "text": "The sync-sql module is designed to make synchronous queries to the database. Since normal SQL queries are asynchronous in node.js but if you want to run it synchronously, then it is possible using this module. In synchronized SQL, the result set is returned when the query is executed." }, { "code": null, "e": 431, "s": 340, "text": "Note: Do not use this module in production mode as node.js is designed to be asynchronous." }, { "code": null, "e": 464, "s": 431, "text": "Installation of sync-sql module:" }, { "code": null, "e": 904, "s": 464, "text": "You can visit the link Install sync-sql module. You can install this package by using this command.npm install sync-sqlAfter installing sync-sql you can check your sync-sql version in command prompt using the command.npm version sync-sqlAfter that, you can just create a folder and add a file for example index.js, To run this file you need to run the following command.node index.jsNow open MySQL and create a database for example ‘demo’." }, { "code": null, "e": 1024, "s": 904, "text": "You can visit the link Install sync-sql module. You can install this package by using this command.npm install sync-sql" }, { "code": null, "e": 1045, "s": 1024, "text": "npm install sync-sql" }, { "code": null, "e": 1164, "s": 1045, "text": "After installing sync-sql you can check your sync-sql version in command prompt using the command.npm version sync-sql" }, { "code": null, "e": 1185, "s": 1164, "text": "npm version sync-sql" }, { "code": null, "e": 1332, "s": 1185, "text": "After that, you can just create a folder and add a file for example index.js, To run this file you need to run the following command.node index.js" }, { "code": null, "e": 1346, "s": 1332, "text": "node index.js" }, { "code": null, "e": 1403, "s": 1346, "text": "Now open MySQL and create a database for example ‘demo’." }, { "code": null, "e": 1422, "s": 1403, "text": "Filename: index.js" }, { "code": "const Mysql = require('sync-mysql') const connection = new Mysql({ host:'localhost', user:'root', password:'password', database:'demo'}) var result = connection.query('SELECT NOW()')console.log(result)", "e": 1638, "s": 1422, "text": null }, { "code": null, "e": 1664, "s": 1638, "text": "Steps to run the program:" }, { "code": null, "e": 1834, "s": 1664, "text": "The project structure will look like this:Make sure you install sync-sql using following commands:npm install sync-sqlRun index.js file using below command:node index.js" }, { "code": null, "e": 1877, "s": 1834, "text": "The project structure will look like this:" }, { "code": null, "e": 1954, "s": 1877, "text": "Make sure you install sync-sql using following commands:npm install sync-sql" }, { "code": null, "e": 1975, "s": 1954, "text": "npm install sync-sql" }, { "code": null, "e": 2027, "s": 1975, "text": "Run index.js file using below command:node index.js" }, { "code": null, "e": 2041, "s": 2027, "text": "node index.js" }, { "code": null, "e": 2128, "s": 2041, "text": "So this is how you can run synchronized SQL queries in node js using sync-sql package." }, { "code": null, "e": 2141, "s": 2128, "text": "Node.js-Misc" }, { "code": null, "e": 2149, "s": 2141, "text": "Node.js" }, { "code": null, "e": 2166, "s": 2149, "text": "Web Technologies" }, { "code": null, "e": 2193, "s": 2166, "text": "Web technologies Questions" }, { "code": null, "e": 2209, "s": 2193, "text": "Write From Home" }, { "code": null, "e": 2307, "s": 2209, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2361, "s": 2307, "text": "Difference between promise and async await in Node.js" }, { "code": null, "e": 2401, "s": 2361, "text": "Mongoose | findByIdAndUpdate() Function" }, { "code": null, "e": 2436, "s": 2401, "text": "Installation of Node.js on Windows" }, { "code": null, "e": 2468, "s": 2436, "text": "JWT Authentication with Node.js" }, { "code": null, "e": 2505, "s": 2468, "text": "How to use an ES6 import in Node.js?" }, { "code": null, "e": 2567, "s": 2505, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2628, "s": 2567, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2678, "s": 2628, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 2721, "s": 2678, "text": "How to fetch data from an API in ReactJS ?" } ]
R – Stem and Leaf Plots
30 Jun, 2020 Stem and Leaf plot is a technique of displaying the frequencies with which some classes of values may occur. It is basically a method of representing the quantitative data in the graphical format. The stem and leaf plot retains the original data item up to two significant figures unlike histogram. The data is put in order which eases the move to no parametric statistics and order-based inference. Let us understand how this plotting technique works. Example: On World’s Obesity Day, suppose in a school a teacher decided to measure the weight of any 10 students whom she feels may have obesity. So she records the weight of 10 students as follows: 54, 43, 67, 76, 45, 59, 66, 78, 80, 92. Now the stem and leaf plot on these records will be: 4 | 3 5 5 | 4 9 6 | 6 7 7 | 6 8 8 | 0 9 | 2 Here the records are arranged based on their most significant digit. The stem is the left side of the chart while the right side is the leaf. In order to increase readability sometimes, the alternate rows can be merged with it’s immediate next row. In case of infinite values or missing values of the number, they are discarded. In R, stem and leaf plots(also known as stem and leaf diagrams) of any quantitative variable, say x, is a textual graph that is used to classify the data items in order of their most significant numeric digits. The term stem and leaf is so because the plot is given in a tabular format where each numeric value or data item is split into a stem i.e. the first digit and a leaf i.e. the last digit. For example, suppose the input data is 94. Then 9 will be the stem and 4 will be the leaf. Syntax:stem(number, scale = 1, width = 80, atom = 1e-08) Parameters:number: the data on which we want to draw the stem and leaf plot [either a numeric vector or a list of numeric vectors]scale: the scale we want to use for our plotwidth: the desired width for our plot [it is 80 by default]atom: tolerance There are many reserved datasets in RStudio. Here let’s use the ChickWeight data set where considering the weight. At first let’s see how to use the stem and leaf plot in a simpler manner by using stem(). Example: # R program to illustrate# Stem and Leaf Plot # using stem()stem(ChickWeight$weight) Output: The decimal point is 1 digit(s) to the right of the | 2 | 599999999 4 | 00000111111111111111111112222222222222223333456678888888899999999999+38 6 | 00111111122222222333334444455555666677777888888900111111222222333334+8 8 | 00112223344444455555566777788999990001223333566666788888889 10 | 0000111122233333334566667778889901122223445555667789 12 | 00002223333344445555667788890113444555566788889 14 | 11123444455556666677788890011234444555666777777789 16 | 00002233334444466788990000134445555789 18 | 12244444555677782225677778889999 20 | 0123444555557900245578 22 | 0012357701123344556788 24 | 08001699 26 | 12344569259 28 | 01780145 30 | 355798 32 | 12712 34 | 1 36 | 13 Explanation: Here $ sign is used in the command to extract the data form the list used. The stem() command extracts the numeric data and splits them into two parts namely, the stem and leaf. The left side shows the most significant digit while the last digit is shown on the right hand side. For better readability the numbers having same stem value are merged together. Now let’s see the same stem and leaf plot after rescaling our desired plot. To rescale the plot we need to use the scale argument inside the stem() function. Example: # R program to illustrate# Stem and Leaf Plot # Drawing Stem and Leaf Plot after rescalingstem(ChickWeight$weight, scale = 5) Output: The decimal point is 1 digit(s) to the right of the | 3 | 599999999 4 | 000001111111111111111111122222222222222233334 4 | 5667888888889999999999999 5 | 00000011111111222233333444 5 | 5555566667778888899999 6 | 001111111222222223333344444 6 | 555556666777778888889 7 | 001111112222223333344444444 7 | 6667778889999 8 | 001122233444444 8 | 5555556677778899999 9 | 0001223333 9 | 566666788888889 10 | 0000111122233333334 10 | 5666677788899 11 | 0112222344 11 | 5555667789 12 | 0000222333334444 12 | 555566778889 13 | 0113444 13 | 555566788889 14 | 111234444 14 | 5555666667778889 15 | 0011234444 15 | 555666777777789 16 | 000022333344444 16 | 6678899 17 | 000013444 17 | 5555789 18 | 12244444 18 | 55567778 19 | 222 19 | 5677778889999 20 | 0123444 20 | 5555579 21 | 0024 21 | 5578 22 | 00123 22 | 577 23 | 01123344 23 | 556788 24 | 0 24 | 8 25 | 001 25 | 699 26 | 12344 26 | 569 27 | 2 27 | 59 28 | 01 28 | 78 29 | 014 29 | 5 30 | 3 30 | 5579 31 | 31 | 8 32 | 12 32 | 7 33 | 12 33 | 34 | 1 34 | 35 | 35 | 36 | 1 36 | 37 | 3 Explanation: After changing the scaling, the distribution of data has changed horizontally. Again here the stems are on the left side and the leaves are on the right side. On using width argument in the stem() function one can change the width of the plot into a desired plot. Example: # R program to illustrate# Stem and Leaf Plot # Drawing Stem and Leaf Plot by changing the widthstem(ChickWeight$weight, width = 100) Output: The decimal point is 1 digit(s) to the right of the | 2 | 599999999 4 | 0000011111111111111111111222222222222222333345667888888889999999999999000000111111112222+18 6 | 0011111112222222233333444445555566667777788888890011111122222233333444444446667778889999 8 | 00112223344444455555566777788999990001223333566666788888889 10 | 0000111122233333334566667778889901122223445555667789 12 | 00002223333344445555667788890113444555566788889 14 | 11123444455556666677788890011234444555666777777789 16 | 00002233334444466788990000134445555789 18 | 12244444555677782225677778889999 20 | 0123444555557900245578 22 | 0012357701123344556788 24 | 08001699 26 | 12344569259 28 | 01780145 30 | 355798 32 | 12712 34 | 1 36 | 13 Explanation: As the width is changed to 100 from 80, the distribution of data has also changed. Here the left side of the chart shows the stem while the leaves are on the right-hand side of the chart. The stem and leaf plot is very useful for displaying the shape and relative density of data, hence giving the reader or customer a quick overview of the kind of distribution. Most of the times they can retain the raw data with quite perfect integrity. A very useful method for highlighting the outliers and also for finding the mode. Picked R Machine-Learning R-plots 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 How to Split Column Into Multiple Columns in R DataFrame? Group by function in R using Dplyr How to Change Axis Scales in R Plots? How to filter R DataFrame by values in a column? Logistic Regression in R Programming R - if statement Replace Specific Characters in String in R How to import an Excel File into R ? Joining of Dataframes in R Programming
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Jun, 2020" }, { "code": null, "e": 481, "s": 28, "text": "Stem and Leaf plot is a technique of displaying the frequencies with which some classes of values may occur. It is basically a method of representing the quantitative data in the graphical format. The stem and leaf plot retains the original data item up to two significant figures unlike histogram. The data is put in order which eases the move to no parametric statistics and order-based inference. Let us understand how this plotting technique works." }, { "code": null, "e": 490, "s": 481, "text": "Example:" }, { "code": null, "e": 679, "s": 490, "text": "On World’s Obesity Day, suppose in a school a teacher decided to measure the weight of any 10 students whom she feels may have obesity. So she records the weight of 10 students as follows:" }, { "code": null, "e": 720, "s": 679, "text": "54, 43, 67, 76, 45, 59, 66, 78, 80, 92.\n" }, { "code": null, "e": 773, "s": 720, "text": "Now the stem and leaf plot on these records will be:" }, { "code": null, "e": 818, "s": 773, "text": "4 | 3 5\n5 | 4 9\n6 | 6 7\n7 | 6 8\n8 | 0\n9 | 2\n" }, { "code": null, "e": 1147, "s": 818, "text": "Here the records are arranged based on their most significant digit. The stem is the left side of the chart while the right side is the leaf. In order to increase readability sometimes, the alternate rows can be merged with it’s immediate next row. In case of infinite values or missing values of the number, they are discarded." }, { "code": null, "e": 1636, "s": 1147, "text": "In R, stem and leaf plots(also known as stem and leaf diagrams) of any quantitative variable, say x, is a textual graph that is used to classify the data items in order of their most significant numeric digits. The term stem and leaf is so because the plot is given in a tabular format where each numeric value or data item is split into a stem i.e. the first digit and a leaf i.e. the last digit. For example, suppose the input data is 94. Then 9 will be the stem and 4 will be the leaf." }, { "code": null, "e": 1693, "s": 1636, "text": "Syntax:stem(number, scale = 1, width = 80, atom = 1e-08)" }, { "code": null, "e": 1942, "s": 1693, "text": "Parameters:number: the data on which we want to draw the stem and leaf plot [either a numeric vector or a list of numeric vectors]scale: the scale we want to use for our plotwidth: the desired width for our plot [it is 80 by default]atom: tolerance" }, { "code": null, "e": 2147, "s": 1942, "text": "There are many reserved datasets in RStudio. Here let’s use the ChickWeight data set where considering the weight. At first let’s see how to use the stem and leaf plot in a simpler manner by using stem()." }, { "code": null, "e": 2156, "s": 2147, "text": "Example:" }, { "code": "# R program to illustrate# Stem and Leaf Plot # using stem()stem(ChickWeight$weight)", "e": 2242, "s": 2156, "text": null }, { "code": null, "e": 2250, "s": 2242, "text": "Output:" }, { "code": null, "e": 2964, "s": 2250, "text": "The decimal point is 1 digit(s) to the right of the |\n\n 2 | 599999999\n 4 | 00000111111111111111111112222222222222223333456678888888899999999999+38\n 6 | 00111111122222222333334444455555666677777888888900111111222222333334+8\n 8 | 00112223344444455555566777788999990001223333566666788888889\n 10 | 0000111122233333334566667778889901122223445555667789\n 12 | 00002223333344445555667788890113444555566788889\n 14 | 11123444455556666677788890011234444555666777777789\n 16 | 00002233334444466788990000134445555789\n 18 | 12244444555677782225677778889999\n 20 | 0123444555557900245578\n 22 | 0012357701123344556788\n 24 | 08001699\n 26 | 12344569259\n 28 | 01780145\n 30 | 355798\n 32 | 12712\n 34 | 1\n 36 | 13\n\n" }, { "code": null, "e": 2977, "s": 2964, "text": "Explanation:" }, { "code": null, "e": 3335, "s": 2977, "text": "Here $ sign is used in the command to extract the data form the list used. The stem() command extracts the numeric data and splits them into two parts namely, the stem and leaf. The left side shows the most significant digit while the last digit is shown on the right hand side. For better readability the numbers having same stem value are merged together." }, { "code": null, "e": 3493, "s": 3335, "text": "Now let’s see the same stem and leaf plot after rescaling our desired plot. To rescale the plot we need to use the scale argument inside the stem() function." }, { "code": null, "e": 3502, "s": 3493, "text": "Example:" }, { "code": "# R program to illustrate# Stem and Leaf Plot # Drawing Stem and Leaf Plot after rescalingstem(ChickWeight$weight, scale = 5)", "e": 3629, "s": 3502, "text": null }, { "code": null, "e": 3637, "s": 3629, "text": "Output:" }, { "code": null, "e": 4810, "s": 3637, "text": "The decimal point is 1 digit(s) to the right of the |\n\n 3 | 599999999\n 4 | 000001111111111111111111122222222222222233334\n 4 | 5667888888889999999999999\n 5 | 00000011111111222233333444\n 5 | 5555566667778888899999\n 6 | 001111111222222223333344444\n 6 | 555556666777778888889\n 7 | 001111112222223333344444444\n 7 | 6667778889999\n 8 | 001122233444444\n 8 | 5555556677778899999\n 9 | 0001223333\n 9 | 566666788888889\n 10 | 0000111122233333334\n 10 | 5666677788899\n 11 | 0112222344\n 11 | 5555667789\n 12 | 0000222333334444\n 12 | 555566778889\n 13 | 0113444\n 13 | 555566788889\n 14 | 111234444\n 14 | 5555666667778889\n 15 | 0011234444\n 15 | 555666777777789\n 16 | 000022333344444\n 16 | 6678899\n 17 | 000013444\n 17 | 5555789\n 18 | 12244444\n 18 | 55567778\n 19 | 222\n 19 | 5677778889999\n 20 | 0123444\n 20 | 5555579\n 21 | 0024\n 21 | 5578\n 22 | 00123\n 22 | 577\n 23 | 01123344\n 23 | 556788\n 24 | 0\n 24 | 8\n 25 | 001\n 25 | 699\n 26 | 12344\n 26 | 569\n 27 | 2\n 27 | 59\n 28 | 01\n 28 | 78\n 29 | 014\n 29 | 5\n 30 | 3\n 30 | 5579\n 31 |\n 31 | 8\n 32 | 12\n 32 | 7\n 33 | 12\n 33 |\n 34 | 1\n 34 |\n 35 |\n 35 |\n 36 | 1\n 36 |\n 37 | 3\n\n" }, { "code": null, "e": 4823, "s": 4810, "text": "Explanation:" }, { "code": null, "e": 4982, "s": 4823, "text": "After changing the scaling, the distribution of data has changed horizontally. Again here the stems are on the left side and the leaves are on the right side." }, { "code": null, "e": 5087, "s": 4982, "text": "On using width argument in the stem() function one can change the width of the plot into a desired plot." }, { "code": null, "e": 5096, "s": 5087, "text": "Example:" }, { "code": "# R program to illustrate# Stem and Leaf Plot # Drawing Stem and Leaf Plot by changing the widthstem(ChickWeight$weight, width = 100)", "e": 5231, "s": 5096, "text": null }, { "code": null, "e": 5239, "s": 5231, "text": "Output:" }, { "code": null, "e": 5972, "s": 5239, "text": "The decimal point is 1 digit(s) to the right of the |\n\n 2 | 599999999\n 4 | 0000011111111111111111111222222222222222333345667888888889999999999999000000111111112222+18\n 6 | 0011111112222222233333444445555566667777788888890011111122222233333444444446667778889999\n 8 | 00112223344444455555566777788999990001223333566666788888889\n 10 | 0000111122233333334566667778889901122223445555667789\n 12 | 00002223333344445555667788890113444555566788889\n 14 | 11123444455556666677788890011234444555666777777789\n 16 | 00002233334444466788990000134445555789\n 18 | 12244444555677782225677778889999\n 20 | 0123444555557900245578\n 22 | 0012357701123344556788\n 24 | 08001699\n 26 | 12344569259\n 28 | 01780145\n 30 | 355798\n 32 | 12712\n 34 | 1\n 36 | 13\n" }, { "code": null, "e": 5985, "s": 5972, "text": "Explanation:" }, { "code": null, "e": 6173, "s": 5985, "text": "As the width is changed to 100 from 80, the distribution of data has also changed. Here the left side of the chart shows the stem while the leaves are on the right-hand side of the chart." }, { "code": null, "e": 6348, "s": 6173, "text": "The stem and leaf plot is very useful for displaying the shape and relative density of data, hence giving the reader or customer a quick overview of the kind of distribution." }, { "code": null, "e": 6425, "s": 6348, "text": "Most of the times they can retain the raw data with quite perfect integrity." }, { "code": null, "e": 6507, "s": 6425, "text": "A very useful method for highlighting the outliers and also for finding the mode." }, { "code": null, "e": 6514, "s": 6507, "text": "Picked" }, { "code": null, "e": 6533, "s": 6514, "text": "R Machine-Learning" }, { "code": null, "e": 6541, "s": 6533, "text": "R-plots" }, { "code": null, "e": 6554, "s": 6541, "text": "R-Statistics" }, { "code": null, "e": 6565, "s": 6554, "text": "R Language" }, { "code": null, "e": 6663, "s": 6565, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6715, "s": 6663, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 6773, "s": 6715, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 6808, "s": 6773, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 6846, "s": 6808, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 6895, "s": 6846, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 6932, "s": 6895, "text": "Logistic Regression in R Programming" }, { "code": null, "e": 6949, "s": 6932, "text": "R - if statement" }, { "code": null, "e": 6992, "s": 6949, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 7029, "s": 6992, "text": "How to import an Excel File into R ?" } ]
Print anagrams together in Python using List and Dictionary
19 Apr, 2022 Given an array of words, print all anagrams together ? Examples: Input : arr = ['cat', 'dog', 'tac', 'god', 'act'] Output : 'cat tac act dog god' This problem has existing solution please refer Anagrams and Given a sequence of words, print all anagrams together links. We will solve this problem in python using List and Dictionary data structures. Approach is very simple : Traverse list of strings. Sort each string in ascending order and consider this sorted value as Key and original value as Value of corresponding key. Check if key is not present in dictionary that means it is occurring first time, so map a empty list to Key and append value in it, if key is already present then simple append the value. Now each key will contain list of strings which are anagram together. Python3 # Function to return all anagrams togetherdef allAnagram(input): # empty dictionary which holds subsets # of all anagrams together dict = {} # traverse list of strings for strVal in input: # sorted(iterable) method accepts any # iterable and returns list of items # in ascending order key = ''.join(sorted(strVal)) # now check if key exist in dictionary # or not. If yes then simply append the # strVal into the list of it's corresponding # key. If not then map empty list onto # key and then start appending values if key in dict.keys(): dict[key].append(strVal) else: dict[key] = [] dict[key].append(strVal) # traverse dictionary and concatenate values # of keys together output = "" for key,value in dict.items(): output = output + ' '.join(value) + ' ' return output # Driver functionif __name__ == "__main__": input=['cat', 'dog', 'tac', 'god', 'act'] print (allAnagram(input)) Output: 'cat tac act dog god' This article is contributed by Shashank Mishra (Gullu). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. nidhi_biet sumitgumber28 anagram Python dictionary-programs Python list-programs python-dict python-list Python Strings python-dict python-list Strings anagram Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() Write a program to reverse an array or string Reverse a string in Java C++ Data Types Write a program to print all permutations of a given string Check for Balanced Brackets in an expression (well-formedness) using Stack
[ { "code": null, "e": 54, "s": 26, "text": "\n19 Apr, 2022" }, { "code": null, "e": 119, "s": 54, "text": "Given an array of words, print all anagrams together ? Examples:" }, { "code": null, "e": 200, "s": 119, "text": "Input : arr = ['cat', 'dog', 'tac', 'god', 'act']\nOutput : 'cat tac act dog god'" }, { "code": null, "e": 429, "s": 200, "text": "This problem has existing solution please refer Anagrams and Given a sequence of words, print all anagrams together links. We will solve this problem in python using List and Dictionary data structures. Approach is very simple :" }, { "code": null, "e": 455, "s": 429, "text": "Traverse list of strings." }, { "code": null, "e": 767, "s": 455, "text": "Sort each string in ascending order and consider this sorted value as Key and original value as Value of corresponding key. Check if key is not present in dictionary that means it is occurring first time, so map a empty list to Key and append value in it, if key is already present then simple append the value." }, { "code": null, "e": 837, "s": 767, "text": "Now each key will contain list of strings which are anagram together." }, { "code": null, "e": 845, "s": 837, "text": "Python3" }, { "code": "# Function to return all anagrams togetherdef allAnagram(input): # empty dictionary which holds subsets # of all anagrams together dict = {} # traverse list of strings for strVal in input: # sorted(iterable) method accepts any # iterable and returns list of items # in ascending order key = ''.join(sorted(strVal)) # now check if key exist in dictionary # or not. If yes then simply append the # strVal into the list of it's corresponding # key. If not then map empty list onto # key and then start appending values if key in dict.keys(): dict[key].append(strVal) else: dict[key] = [] dict[key].append(strVal) # traverse dictionary and concatenate values # of keys together output = \"\" for key,value in dict.items(): output = output + ' '.join(value) + ' ' return output # Driver functionif __name__ == \"__main__\": input=['cat', 'dog', 'tac', 'god', 'act'] print (allAnagram(input))", "e": 1907, "s": 845, "text": null }, { "code": null, "e": 1915, "s": 1907, "text": "Output:" }, { "code": null, "e": 1937, "s": 1915, "text": "'cat tac act dog god'" }, { "code": null, "e": 2369, "s": 1937, "text": "This article is contributed by Shashank Mishra (Gullu). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 2380, "s": 2369, "text": "nidhi_biet" }, { "code": null, "e": 2394, "s": 2380, "text": "sumitgumber28" }, { "code": null, "e": 2402, "s": 2394, "text": "anagram" }, { "code": null, "e": 2429, "s": 2402, "text": "Python dictionary-programs" }, { "code": null, "e": 2450, "s": 2429, "text": "Python list-programs" }, { "code": null, "e": 2462, "s": 2450, "text": "python-dict" }, { "code": null, "e": 2474, "s": 2462, "text": "python-list" }, { "code": null, "e": 2481, "s": 2474, "text": "Python" }, { "code": null, "e": 2489, "s": 2481, "text": "Strings" }, { "code": null, "e": 2501, "s": 2489, "text": "python-dict" }, { "code": null, "e": 2513, "s": 2501, "text": "python-list" }, { "code": null, "e": 2521, "s": 2513, "text": "Strings" }, { "code": null, "e": 2529, "s": 2521, "text": "anagram" }, { "code": null, "e": 2627, "s": 2529, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2645, "s": 2627, "text": "Python Dictionary" }, { "code": null, "e": 2687, "s": 2645, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2709, "s": 2687, "text": "Enumerate() in Python" }, { "code": null, "e": 2744, "s": 2709, "text": "Read a file line by line in Python" }, { "code": null, "e": 2770, "s": 2744, "text": "Python String | replace()" }, { "code": null, "e": 2816, "s": 2770, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 2841, "s": 2816, "text": "Reverse a string in Java" }, { "code": null, "e": 2856, "s": 2841, "text": "C++ Data Types" }, { "code": null, "e": 2916, "s": 2856, "text": "Write a program to print all permutations of a given string" } ]
Python | Pandas Series.dt.hour
20 Mar, 2019 Series.dt can be used to access the values of the series as datetimelike and return several properties. Pandas Series.dt.hour attribute return a numpy array containing the hour of the datetime in the underlying data of the given series object. Syntax: Series.dt.hour Parameter : None Returns : numpy array Example #1: Use Series.dt.hour attribute to return the hour of the datetime in the underlying data of the given Series object. # importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['2012-10-21 09:30', '2019-7-18 12:30', '2008-02-2 10:30', '2010-4-22 09:25', '2019-11-8 02:22']) # Creating the indexidx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] # set the indexsr.index = idx # Convert the underlying data to datetime sr = pd.to_datetime(sr) # Print the seriesprint(sr) Output : Now we will use Series.dt.hour attribute to return the hour of the datetime in the underlying data of the given Series object. # return the hourresult = sr.dt.hour # print the resultprint(result) Output :As we can see in the output, the Series.dt.hour attribute has successfully accessed and returned the hour of the datetime in the underlying data of the given series object. Example #2 : Use Series.dt.hour attribute to return the hour of the datetime in the underlying data of the given Series object. # importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(pd.date_range('2012-12-12 12:12', periods = 5, freq = 'H')) # Creating the indexidx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] # set the indexsr.index = idx # Print the seriesprint(sr) Output : Now we will use Series.dt.hour attribute to return the hour of the datetime in the underlying data of the given Series object. # return the hourresult = sr.dt.hour # print the resultprint(result) Output : As we can see in the output, the Series.dt.hour attribute has successfully accessed and returned the hour of the datetime in the underlying data of the given series object. Python pandas-series-datetime Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Python OOPs Concepts
[ { "code": null, "e": 28, "s": 0, "text": "\n20 Mar, 2019" }, { "code": null, "e": 272, "s": 28, "text": "Series.dt can be used to access the values of the series as datetimelike and return several properties. Pandas Series.dt.hour attribute return a numpy array containing the hour of the datetime in the underlying data of the given series object." }, { "code": null, "e": 295, "s": 272, "text": "Syntax: Series.dt.hour" }, { "code": null, "e": 312, "s": 295, "text": "Parameter : None" }, { "code": null, "e": 334, "s": 312, "text": "Returns : numpy array" }, { "code": null, "e": 461, "s": 334, "text": "Example #1: Use Series.dt.hour attribute to return the hour of the datetime in the underlying data of the given Series object." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['2012-10-21 09:30', '2019-7-18 12:30', '2008-02-2 10:30', '2010-4-22 09:25', '2019-11-8 02:22']) # Creating the indexidx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] # set the indexsr.index = idx # Convert the underlying data to datetime sr = pd.to_datetime(sr) # Print the seriesprint(sr)", "e": 855, "s": 461, "text": null }, { "code": null, "e": 864, "s": 855, "text": "Output :" }, { "code": null, "e": 991, "s": 864, "text": "Now we will use Series.dt.hour attribute to return the hour of the datetime in the underlying data of the given Series object." }, { "code": "# return the hourresult = sr.dt.hour # print the resultprint(result)", "e": 1061, "s": 991, "text": null }, { "code": null, "e": 1370, "s": 1061, "text": "Output :As we can see in the output, the Series.dt.hour attribute has successfully accessed and returned the hour of the datetime in the underlying data of the given series object. Example #2 : Use Series.dt.hour attribute to return the hour of the datetime in the underlying data of the given Series object." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(pd.date_range('2012-12-12 12:12', periods = 5, freq = 'H')) # Creating the indexidx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] # set the indexsr.index = idx # Print the seriesprint(sr)", "e": 1666, "s": 1370, "text": null }, { "code": null, "e": 1675, "s": 1666, "text": "Output :" }, { "code": null, "e": 1802, "s": 1675, "text": "Now we will use Series.dt.hour attribute to return the hour of the datetime in the underlying data of the given Series object." }, { "code": "# return the hourresult = sr.dt.hour # print the resultprint(result)", "e": 1872, "s": 1802, "text": null }, { "code": null, "e": 1881, "s": 1872, "text": "Output :" }, { "code": null, "e": 2054, "s": 1881, "text": "As we can see in the output, the Series.dt.hour attribute has successfully accessed and returned the hour of the datetime in the underlying data of the given series object." }, { "code": null, "e": 2084, "s": 2054, "text": "Python pandas-series-datetime" }, { "code": null, "e": 2098, "s": 2084, "text": "Python-pandas" }, { "code": null, "e": 2105, "s": 2098, "text": "Python" }, { "code": null, "e": 2203, "s": 2105, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2221, "s": 2203, "text": "Python Dictionary" }, { "code": null, "e": 2263, "s": 2221, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2285, "s": 2263, "text": "Enumerate() in Python" }, { "code": null, "e": 2320, "s": 2285, "text": "Read a file line by line in Python" }, { "code": null, "e": 2346, "s": 2320, "text": "Python String | replace()" }, { "code": null, "e": 2378, "s": 2346, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2407, "s": 2378, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2434, "s": 2407, "text": "Python Classes and Objects" }, { "code": null, "e": 2464, "s": 2434, "text": "Iterate over a list in Python" } ]
Student Information Management System
24 Mar, 2022 Prerequisites: Switch Case in C/C++ Problem Statement: Write a program to build a simple Software for Student Information Management System which can perform the following operations: Store the First name of the student.Store the Last name of the student.Store the unique Roll number for every student.Store the CGPA of every student.Store the courses registered by the student. Store the First name of the student. Store the Last name of the student. Store the unique Roll number for every student. Store the CGPA of every student. Store the courses registered by the student. Approach: The idea is to form an individual functions for every operation. All the functions are unified together to form software. Add Student Details: Get data from user and add a student to the list of students. While adding the students into the list, check for the uniqueness of the roll number.Find the student by the given roll number: This function is to find the student record for the given roll number and print the details.Find the student by the given first name: This function is to find all the students with the given first name and print their details.Find the students registered in a course: This function is to find all the students who have registered for a given course.Count of Students: This function is to print the total number of students in the systemDelete a student: This function is to delete the student record for the given roll number.Update Student: This function is to update the student records. This function does not ask for new details for all fields but the user should be able to pick and choose what he wants to update. Add Student Details: Get data from user and add a student to the list of students. While adding the students into the list, check for the uniqueness of the roll number. Find the student by the given roll number: This function is to find the student record for the given roll number and print the details. Find the student by the given first name: This function is to find all the students with the given first name and print their details. Find the students registered in a course: This function is to find all the students who have registered for a given course. Count of Students: This function is to print the total number of students in the system Delete a student: This function is to delete the student record for the given roll number. Update Student: This function is to update the student records. This function does not ask for new details for all fields but the user should be able to pick and choose what he wants to update. Add Find by Roll No Find by Name Find registered student Count Delete Update // Function to add the student into the databasevoid add_student(){ printf("Add the Students Details\n"); printf("-------------------------\n"); printf("Enter the first name of student\n"); // First name of the student st[i].fname = "Rahul"; printf("Enter the last name of student\n"); // Last name of the student st[i].lname = "Kumar"; printf("Enter the Roll Number\n"); // Roll Number of the student st[i].roll = 1; printf("Enter the CGPA you obtained\n"); // CGPA of the student st[i].cgpa = 8; printf("Enter the course ID" " of each course\n"); // Storing the courses every student // is enrolled in for (int j = 0; j < 5; j++) { st[i].cid[j] = j; } i = i + 1;} // Function to find the details// of the student by roll numbervoid find_rl(){ int x; printf("Enter the Roll Number" " of the student\n"); // Roll number for which the details // needs to be found x = 1; // Iterating through all the students for (int j = 0; j < i; j++) { // If the roll number is found if (x == st[j].roll) { printf("The Students Details are\n"); printf("The First name is %s\n", st[j].fname); printf("The Last name is %s\n", st[j].lname); printf("The CGPA is %f\n", st[j].cgpa); // Printing the courses // in which the student // is enrolled for (int k = 0; k < 5; k++) { printf( "The course ID are %d\n", st[j].cid[k]); } break; } }} // Function to search the students list// by the given first namevoid find_fn(){ char a[50]; printf("Enter the First Name" " of the student\n"); a = "Rahul"; int c = 0; // Iterating through the students list for (int j = 0; j <= i; j++) { // Compare the first names if (!strcmp(st[j].fname, a)) { printf( "The Students Details are\n"); printf( "The First name is %s\n", st[j].fname); printf( "The Last name is %s\n", st[j].lname); printf( "The Roll Number is %d\n ", st[j].roll); printf( "The CGPA is %f\n", st[j].cgpa); printf("Enter the course ID " "of each course\n"); // Print the course ID's for (int k = 0; k < 5; k++) { printf( "The course ID are %d\n", st[j].cid[k]); } c = 1; } }} // Function to find all the students// who have registered for a given coursevoid find_c(){ int id; printf("Enter the course ID \n"); // Course ID id = 1; int c = 0; // Iterating through the students list for (int j = 0; j <= i; j++) { // Checking if the student // has registered in the // given course or not for (int d = 0; d < 5; d++) { if (id == st[j].cid[d]) { printf( "The Students Details are\n"); printf( "The First name is %s\n", st[j].fname); printf( "The Last name is %s\n", st[j].lname); printf( "The Roll Number is %d\n ", st[j].roll); printf( "The CGPA is %f\n", st[j].cgpa); c = 1; break; } } }} // Function to print the// total number of studentsvoid tot_s(){ printf("The total number of" " Student is %d\n", i); printf("\n you can have a " "max of 50 students\n"); printf("you can have %d more" " students\n", 50 - i);} // Function to delete a student// by the roll numbervoid del_s(){ int a; printf("Enter the Roll Number" " which you want to delete\n"); a = 1; // Iterating through the list and // find the student with the given // roll number for (int j = 0; j <= i; j++) { if (a == st[j].roll) { for (int k = j; k < 49; k++) st[k] = st[k + 1]; i--; } } printf("The Roll Number is " "removed Successfully\n");} // Function to update the// details of the studentvoid up_s(){ printf("Enter the roll number" " to update the entry: "); long int x; x = 1; for (int j = 0; j < i; j++) { if (st[j].roll == x) { printf("1. first name\n" "2. last name\n" "3. roll no.\n" "4. CGPA\n" "5. courses\n"); int z; // Updating the CGPA z = 4; switch (z) { case 1: printf("Enter the new first name : \n"); scanf("%s", st[j].fname); break; case 2: printf("Enter the new last name : \n"); scanf("%s", st[j].lname); break; case 3: printf("Enter the new roll number : \n"); scanf("%d", &st[j].roll); break; case 4: printf("Enter the new CGPA : \n"); st[j].cgpa = 9; break; case 5: printf("Enter the new courses \n"); scanf("%d%d%d%d%d", &st[j].cid[0], &st[j].cid[1], &st[j].cid[2], &st[j].cid[3], &st[j].cid[4]); break; } printf("UPDATED SUCCESSFULLY.\n"); } }} Below is the implementation of the above approach: C // C program for the implementation of// menu driven program for student// management system#include <math.h>#include <stdio.h>#include <stdlib.h>#include <string.h> // Variable to keep track of// number of studentsint i = 0; // Structure to store the studentstruct sinfo { char fname[50]; char lname[50]; int roll; float cgpa; int cid[10];} st[55]; // Function to add the studentvoid add_student(){ printf("Add the Students Details\n"); printf("-------------------------\n"); printf("Enter the first " "name of student\n"); scanf("%s", st[i].fname); printf("Enter the last name" " of student\n"); scanf("%s", st[i].lname); printf("Enter the Roll Number\n"); scanf("%d", &st[i].roll); printf("Enter the CGPA " "you obtained\n"); scanf("%f", &st[i].cgpa); printf("Enter the course ID" " of each course\n"); for (int j = 0; j < 5; j++) { scanf("%d", &st[i].cid[j]); } i = i + 1;} // Function to find the student// by the roll numbervoid find_rl(){ int x; printf("Enter the Roll Number" " of the student\n"); scanf("%d", &x); for (int j = 1; j <= i; j++) { if (x == st[i].roll) { printf( "The Students Details are\n"); printf( "The First name is %s\n", st[i].fname); printf( "The Last name is %s\n", st[i].lname); printf( "The CGPA is %f\n", st[i].cgpa); printf( "Enter the course ID" " of each course\n"); } for (int j = 0; j < 5; j++) { printf( "The course ID are %d\n", st[i].cid[j]); } break; }} // Function to find the student// by the first namevoid find_fn(){ char a[50]; printf("Enter the First Name" " of the student\n"); scanf("%s", a); int c = 0; for (int j = 1; j <= i; j++) { if (!strcmp(st[j].fname, a)) { printf( "The Students Details are\n"); printf( "The First name is %s\n", st[i].fname); printf( "The Last name is %s\n", st[i].lname); printf( "The Roll Number is %d\n ", st[i].roll); printf( "The CGPA is %f\n", st[i].cgpa); printf( "Enter the course ID of each course\n"); for (int j = 0; j < 5; j++) { printf( "The course ID are %d\n", st[i].cid[j]); } c = 1; } else printf( "The First Name not Found\n"); }} // Function to find// the students enrolled// in a particular coursevoid find_c(){ int id; printf("Enter the course ID \n"); scanf("%d", &id); int c = 0; for (int j = 1; j <= i; j++) { for (int d = 0; d < 5; d++) { if (id == st[j].cid[d]) { printf( "The Students Details are\n"); printf( "The First name is %s\n", st[i].fname); printf( "The Last name is %s\n", st[i].lname); printf( "The Roll Number is %d\n ", st[i].roll); printf( "The CGPA is %f\n", st[i].cgpa); c = 1; break; } else printf( "The First Name not Found\n"); } }} // Function to print the total// number of studentsvoid tot_s(){ printf("The total number of" " Student is %d\n", i); printf("\n you can have a " "max of 50 students\n"); printf("you can have %d " "more students\n", 50 - i);} // Function to delete a student// by the roll numbervoid del_s(){ int a; printf("Enter the Roll Number" " which you want " "to delete\n"); scanf("%d", &a); for (int j = 1; j <= i; j++) { if (a == st[j].roll) { for (int k = j; k < 49; k++) st[k] = st[k + 1]; i--; } } printf("The Roll Number" " is removed Successfully\n");} // Function to update a students datavoid up_s(){ printf("Enter the roll number" " to update the entry : "); long int x; scanf("%ld", &x); for (int j = 0; j < i; j++) { if (st[j].roll == x) { printf("1. first name\n" "2. last name\n" "3. roll no.\n" "4. CGPA\n" "5. courses\n"); int z; scanf("%d", &z); switch (z) { case 1: printf("Enter the new " "first name : \n"); scanf("%s", st[j].fname); break; case 2: printf("Enter the new " "last name : \n"); scanf("%s", st[j].lname); break; case 3: printf("Enter the new " "roll number : \n"); scanf("%d", &st[j].roll); break; case 4: printf("Enter the new CGPA : \n"); scanf("%f", &st[j].cgpa); break; case 5: printf("Enter the new courses \n"); scanf( "%d%d%d%d%d", &st[j].cid[0], &st[j].cid[1], &st[j].cid[2], &st[j].cid[3], &st[j].cid[4]); break; } printf("UPDATED SUCCESSFULLY.\n"); } }} // Driver codevoid main() { int choice, count; while (i = 1) { printf("The Task that you " "want to perform\n"); printf("1. Add the Student Details\n"); printf("2. Find the Student " "Details by Roll Number\n"); printf("3. Find the Student " "Details by First Name\n"); printf("4. Find the Student " "Details by Course Id\n"); printf("5. Find the Total number" " of Students\n"); printf("6. Delete the Students Details" " by Roll Number\n"); printf("7. Update the Students Details" " by Roll Number\n"); printf("8. To Exit\n"); printf("Enter your choice to " "find the task\n"); scanf("%d", &choice); switch (choice) { case 1: add_student(); break; case 2: find_rl(); break; case 3: find_fn(); break; case 4: find_c(); break; case 5: tot_s(); break; case 6: del_s(); break; case 7: up_s(); break; case 8: exit(0); break; } }} sagartomar9927 Project School Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Implementing Web Scraping in Python with BeautifulSoup OpenCV C++ Program for Face Detection 10 Best Web Development Projects For Your Resume Simple Chat Room using Python Twitter Sentiment Analysis using Python Python Dictionary Reverse a string in Java Arrays in C/C++ Introduction To PYTHON Interfaces in Java
[ { "code": null, "e": 54, "s": 26, "text": "\n24 Mar, 2022" }, { "code": null, "e": 238, "s": 54, "text": "Prerequisites: Switch Case in C/C++ Problem Statement: Write a program to build a simple Software for Student Information Management System which can perform the following operations:" }, { "code": null, "e": 433, "s": 238, "text": "Store the First name of the student.Store the Last name of the student.Store the unique Roll number for every student.Store the CGPA of every student.Store the courses registered by the student." }, { "code": null, "e": 470, "s": 433, "text": "Store the First name of the student." }, { "code": null, "e": 506, "s": 470, "text": "Store the Last name of the student." }, { "code": null, "e": 554, "s": 506, "text": "Store the unique Roll number for every student." }, { "code": null, "e": 587, "s": 554, "text": "Store the CGPA of every student." }, { "code": null, "e": 632, "s": 587, "text": "Store the courses registered by the student." }, { "code": null, "e": 764, "s": 632, "text": "Approach: The idea is to form an individual functions for every operation. All the functions are unified together to form software." }, { "code": null, "e": 1695, "s": 764, "text": "Add Student Details: Get data from user and add a student to the list of students. While adding the students into the list, check for the uniqueness of the roll number.Find the student by the given roll number: This function is to find the student record for the given roll number and print the details.Find the student by the given first name: This function is to find all the students with the given first name and print their details.Find the students registered in a course: This function is to find all the students who have registered for a given course.Count of Students: This function is to print the total number of students in the systemDelete a student: This function is to delete the student record for the given roll number.Update Student: This function is to update the student records. This function does not ask for new details for all fields but the user should be able to pick and choose what he wants to update." }, { "code": null, "e": 1864, "s": 1695, "text": "Add Student Details: Get data from user and add a student to the list of students. While adding the students into the list, check for the uniqueness of the roll number." }, { "code": null, "e": 2000, "s": 1864, "text": "Find the student by the given roll number: This function is to find the student record for the given roll number and print the details." }, { "code": null, "e": 2135, "s": 2000, "text": "Find the student by the given first name: This function is to find all the students with the given first name and print their details." }, { "code": null, "e": 2259, "s": 2135, "text": "Find the students registered in a course: This function is to find all the students who have registered for a given course." }, { "code": null, "e": 2347, "s": 2259, "text": "Count of Students: This function is to print the total number of students in the system" }, { "code": null, "e": 2438, "s": 2347, "text": "Delete a student: This function is to delete the student record for the given roll number." }, { "code": null, "e": 2632, "s": 2438, "text": "Update Student: This function is to update the student records. This function does not ask for new details for all fields but the user should be able to pick and choose what he wants to update." }, { "code": null, "e": 2636, "s": 2632, "text": "Add" }, { "code": null, "e": 2652, "s": 2636, "text": "Find by Roll No" }, { "code": null, "e": 2665, "s": 2652, "text": "Find by Name" }, { "code": null, "e": 2689, "s": 2665, "text": "Find registered student" }, { "code": null, "e": 2695, "s": 2689, "text": "Count" }, { "code": null, "e": 2702, "s": 2695, "text": "Delete" }, { "code": null, "e": 2709, "s": 2702, "text": "Update" }, { "code": "// Function to add the student into the databasevoid add_student(){ printf(\"Add the Students Details\\n\"); printf(\"-------------------------\\n\"); printf(\"Enter the first name of student\\n\"); // First name of the student st[i].fname = \"Rahul\"; printf(\"Enter the last name of student\\n\"); // Last name of the student st[i].lname = \"Kumar\"; printf(\"Enter the Roll Number\\n\"); // Roll Number of the student st[i].roll = 1; printf(\"Enter the CGPA you obtained\\n\"); // CGPA of the student st[i].cgpa = 8; printf(\"Enter the course ID\" \" of each course\\n\"); // Storing the courses every student // is enrolled in for (int j = 0; j < 5; j++) { st[i].cid[j] = j; } i = i + 1;}", "e": 3458, "s": 2709, "text": null }, { "code": "// Function to find the details// of the student by roll numbervoid find_rl(){ int x; printf(\"Enter the Roll Number\" \" of the student\\n\"); // Roll number for which the details // needs to be found x = 1; // Iterating through all the students for (int j = 0; j < i; j++) { // If the roll number is found if (x == st[j].roll) { printf(\"The Students Details are\\n\"); printf(\"The First name is %s\\n\", st[j].fname); printf(\"The Last name is %s\\n\", st[j].lname); printf(\"The CGPA is %f\\n\", st[j].cgpa); // Printing the courses // in which the student // is enrolled for (int k = 0; k < 5; k++) { printf( \"The course ID are %d\\n\", st[j].cid[k]); } break; } }}", "e": 4387, "s": 3458, "text": null }, { "code": "// Function to search the students list// by the given first namevoid find_fn(){ char a[50]; printf(\"Enter the First Name\" \" of the student\\n\"); a = \"Rahul\"; int c = 0; // Iterating through the students list for (int j = 0; j <= i; j++) { // Compare the first names if (!strcmp(st[j].fname, a)) { printf( \"The Students Details are\\n\"); printf( \"The First name is %s\\n\", st[j].fname); printf( \"The Last name is %s\\n\", st[j].lname); printf( \"The Roll Number is %d\\n \", st[j].roll); printf( \"The CGPA is %f\\n\", st[j].cgpa); printf(\"Enter the course ID \" \"of each course\\n\"); // Print the course ID's for (int k = 0; k < 5; k++) { printf( \"The course ID are %d\\n\", st[j].cid[k]); } c = 1; } }}", "e": 5449, "s": 4387, "text": null }, { "code": "// Function to find all the students// who have registered for a given coursevoid find_c(){ int id; printf(\"Enter the course ID \\n\"); // Course ID id = 1; int c = 0; // Iterating through the students list for (int j = 0; j <= i; j++) { // Checking if the student // has registered in the // given course or not for (int d = 0; d < 5; d++) { if (id == st[j].cid[d]) { printf( \"The Students Details are\\n\"); printf( \"The First name is %s\\n\", st[j].fname); printf( \"The Last name is %s\\n\", st[j].lname); printf( \"The Roll Number is %d\\n \", st[j].roll); printf( \"The CGPA is %f\\n\", st[j].cgpa); c = 1; break; } } }}", "e": 6423, "s": 5449, "text": null }, { "code": "// Function to print the// total number of studentsvoid tot_s(){ printf(\"The total number of\" \" Student is %d\\n\", i); printf(\"\\n you can have a \" \"max of 50 students\\n\"); printf(\"you can have %d more\" \" students\\n\", 50 - i);}", "e": 6708, "s": 6423, "text": null }, { "code": "// Function to delete a student// by the roll numbervoid del_s(){ int a; printf(\"Enter the Roll Number\" \" which you want to delete\\n\"); a = 1; // Iterating through the list and // find the student with the given // roll number for (int j = 0; j <= i; j++) { if (a == st[j].roll) { for (int k = j; k < 49; k++) st[k] = st[k + 1]; i--; } } printf(\"The Roll Number is \" \"removed Successfully\\n\");}", "e": 7202, "s": 6708, "text": null }, { "code": "// Function to update the// details of the studentvoid up_s(){ printf(\"Enter the roll number\" \" to update the entry: \"); long int x; x = 1; for (int j = 0; j < i; j++) { if (st[j].roll == x) { printf(\"1. first name\\n\" \"2. last name\\n\" \"3. roll no.\\n\" \"4. CGPA\\n\" \"5. courses\\n\"); int z; // Updating the CGPA z = 4; switch (z) { case 1: printf(\"Enter the new first name : \\n\"); scanf(\"%s\", st[j].fname); break; case 2: printf(\"Enter the new last name : \\n\"); scanf(\"%s\", st[j].lname); break; case 3: printf(\"Enter the new roll number : \\n\"); scanf(\"%d\", &st[j].roll); break; case 4: printf(\"Enter the new CGPA : \\n\"); st[j].cgpa = 9; break; case 5: printf(\"Enter the new courses \\n\"); scanf(\"%d%d%d%d%d\", &st[j].cid[0], &st[j].cid[1], &st[j].cid[2], &st[j].cid[3], &st[j].cid[4]); break; } printf(\"UPDATED SUCCESSFULLY.\\n\"); } }}", "e": 8544, "s": 7202, "text": null }, { "code": null, "e": 8596, "s": 8544, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 8598, "s": 8596, "text": "C" }, { "code": "// C program for the implementation of// menu driven program for student// management system#include <math.h>#include <stdio.h>#include <stdlib.h>#include <string.h> // Variable to keep track of// number of studentsint i = 0; // Structure to store the studentstruct sinfo { char fname[50]; char lname[50]; int roll; float cgpa; int cid[10];} st[55]; // Function to add the studentvoid add_student(){ printf(\"Add the Students Details\\n\"); printf(\"-------------------------\\n\"); printf(\"Enter the first \" \"name of student\\n\"); scanf(\"%s\", st[i].fname); printf(\"Enter the last name\" \" of student\\n\"); scanf(\"%s\", st[i].lname); printf(\"Enter the Roll Number\\n\"); scanf(\"%d\", &st[i].roll); printf(\"Enter the CGPA \" \"you obtained\\n\"); scanf(\"%f\", &st[i].cgpa); printf(\"Enter the course ID\" \" of each course\\n\"); for (int j = 0; j < 5; j++) { scanf(\"%d\", &st[i].cid[j]); } i = i + 1;} // Function to find the student// by the roll numbervoid find_rl(){ int x; printf(\"Enter the Roll Number\" \" of the student\\n\"); scanf(\"%d\", &x); for (int j = 1; j <= i; j++) { if (x == st[i].roll) { printf( \"The Students Details are\\n\"); printf( \"The First name is %s\\n\", st[i].fname); printf( \"The Last name is %s\\n\", st[i].lname); printf( \"The CGPA is %f\\n\", st[i].cgpa); printf( \"Enter the course ID\" \" of each course\\n\"); } for (int j = 0; j < 5; j++) { printf( \"The course ID are %d\\n\", st[i].cid[j]); } break; }} // Function to find the student// by the first namevoid find_fn(){ char a[50]; printf(\"Enter the First Name\" \" of the student\\n\"); scanf(\"%s\", a); int c = 0; for (int j = 1; j <= i; j++) { if (!strcmp(st[j].fname, a)) { printf( \"The Students Details are\\n\"); printf( \"The First name is %s\\n\", st[i].fname); printf( \"The Last name is %s\\n\", st[i].lname); printf( \"The Roll Number is %d\\n \", st[i].roll); printf( \"The CGPA is %f\\n\", st[i].cgpa); printf( \"Enter the course ID of each course\\n\"); for (int j = 0; j < 5; j++) { printf( \"The course ID are %d\\n\", st[i].cid[j]); } c = 1; } else printf( \"The First Name not Found\\n\"); }} // Function to find// the students enrolled// in a particular coursevoid find_c(){ int id; printf(\"Enter the course ID \\n\"); scanf(\"%d\", &id); int c = 0; for (int j = 1; j <= i; j++) { for (int d = 0; d < 5; d++) { if (id == st[j].cid[d]) { printf( \"The Students Details are\\n\"); printf( \"The First name is %s\\n\", st[i].fname); printf( \"The Last name is %s\\n\", st[i].lname); printf( \"The Roll Number is %d\\n \", st[i].roll); printf( \"The CGPA is %f\\n\", st[i].cgpa); c = 1; break; } else printf( \"The First Name not Found\\n\"); } }} // Function to print the total// number of studentsvoid tot_s(){ printf(\"The total number of\" \" Student is %d\\n\", i); printf(\"\\n you can have a \" \"max of 50 students\\n\"); printf(\"you can have %d \" \"more students\\n\", 50 - i);} // Function to delete a student// by the roll numbervoid del_s(){ int a; printf(\"Enter the Roll Number\" \" which you want \" \"to delete\\n\"); scanf(\"%d\", &a); for (int j = 1; j <= i; j++) { if (a == st[j].roll) { for (int k = j; k < 49; k++) st[k] = st[k + 1]; i--; } } printf(\"The Roll Number\" \" is removed Successfully\\n\");} // Function to update a students datavoid up_s(){ printf(\"Enter the roll number\" \" to update the entry : \"); long int x; scanf(\"%ld\", &x); for (int j = 0; j < i; j++) { if (st[j].roll == x) { printf(\"1. first name\\n\" \"2. last name\\n\" \"3. roll no.\\n\" \"4. CGPA\\n\" \"5. courses\\n\"); int z; scanf(\"%d\", &z); switch (z) { case 1: printf(\"Enter the new \" \"first name : \\n\"); scanf(\"%s\", st[j].fname); break; case 2: printf(\"Enter the new \" \"last name : \\n\"); scanf(\"%s\", st[j].lname); break; case 3: printf(\"Enter the new \" \"roll number : \\n\"); scanf(\"%d\", &st[j].roll); break; case 4: printf(\"Enter the new CGPA : \\n\"); scanf(\"%f\", &st[j].cgpa); break; case 5: printf(\"Enter the new courses \\n\"); scanf( \"%d%d%d%d%d\", &st[j].cid[0], &st[j].cid[1], &st[j].cid[2], &st[j].cid[3], &st[j].cid[4]); break; } printf(\"UPDATED SUCCESSFULLY.\\n\"); } }} // Driver codevoid main() { int choice, count; while (i = 1) { printf(\"The Task that you \" \"want to perform\\n\"); printf(\"1. Add the Student Details\\n\"); printf(\"2. Find the Student \" \"Details by Roll Number\\n\"); printf(\"3. Find the Student \" \"Details by First Name\\n\"); printf(\"4. Find the Student \" \"Details by Course Id\\n\"); printf(\"5. Find the Total number\" \" of Students\\n\"); printf(\"6. Delete the Students Details\" \" by Roll Number\\n\"); printf(\"7. Update the Students Details\" \" by Roll Number\\n\"); printf(\"8. To Exit\\n\"); printf(\"Enter your choice to \" \"find the task\\n\"); scanf(\"%d\", &choice); switch (choice) { case 1: add_student(); break; case 2: find_rl(); break; case 3: find_fn(); break; case 4: find_c(); break; case 5: tot_s(); break; case 6: del_s(); break; case 7: up_s(); break; case 8: exit(0); break; } }}", "e": 15706, "s": 8598, "text": null }, { "code": null, "e": 15721, "s": 15706, "text": "sagartomar9927" }, { "code": null, "e": 15729, "s": 15721, "text": "Project" }, { "code": null, "e": 15748, "s": 15729, "text": "School Programming" }, { "code": null, "e": 15846, "s": 15748, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 15901, "s": 15846, "text": "Implementing Web Scraping in Python with BeautifulSoup" }, { "code": null, "e": 15939, "s": 15901, "text": "OpenCV C++ Program for Face Detection" }, { "code": null, "e": 15988, "s": 15939, "text": "10 Best Web Development Projects For Your Resume" }, { "code": null, "e": 16018, "s": 15988, "text": "Simple Chat Room using Python" }, { "code": null, "e": 16058, "s": 16018, "text": "Twitter Sentiment Analysis using Python" }, { "code": null, "e": 16076, "s": 16058, "text": "Python Dictionary" }, { "code": null, "e": 16101, "s": 16076, "text": "Reverse a string in Java" }, { "code": null, "e": 16117, "s": 16101, "text": "Arrays in C/C++" }, { "code": null, "e": 16140, "s": 16117, "text": "Introduction To PYTHON" } ]
Convert HashSet to TreeSet in Java
03 Jan, 2019 Hashset: Hashset in Java is generally used for operations like search, insert and delete. It takes constant time for these operations on average. HashSet is faster than TreeSet. HashSet is Implemented using a hash table. TreeSet: TreeSet in Java takes O(log n) for search, insert and delete which is higher than HashSet. But TreeSet keeps sorted data. Also, it supports operations like higher() (Returns least higher element), floor(), ceiling(), etc. These operations are also O(log n) in TreeSet and not supported in HashSet. TreeSet is implemented using a Self Balancing Binary Search Tree (Red-Black Tree). TreeSet is backed by TreeMap in Java. In general, if you want a sorted set then it is better to add elements to HashSet and then convert it into TreeSet rather than creating a TreeSet and adding elements to it. Given a HashSet the task is to convert it into TreeSet in Java. Examples: HashSet: [Geeks, For, Welcome, To] TreeSet: [For, Geeks, To, Welcome] HashSet: [1, 2, 3, 4, 5] TreeSet: [1, 2, 3, 4, 5] We can convert HashSet to TreeSet in following ways: By invoking the parameterized constructor and sending object of Hash set as a parameter to it.First, we have to create an object for the hash set.Then we have to add all the elements to the hash set.Finally, create an object for the tree set and send the hash set object to it.Below is the implementation of the above approach:Program:import java.util.HashSet;import java.util.Set;import java.util.TreeSet; public class GFG { public static void main(String[] args) { // Get the HashSet Set<String> setobj = new HashSet<>(); setobj.add("Welcome"); setobj.add("To"); setobj.add("Geeks"); setobj.add("For"); setobj.add("Geeks"); System.out.println("HashSet: " + setobj); // Convert the HashSet to TreeSet Set<String> hashSetToTreeSet = new TreeSet<>(setobj); // Print the TreeSet System.out.println("TreeSet: " + hashSetToTreeSet); }}Output:HashSet: [Geeks, For, Welcome, To] TreeSet: [For, Geeks, To, Welcome] First, we have to create an object for the hash set.Then we have to add all the elements to the hash set.Finally, create an object for the tree set and send the hash set object to it. First, we have to create an object for the hash set. Then we have to add all the elements to the hash set. Finally, create an object for the tree set and send the hash set object to it. Below is the implementation of the above approach: Program: import java.util.HashSet;import java.util.Set;import java.util.TreeSet; public class GFG { public static void main(String[] args) { // Get the HashSet Set<String> setobj = new HashSet<>(); setobj.add("Welcome"); setobj.add("To"); setobj.add("Geeks"); setobj.add("For"); setobj.add("Geeks"); System.out.println("HashSet: " + setobj); // Convert the HashSet to TreeSet Set<String> hashSetToTreeSet = new TreeSet<>(setobj); // Print the TreeSet System.out.println("TreeSet: " + hashSetToTreeSet); }} HashSet: [Geeks, For, Welcome, To] TreeSet: [For, Geeks, To, Welcome] By constructing a tree set containing the same elements present in the hash set by using addAll method.First, we have to create an object for the hash set.Then we have to add all the elements to the hash set.Now create an object for the treeset .Using addAll method add all elements of hash set to it.Below is the implementation of the above approach:Program:import java.util.HashSet;import java.util.Set;import java.util.TreeSet; public class GFG { public static void main(String[] args) { // Get the HashSet Set<String> setobj = new HashSet<>(); setobj.add("Welcome"); setobj.add("To"); setobj.add("Geeks"); setobj.add("For"); setobj.add("Geeks"); System.out.println("HashSet: " + setobj); // Convert the HashSet to TreeSet Set<String> hashSetToTreeSet = new TreeSet<>(); hashSetToTreeSet.addAll(setobj); // Print the TreeSet System.out.println("TreeSet: " + hashSetToTreeSet); }}Output:HashSet: [Geeks, For, Welcome, To] TreeSet: [For, Geeks, To, Welcome] First, we have to create an object for the hash set.Then we have to add all the elements to the hash set.Now create an object for the treeset .Using addAll method add all elements of hash set to it. First, we have to create an object for the hash set. Then we have to add all the elements to the hash set. Now create an object for the treeset . Using addAll method add all elements of hash set to it. Below is the implementation of the above approach: Program: import java.util.HashSet;import java.util.Set;import java.util.TreeSet; public class GFG { public static void main(String[] args) { // Get the HashSet Set<String> setobj = new HashSet<>(); setobj.add("Welcome"); setobj.add("To"); setobj.add("Geeks"); setobj.add("For"); setobj.add("Geeks"); System.out.println("HashSet: " + setobj); // Convert the HashSet to TreeSet Set<String> hashSetToTreeSet = new TreeSet<>(); hashSetToTreeSet.addAll(setobj); // Print the TreeSet System.out.println("TreeSet: " + hashSetToTreeSet); }} HashSet: [Geeks, For, Welcome, To] TreeSet: [For, Geeks, To, Welcome] By using a for each loop.( This method is commonly used for conversion between two incompatible types.)First, we have to create an object for the hash set.Then we have to add all the elements to the hash set.Now create an object for the treeset .Finally, by using for each loop adding all elements of hash set to the tree set.Below is the implementation of the above approach:Program:import java.util.HashSet;import java.util.Set;import java.util.TreeSet; public class GFG { public static void main(String[] args) { // Get the HashSet Set<String> setobj = new HashSet<>(); setobj.add("Welcome"); setobj.add("To"); setobj.add("Geeks"); setobj.add("For"); setobj.add("Geeks"); System.out.println("HashSet: " + setobj); // Convert the HashSet to TreeSet Set<String> hashSetToTreeSet = new TreeSet<>(); for (String i : setobj) hashSetToTreeSet .add(i); // Print the TreeSet System.out.println("TreeSet: " + hashSetToTreeSet); }}Output:HashSet: [Geeks, For, Welcome, To] TreeSet: [For, Geeks, To, Welcome] First, we have to create an object for the hash set.Then we have to add all the elements to the hash set.Now create an object for the treeset .Finally, by using for each loop adding all elements of hash set to the tree set. First, we have to create an object for the hash set. Then we have to add all the elements to the hash set. Now create an object for the treeset . Finally, by using for each loop adding all elements of hash set to the tree set. Below is the implementation of the above approach: Program: import java.util.HashSet;import java.util.Set;import java.util.TreeSet; public class GFG { public static void main(String[] args) { // Get the HashSet Set<String> setobj = new HashSet<>(); setobj.add("Welcome"); setobj.add("To"); setobj.add("Geeks"); setobj.add("For"); setobj.add("Geeks"); System.out.println("HashSet: " + setobj); // Convert the HashSet to TreeSet Set<String> hashSetToTreeSet = new TreeSet<>(); for (String i : setobj) hashSetToTreeSet .add(i); // Print the TreeSet System.out.println("TreeSet: " + hashSetToTreeSet); }} HashSet: [Geeks, For, Welcome, To] TreeSet: [For, Geeks, To, Welcome] Java - util package Java-Collections java-hashset Java-Set-Programs java-treeset Picked Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Arrays in Java Split() String method in Java with examples Arrays.sort() in Java with examples Object Oriented Programming (OOPs) Concept in Java Reverse a string in Java For-each loop in Java How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples ArrayList in Java
[ { "code": null, "e": 52, "s": 24, "text": "\n03 Jan, 2019" }, { "code": null, "e": 273, "s": 52, "text": "Hashset: Hashset in Java is generally used for operations like search, insert and delete. It takes constant time for these operations on average. HashSet is faster than TreeSet. HashSet is Implemented using a hash table." }, { "code": null, "e": 701, "s": 273, "text": "TreeSet: TreeSet in Java takes O(log n) for search, insert and delete which is higher than HashSet. But TreeSet keeps sorted data. Also, it supports operations like higher() (Returns least higher element), floor(), ceiling(), etc. These operations are also O(log n) in TreeSet and not supported in HashSet. TreeSet is implemented using a Self Balancing Binary Search Tree (Red-Black Tree). TreeSet is backed by TreeMap in Java." }, { "code": null, "e": 874, "s": 701, "text": "In general, if you want a sorted set then it is better to add elements to HashSet and then convert it into TreeSet rather than creating a TreeSet and adding elements to it." }, { "code": null, "e": 938, "s": 874, "text": "Given a HashSet the task is to convert it into TreeSet in Java." }, { "code": null, "e": 948, "s": 938, "text": "Examples:" }, { "code": null, "e": 1070, "s": 948, "text": "HashSet: [Geeks, For, Welcome, To]\nTreeSet: [For, Geeks, To, Welcome]\n\nHashSet: [1, 2, 3, 4, 5]\nTreeSet: [1, 2, 3, 4, 5]\n" }, { "code": null, "e": 1123, "s": 1070, "text": "We can convert HashSet to TreeSet in following ways:" }, { "code": null, "e": 2199, "s": 1123, "text": "By invoking the parameterized constructor and sending object of Hash set as a parameter to it.First, we have to create an object for the hash set.Then we have to add all the elements to the hash set.Finally, create an object for the tree set and send the hash set object to it.Below is the implementation of the above approach:Program:import java.util.HashSet;import java.util.Set;import java.util.TreeSet; public class GFG { public static void main(String[] args) { // Get the HashSet Set<String> setobj = new HashSet<>(); setobj.add(\"Welcome\"); setobj.add(\"To\"); setobj.add(\"Geeks\"); setobj.add(\"For\"); setobj.add(\"Geeks\"); System.out.println(\"HashSet: \" + setobj); // Convert the HashSet to TreeSet Set<String> hashSetToTreeSet = new TreeSet<>(setobj); // Print the TreeSet System.out.println(\"TreeSet: \" + hashSetToTreeSet); }}Output:HashSet: [Geeks, For, Welcome, To]\nTreeSet: [For, Geeks, To, Welcome]\n" }, { "code": null, "e": 2383, "s": 2199, "text": "First, we have to create an object for the hash set.Then we have to add all the elements to the hash set.Finally, create an object for the tree set and send the hash set object to it." }, { "code": null, "e": 2436, "s": 2383, "text": "First, we have to create an object for the hash set." }, { "code": null, "e": 2490, "s": 2436, "text": "Then we have to add all the elements to the hash set." }, { "code": null, "e": 2569, "s": 2490, "text": "Finally, create an object for the tree set and send the hash set object to it." }, { "code": null, "e": 2620, "s": 2569, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 2629, "s": 2620, "text": "Program:" }, { "code": "import java.util.HashSet;import java.util.Set;import java.util.TreeSet; public class GFG { public static void main(String[] args) { // Get the HashSet Set<String> setobj = new HashSet<>(); setobj.add(\"Welcome\"); setobj.add(\"To\"); setobj.add(\"Geeks\"); setobj.add(\"For\"); setobj.add(\"Geeks\"); System.out.println(\"HashSet: \" + setobj); // Convert the HashSet to TreeSet Set<String> hashSetToTreeSet = new TreeSet<>(setobj); // Print the TreeSet System.out.println(\"TreeSet: \" + hashSetToTreeSet); }}", "e": 3293, "s": 2629, "text": null }, { "code": null, "e": 3364, "s": 3293, "text": "HashSet: [Geeks, For, Welcome, To]\nTreeSet: [For, Geeks, To, Welcome]\n" }, { "code": null, "e": 4498, "s": 3364, "text": "By constructing a tree set containing the same elements present in the hash set by using addAll method.First, we have to create an object for the hash set.Then we have to add all the elements to the hash set.Now create an object for the treeset .Using addAll method add all elements of hash set to it.Below is the implementation of the above approach:Program:import java.util.HashSet;import java.util.Set;import java.util.TreeSet; public class GFG { public static void main(String[] args) { // Get the HashSet Set<String> setobj = new HashSet<>(); setobj.add(\"Welcome\"); setobj.add(\"To\"); setobj.add(\"Geeks\"); setobj.add(\"For\"); setobj.add(\"Geeks\"); System.out.println(\"HashSet: \" + setobj); // Convert the HashSet to TreeSet Set<String> hashSetToTreeSet = new TreeSet<>(); hashSetToTreeSet.addAll(setobj); // Print the TreeSet System.out.println(\"TreeSet: \" + hashSetToTreeSet); }}Output:HashSet: [Geeks, For, Welcome, To]\nTreeSet: [For, Geeks, To, Welcome]\n" }, { "code": null, "e": 4697, "s": 4498, "text": "First, we have to create an object for the hash set.Then we have to add all the elements to the hash set.Now create an object for the treeset .Using addAll method add all elements of hash set to it." }, { "code": null, "e": 4750, "s": 4697, "text": "First, we have to create an object for the hash set." }, { "code": null, "e": 4804, "s": 4750, "text": "Then we have to add all the elements to the hash set." }, { "code": null, "e": 4843, "s": 4804, "text": "Now create an object for the treeset ." }, { "code": null, "e": 4899, "s": 4843, "text": "Using addAll method add all elements of hash set to it." }, { "code": null, "e": 4950, "s": 4899, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 4959, "s": 4950, "text": "Program:" }, { "code": "import java.util.HashSet;import java.util.Set;import java.util.TreeSet; public class GFG { public static void main(String[] args) { // Get the HashSet Set<String> setobj = new HashSet<>(); setobj.add(\"Welcome\"); setobj.add(\"To\"); setobj.add(\"Geeks\"); setobj.add(\"For\"); setobj.add(\"Geeks\"); System.out.println(\"HashSet: \" + setobj); // Convert the HashSet to TreeSet Set<String> hashSetToTreeSet = new TreeSet<>(); hashSetToTreeSet.addAll(setobj); // Print the TreeSet System.out.println(\"TreeSet: \" + hashSetToTreeSet); }}", "e": 5657, "s": 4959, "text": null }, { "code": null, "e": 5728, "s": 5657, "text": "HashSet: [Geeks, For, Welcome, To]\nTreeSet: [For, Geeks, To, Welcome]\n" }, { "code": null, "e": 6930, "s": 5728, "text": "By using a for each loop.( This method is commonly used for conversion between two incompatible types.)First, we have to create an object for the hash set.Then we have to add all the elements to the hash set.Now create an object for the treeset .Finally, by using for each loop adding all elements of hash set to the tree set.Below is the implementation of the above approach:Program:import java.util.HashSet;import java.util.Set;import java.util.TreeSet; public class GFG { public static void main(String[] args) { // Get the HashSet Set<String> setobj = new HashSet<>(); setobj.add(\"Welcome\"); setobj.add(\"To\"); setobj.add(\"Geeks\"); setobj.add(\"For\"); setobj.add(\"Geeks\"); System.out.println(\"HashSet: \" + setobj); // Convert the HashSet to TreeSet Set<String> hashSetToTreeSet = new TreeSet<>(); for (String i : setobj) hashSetToTreeSet .add(i); // Print the TreeSet System.out.println(\"TreeSet: \" + hashSetToTreeSet); }}Output:HashSet: [Geeks, For, Welcome, To]\nTreeSet: [For, Geeks, To, Welcome]\n" }, { "code": null, "e": 7154, "s": 6930, "text": "First, we have to create an object for the hash set.Then we have to add all the elements to the hash set.Now create an object for the treeset .Finally, by using for each loop adding all elements of hash set to the tree set." }, { "code": null, "e": 7207, "s": 7154, "text": "First, we have to create an object for the hash set." }, { "code": null, "e": 7261, "s": 7207, "text": "Then we have to add all the elements to the hash set." }, { "code": null, "e": 7300, "s": 7261, "text": "Now create an object for the treeset ." }, { "code": null, "e": 7381, "s": 7300, "text": "Finally, by using for each loop adding all elements of hash set to the tree set." }, { "code": null, "e": 7432, "s": 7381, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 7441, "s": 7432, "text": "Program:" }, { "code": "import java.util.HashSet;import java.util.Set;import java.util.TreeSet; public class GFG { public static void main(String[] args) { // Get the HashSet Set<String> setobj = new HashSet<>(); setobj.add(\"Welcome\"); setobj.add(\"To\"); setobj.add(\"Geeks\"); setobj.add(\"For\"); setobj.add(\"Geeks\"); System.out.println(\"HashSet: \" + setobj); // Convert the HashSet to TreeSet Set<String> hashSetToTreeSet = new TreeSet<>(); for (String i : setobj) hashSetToTreeSet .add(i); // Print the TreeSet System.out.println(\"TreeSet: \" + hashSetToTreeSet); }}", "e": 8182, "s": 7441, "text": null }, { "code": null, "e": 8253, "s": 8182, "text": "HashSet: [Geeks, For, Welcome, To]\nTreeSet: [For, Geeks, To, Welcome]\n" }, { "code": null, "e": 8273, "s": 8253, "text": "Java - util package" }, { "code": null, "e": 8290, "s": 8273, "text": "Java-Collections" }, { "code": null, "e": 8303, "s": 8290, "text": "java-hashset" }, { "code": null, "e": 8321, "s": 8303, "text": "Java-Set-Programs" }, { "code": null, "e": 8334, "s": 8321, "text": "java-treeset" }, { "code": null, "e": 8341, "s": 8334, "text": "Picked" }, { "code": null, "e": 8346, "s": 8341, "text": "Java" }, { "code": null, "e": 8351, "s": 8346, "text": "Java" }, { "code": null, "e": 8368, "s": 8351, "text": "Java-Collections" }, { "code": null, "e": 8466, "s": 8368, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8481, "s": 8466, "text": "Arrays in Java" }, { "code": null, "e": 8525, "s": 8481, "text": "Split() String method in Java with examples" }, { "code": null, "e": 8561, "s": 8525, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 8612, "s": 8561, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 8637, "s": 8612, "text": "Reverse a string in Java" }, { "code": null, "e": 8659, "s": 8637, "text": "For-each loop in Java" }, { "code": null, "e": 8690, "s": 8659, "text": "How to iterate any Map in Java" }, { "code": null, "e": 8709, "s": 8690, "text": "Interfaces in Java" }, { "code": null, "e": 8739, "s": 8709, "text": "HashMap in Java with Examples" } ]
How to get the file size using PHP ?
22 Jan, 2021 In this article, we are going to discuss how to get the file size using PHP. PHP is a general-purpose scripting language that is suited for both server and client scripting language for website development. To get the file size, we will use filesize() function. The filesize() function returns the size of a file in bytes. This function accepts the filename as a parameter and returns the size of a file in bytes on success and False on failure. Syntax: filesize($filename) Parameters: The filesize() function in PHP accepts only one parameter i.e. $filename that specifies the filename of the file whose size that you want to check. Example 1: In this example, we use filesize() function with a file parameter and it returns the size of given file. PHP <?php echo "The File size is: "; echo filesize("gfg.txt"); ?> Output: The File size is: 15 Example 2: In this example, we use filesize() function with a non-existing file parameter then it returns an error message. PHP <?php echo "The File size is: "; echo filesize("gfg2.txt");?> Output: The File size is: Warning: filesize(): stat failed for inde1x.php in C:\xampp\htdocs\gfg.php on line 4 PHP-Misc Picked Technical Scripter 2020 PHP PHP Programs Technical Scripter Web Technologies Web technologies Questions PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to fetch data from localserver database and display on HTML table using PHP ? Difference between HTTP GET and POST Methods Different ways for passing data to view in Laravel PHP | file_exists( ) Function How to create admin login page using PHP? How to call PHP function on the click of a Button ? How to fetch data from localserver database and display on HTML table using PHP ? How to create admin login page using PHP? PHP | Ternary Operator How to send an email using PHPMailer ?
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Jan, 2021" }, { "code": null, "e": 291, "s": 28, "text": "In this article, we are going to discuss how to get the file size using PHP. PHP is a general-purpose scripting language that is suited for both server and client scripting language for website development. To get the file size, we will use filesize() function. " }, { "code": null, "e": 476, "s": 291, "text": "The filesize() function returns the size of a file in bytes. This function accepts the filename as a parameter and returns the size of a file in bytes on success and False on failure. " }, { "code": null, "e": 484, "s": 476, "text": "Syntax:" }, { "code": null, "e": 504, "s": 484, "text": "filesize($filename)" }, { "code": null, "e": 664, "s": 504, "text": "Parameters: The filesize() function in PHP accepts only one parameter i.e. $filename that specifies the filename of the file whose size that you want to check." }, { "code": null, "e": 780, "s": 664, "text": "Example 1: In this example, we use filesize() function with a file parameter and it returns the size of given file." }, { "code": null, "e": 784, "s": 780, "text": "PHP" }, { "code": "<?php echo \"The File size is: \"; echo filesize(\"gfg.txt\"); ?>", "e": 851, "s": 784, "text": null }, { "code": null, "e": 859, "s": 851, "text": "Output:" }, { "code": null, "e": 880, "s": 859, "text": "The File size is: 15" }, { "code": null, "e": 1004, "s": 880, "text": "Example 2: In this example, we use filesize() function with a non-existing file parameter then it returns an error message." }, { "code": null, "e": 1008, "s": 1004, "text": "PHP" }, { "code": "<?php echo \"The File size is: \"; echo filesize(\"gfg2.txt\");?>", "e": 1074, "s": 1008, "text": null }, { "code": null, "e": 1082, "s": 1074, "text": "Output:" }, { "code": null, "e": 1186, "s": 1082, "text": "The File size is: \nWarning: filesize(): stat failed for inde1x.php in\nC:\\xampp\\htdocs\\gfg.php on line 4" }, { "code": null, "e": 1195, "s": 1186, "text": "PHP-Misc" }, { "code": null, "e": 1202, "s": 1195, "text": "Picked" }, { "code": null, "e": 1226, "s": 1202, "text": "Technical Scripter 2020" }, { "code": null, "e": 1230, "s": 1226, "text": "PHP" }, { "code": null, "e": 1243, "s": 1230, "text": "PHP Programs" }, { "code": null, "e": 1262, "s": 1243, "text": "Technical Scripter" }, { "code": null, "e": 1279, "s": 1262, "text": "Web Technologies" }, { "code": null, "e": 1306, "s": 1279, "text": "Web technologies Questions" }, { "code": null, "e": 1310, "s": 1306, "text": "PHP" }, { "code": null, "e": 1408, "s": 1310, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1490, "s": 1408, "text": "How to fetch data from localserver database and display on HTML table using PHP ?" }, { "code": null, "e": 1535, "s": 1490, "text": "Difference between HTTP GET and POST Methods" }, { "code": null, "e": 1586, "s": 1535, "text": "Different ways for passing data to view in Laravel" }, { "code": null, "e": 1616, "s": 1586, "text": "PHP | file_exists( ) Function" }, { "code": null, "e": 1658, "s": 1616, "text": "How to create admin login page using PHP?" }, { "code": null, "e": 1710, "s": 1658, "text": "How to call PHP function on the click of a Button ?" }, { "code": null, "e": 1792, "s": 1710, "text": "How to fetch data from localserver database and display on HTML table using PHP ?" }, { "code": null, "e": 1834, "s": 1792, "text": "How to create admin login page using PHP?" }, { "code": null, "e": 1857, "s": 1834, "text": "PHP | Ternary Operator" } ]
Python OpenCV: Object Tracking using Homography
13 Sep, 2021 In this article, we are trying to track an object in the video with the image already given in it. We can also track the object in the image. Before seeing object tracking using homography let us know some basics. Homography is a transformation that maps the points in one point to the corresponding point in another image. The homography is a 3×3 matrix : If 2 points are not in the same plane then we have to use 2 homographs. Similarly, for n planes, we have to use n homographs. If we have more homographs then we need to handle all of them properly. So that is why we use feature matching. Importing Image Data : We will be reading the following image : Above image is the cover page of book and it is stored as ‘img.jpg’. Python # importing the required librariesimport cv2import numpy as np # reading image in grayscaleimg = cv2.imread("img.jpg", cv2.IMREAD_GRAYSCALE) # initializing web camcap = cv2.VideoCapture(0) Feature Matching : Feature matching means finding corresponding features from two similar datasets based on a search distance. Now will be using sift algorithm and flann type feature matching. Python # creating the SIFT algorithmsift = cv2.xfeatures2d.SIFT_create() # find the keypoints and descriptors with SIFTkp_image, desc_image =sift.detectAndCompute(img, None) # initializing the dictionaryindex_params = dict(algorithm = 0, trees = 5)search_params = dict() # by using Flann Matcherflann = cv2.FlannBasedMatcher(index_params, search_params) Now, we also have to convert the video capture into grayscale and by using appropriate matcher we have to match the points from image to the frame. Here, we may face exceptions when we draw matches because infinitely there will we many points on both planes. To handle such conditions we should consider only some points, to get some accurate points we can vary the distance barrier. Python # reading the frame_, frame = cap.read() # converting the frame into grayscalegrayframe = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # find the keypoints and descriptors with SIFTkp_grayframe, desc_grayframe = sift.detectAndCompute(grayframe, None) # finding nearest match with KNN algorithmmatches= flann.knnMatch(desc_image, desc_grayframe, k=2) # initialize list to keep track of only good pointsgood_points=[] for m, n in matches: #append the points according #to distance of descriptors if(m.distance < 0.6*n.distance): good_points.append(m) Homography : To detect the homography of the object we have to obtain the matrix and use function findHomography() to obtain the homograph of the object. Python # maintaining list of index of descriptors# in query descriptorsquery_pts = np.float32([kp_image[m.queryIdx] .pt for m in good_points]).reshape(-1, 1, 2) # maintaining list of index of descriptors# in train descriptorstrain_pts = np.float32([kp_grayframe[m.trainIdx] .pt for m in good_points]).reshape(-1, 1, 2) # finding perspective transformation# between two planesmatrix, mask = cv2.findHomography(query_pts, train_pts, cv2.RANSAC, 5.0) # ravel function returns# contiguous flattened arraymatches_mask = mask.ravel().tolist() Everything is done till now, but when we try to change or move the object in another direction then the computer cannot able to find its homograph to deal with this we have to use perspective transform. For example, humans can see near objects larger than far objects, here perspective is changing. This is called Perspective transform. Python # initializing height and width of the imageh, w = img.shape # saving all points in ptspts = np.float32([[0, 0], [0, h], [w, h], [w, 0]]) .reshape(-1, 1, 2) # applying perspective algorithmdst = cv2.perspectiveTransform(pts, matrix) At the end, lets see the output Python # using drawing function for the framehomography = cv2.polylines(frame, [np.int32(dst)], True, (255, 0, 0), 3) # showing the final output# with homographycv2.imshow("Homography", homography) Output : arorakashish0911 Python-OpenCV Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n13 Sep, 2021" }, { "code": null, "e": 266, "s": 52, "text": "In this article, we are trying to track an object in the video with the image already given in it. We can also track the object in the image. Before seeing object tracking using homography let us know some basics." }, { "code": null, "e": 409, "s": 266, "text": "Homography is a transformation that maps the points in one point to the corresponding point in another image. The homography is a 3×3 matrix :" }, { "code": null, "e": 647, "s": 409, "text": "If 2 points are not in the same plane then we have to use 2 homographs. Similarly, for n planes, we have to use n homographs. If we have more homographs then we need to handle all of them properly. So that is why we use feature matching." }, { "code": null, "e": 712, "s": 647, "text": "Importing Image Data : We will be reading the following image : " }, { "code": null, "e": 782, "s": 712, "text": "Above image is the cover page of book and it is stored as ‘img.jpg’. " }, { "code": null, "e": 789, "s": 782, "text": "Python" }, { "code": "# importing the required librariesimport cv2import numpy as np # reading image in grayscaleimg = cv2.imread(\"img.jpg\", cv2.IMREAD_GRAYSCALE) # initializing web camcap = cv2.VideoCapture(0)", "e": 978, "s": 789, "text": null }, { "code": null, "e": 1172, "s": 978, "text": "Feature Matching : Feature matching means finding corresponding features from two similar datasets based on a search distance. Now will be using sift algorithm and flann type feature matching. " }, { "code": null, "e": 1179, "s": 1172, "text": "Python" }, { "code": "# creating the SIFT algorithmsift = cv2.xfeatures2d.SIFT_create() # find the keypoints and descriptors with SIFTkp_image, desc_image =sift.detectAndCompute(img, None) # initializing the dictionaryindex_params = dict(algorithm = 0, trees = 5)search_params = dict() # by using Flann Matcherflann = cv2.FlannBasedMatcher(index_params, search_params)", "e": 1526, "s": 1179, "text": null }, { "code": null, "e": 1674, "s": 1526, "text": "Now, we also have to convert the video capture into grayscale and by using appropriate matcher we have to match the points from image to the frame." }, { "code": null, "e": 1910, "s": 1674, "text": "Here, we may face exceptions when we draw matches because infinitely there will we many points on both planes. To handle such conditions we should consider only some points, to get some accurate points we can vary the distance barrier." }, { "code": null, "e": 1917, "s": 1910, "text": "Python" }, { "code": "# reading the frame_, frame = cap.read() # converting the frame into grayscalegrayframe = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # find the keypoints and descriptors with SIFTkp_grayframe, desc_grayframe = sift.detectAndCompute(grayframe, None) # finding nearest match with KNN algorithmmatches= flann.knnMatch(desc_image, desc_grayframe, k=2) # initialize list to keep track of only good pointsgood_points=[] for m, n in matches: #append the points according #to distance of descriptors if(m.distance < 0.6*n.distance): good_points.append(m)", "e": 2477, "s": 1917, "text": null }, { "code": null, "e": 2632, "s": 2477, "text": "Homography : To detect the homography of the object we have to obtain the matrix and use function findHomography() to obtain the homograph of the object. " }, { "code": null, "e": 2639, "s": 2632, "text": "Python" }, { "code": "# maintaining list of index of descriptors# in query descriptorsquery_pts = np.float32([kp_image[m.queryIdx] .pt for m in good_points]).reshape(-1, 1, 2) # maintaining list of index of descriptors# in train descriptorstrain_pts = np.float32([kp_grayframe[m.trainIdx] .pt for m in good_points]).reshape(-1, 1, 2) # finding perspective transformation# between two planesmatrix, mask = cv2.findHomography(query_pts, train_pts, cv2.RANSAC, 5.0) # ravel function returns# contiguous flattened arraymatches_mask = mask.ravel().tolist()", "e": 3202, "s": 2639, "text": null }, { "code": null, "e": 3539, "s": 3202, "text": "Everything is done till now, but when we try to change or move the object in another direction then the computer cannot able to find its homograph to deal with this we have to use perspective transform. For example, humans can see near objects larger than far objects, here perspective is changing. This is called Perspective transform." }, { "code": null, "e": 3546, "s": 3539, "text": "Python" }, { "code": "# initializing height and width of the imageh, w = img.shape # saving all points in ptspts = np.float32([[0, 0], [0, h], [w, h], [w, 0]]) .reshape(-1, 1, 2) # applying perspective algorithmdst = cv2.perspectiveTransform(pts, matrix)", "e": 3790, "s": 3546, "text": null }, { "code": null, "e": 3823, "s": 3790, "text": "At the end, lets see the output " }, { "code": null, "e": 3830, "s": 3823, "text": "Python" }, { "code": "# using drawing function for the framehomography = cv2.polylines(frame, [np.int32(dst)], True, (255, 0, 0), 3) # showing the final output# with homographycv2.imshow(\"Homography\", homography)", "e": 4021, "s": 3830, "text": null }, { "code": null, "e": 4031, "s": 4021, "text": "Output : " }, { "code": null, "e": 4050, "s": 4033, "text": "arorakashish0911" }, { "code": null, "e": 4064, "s": 4050, "text": "Python-OpenCV" }, { "code": null, "e": 4071, "s": 4064, "text": "Python" } ]
Print the longest palindromic prefix of a given string
07 Jul, 2021 Given a string str, the task is to find the longest palindromic prefix of the given string. Examples: Input: str = “abaac” Output: aba Explanation: The longest prefix of the given string which is palindromic is “aba”. Input: str = “abacabaxyz” Output: abacaba Explanation: The prefixes of the given string which is palindromic are “aba” and “abacabaxyz”. But the longest of among two is “abacabaxyz”. Naive Approach: The idea is to generate all the substring of the given string from the starting index and check whether the substrings are palindromic or not. The palindromic string with a maximum length is the resultant string. 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 longest prefix// which is palindromicvoid LongestPalindromicPrefix(string s){ // Find the length of the given string int n = s.length(); // For storing the length of longest // prefix palindrome int max_len = 0; // Loop to check the substring of all // length from 1 to N which is palindrome for (int len = 1; len <= n; len++) { // String of length i string temp = s.substr(0, len); // To store the reversed of temp string temp2 = temp; // Reversing string temp2 reverse(temp2.begin(), temp2.end()); // If string temp is palindromic // then update the length if (temp == temp2) { max_len = len; } } // Print the palindromic string of // max_len cout << s.substr(0, max_len);} // Driver Codeint main(){ // Given string string str = "abaab"; // Function Call LongestPalindromicPrefix(str);} // Java program for the above approachimport java.util.*;class GFG{ // Function to find the longest prefix// which is palindromicstatic void LongestPalindromicPrefix(String s){ // Find the length of the given String int n = s.length(); // For storing the length of longest // prefix palindrome int max_len = 0; // Loop to check the subString of all // length from 1 to N which is palindrome for (int len = 1; len <= n; len++) { // String of length i String temp = s.substring(0, len); // To store the reversed of temp String temp2 = temp; // Reversing String temp2 temp2 = reverse(temp2); // If String temp is palindromic // then update the length if (temp.equals(temp2)) { max_len = len; } } // Print the palindromic String of // max_len System.out.print(s.substring(0, max_len));} static String reverse(String input){ char[] a = input.toCharArray(); int l, r = a.length - 1; for (l = 0; l < r; l++, r--) { char temp = a[l]; a[l] = a[r]; a[r] = temp; } return String.valueOf(a);} // Driver Codepublic static void main(String[] args){ // Given String String str = "abaab"; // Function Call LongestPalindromicPrefix(str);}} // This code is contributed by Rajput-Ji # Python3 program for the above approach # Function to find the longest prefix# which is palindromedef LongestPalindromicPrefix(string): # Find the length of the given string n = len(string) # For storing the length of longest # Prefix Palindrome max_len = 0 # Loop to check the substring of all # length from 1 to n which is palindrome for length in range(0, n + 1): # String of length i temp = string[0:length] # To store the value of temp temp2 = temp # Reversing the value of temp temp3 = temp2[::-1] # If string temp is palindromic # then update the length if temp == temp3: max_len = length # Print the palindromic string # of max_len print(string[0:max_len]) # Driver codeif __name__ == '__main__' : string = "abaac"; # Function call LongestPalindromicPrefix(string) # This code is contributed by virusbuddah_ // C# program for the above approachusing System; class GFG{ // Function to find the longest prefix// which is palindromicstatic void longestPalindromicPrefix(String s){ // Find the length of the given String int n = s.Length; // For storing the length of longest // prefix palindrome int max_len = 0; // Loop to check the subString of all // length from 1 to N which is palindrome for (int len = 1; len <= n; len++) { // String of length i String temp = s.Substring(0, len); // To store the reversed of temp String temp2 = temp; // Reversing String temp2 temp2 = reverse(temp2); // If String temp is palindromic // then update the length if (temp.Equals(temp2)) { max_len = len; } } // Print the palindromic String of // max_len Console.Write(s.Substring(0, max_len));} static String reverse(String input){ char[] a = input.ToCharArray(); int l, r = a.Length - 1; for (l = 0; l < r; l++, r--) { char temp = a[l]; a[l] = a[r]; a[r] = temp; } return String.Join("",a);} // Driver Codepublic static void Main(String[] args){ // Given String String str = "abaab"; // Function Call longestPalindromicPrefix(str);}} // This code is contributed by amal kumar choubey <script> // JavaScript program for the above approach // Function to find the longest prefix // which is palindromic function LongestPalindromicPrefix(s) { // Find the length of the given String let n = s.length; // For storing the length of longest // prefix palindrome let max_len = 0; // Loop to check the subString of all // length from 1 to N which is palindrome for (let len = 1; len <= n; len++) { // String of length i let temp = s.substring(0, len); // To store the reversed of temp let temp2 = temp; // Reversing String temp2 temp2 = reverse(temp2); // If String temp is palindromic // then update the length if (temp == temp2) { max_len = len; } } // Print the palindromic String of // max_len document.write(s.substring(0, max_len)); } function reverse(input) { let a = input.split(''); let l, r = a.length - 1; for (l = 0; l < r; l++, r--) { let temp = a[l]; a[l] = a[r]; a[r] = temp; } return a.join(""); } // Given String let str = "abaab"; // Function Call LongestPalindromicPrefix(str); </script> aba Time Complexity: O(N2), where N is the length of the given string. Efficient Approach: The idea is to use preprocessing algorithm KMP Algorithm. Below are the steps: Create a temporary string(say str2) which is: str2 = str + '?' reverse(str); Create an array(say lps[]) of size of length of the string str2 which will store the longest palindromic prefix which is also a suffix of string str2. Update the lps[] by using preprocessing algorithm of KMP Search Algorithm. lps[length(str2) – 1] will give the length of the longest palindromic prefix string of the given string str. 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 longest prefix// which is palindromicvoid LongestPalindromicPrefix(string str){ // Create temporary string string temp = str + '?'; // Reverse the string str reverse(str.begin(), str.end()); // Append string str to temp temp += str; // Find the length of string temp int n = temp.length(); // lps[] array for string temp int lps[n]; // Initialise every value with zero fill(lps, lps + n, 0); // Iterate the string temp for (int i = 1; i < n; i++) { // Length of longest prefix // till less than i int len = lps[i - 1]; // Calculate length for i+1 while (len > 0 && temp[len] != temp[i]) { len = lps[len - 1]; } // If character at current index // len are same then increment // length by 1 if (temp[i] == temp[len]) { len++; } // Update the length at current // index to len lps[i] = len; } // Print the palindromic string of // max_len cout << temp.substr(0, lps[n - 1]);} // Driver's Codeint main(){ // Given string string str = "abaab"; // Function Call LongestPalindromicPrefix(str);} // Java program for the above approachimport java.util.*; class GFG{ // Function to find the longest// prefix which is palindromicstatic void LongestPalindromicPrefix(String str){ // Create temporary String String temp = str + '?'; // Reverse the String str str = reverse(str); // Append String str to temp temp += str; // Find the length of String temp int n = temp.length(); // lps[] array for String temp int []lps = new int[n]; // Initialise every value with zero Arrays.fill(lps, 0); // Iterate the String temp for(int i = 1; i < n; i++) { // Length of longest prefix // till less than i int len = lps[i - 1]; // Calculate length for i+1 while (len > 0 && temp.charAt(len) != temp.charAt(i)) { len = lps[len - 1]; } // If character at current index // len are same then increment // length by 1 if (temp.charAt(i) == temp.charAt(len)) { len++; } // Update the length at current // index to len lps[i] = len; } // Print the palindromic String // of max_len System.out.print(temp.substring(0, lps[n - 1]));} static String reverse(String input){ char[] a = input.toCharArray(); int l, r = a.length - 1; for(l = 0; l < r; l++, r--) { char temp = a[l]; a[l] = a[r]; a[r] = temp; } return String.valueOf(a);} // Driver Codepublic static void main(String[] args){ // Given String String str = "abaab"; // Function Call LongestPalindromicPrefix(str);}} // This code is contributed by Rajput-Ji # Python3 program for the above approach # Function to find the longest prefix# which is palindromicdef LongestPalindromicPrefix(Str): # Create temporary string temp = Str + "?" # Reverse the string Str Str = Str[::-1] # Append string Str to temp temp = temp + Str # Find the length of string temp n = len(temp) # lps[] array for string temp lps = [0] * n # Iterate the string temp for i in range(1, n): # Length of longest prefix # till less than i Len = lps[i - 1] # Calculate length for i+1 while (Len > 0 and temp[Len] != temp[i]): Len = lps[Len - 1] # If character at current index # Len are same then increment # length by 1 if (temp[i] == temp[Len]): Len += 1 # Update the length at current # index to Len lps[i] = Len # Print the palindromic string # of max_len print(temp[0 : lps[n - 1]]) # Driver Codeif __name__ == '__main__': # Given string Str = "abaab" # Function call LongestPalindromicPrefix(Str) # This code is contributed by himanshu77 // C# program for the above approachusing System; class GFG{ // Function to find the longest// prefix which is palindromicstatic void longestPalindromicPrefix(String str){ // Create temporary String String temp = str + '?'; // Reverse the String str str = reverse(str); // Append String str to temp temp += str; // Find the length of String temp int n = temp.Length; // lps[] array for String temp int []lps = new int[n]; // Iterate the String temp for(int i = 1; i < n; i++) { // Length of longest prefix // till less than i int len = lps[i - 1]; // Calculate length for i+1 while (len > 0 && temp[len] != temp[i]) { len = lps[len - 1]; } // If character at current index // len are same then increment // length by 1 if (temp[i] == temp[len]) { len++; } // Update the length at current // index to len lps[i] = len; } // Print the palindromic String // of max_len Console.Write(temp.Substring(0, lps[n - 1]));} static String reverse(String input){ char[] a = input.ToCharArray(); int l, r = a.Length - 1; for(l = 0; l < r; l++, r--) { char temp = a[l]; a[l] = a[r]; a[r] = temp; } return String.Join("", a);} // Driver Codepublic static void Main(String[] args){ // Given String String str = "abaab"; // Function Call longestPalindromicPrefix(str);}} // This code is contributed by Rajput-Ji <script> // Javascript program for the above approach // Function to find the longest// prefix which is palindromicfunction longestPalindromicPrefix(str){ // Create temporary String let temp = str + '?'; // Reverse the String str str = reverse(str); // Append String str to temp temp += str; // Find the length of String temp let n = temp.length; // lps[] array for String temp let lps = new Array(n); lps.fill(0); // Iterate the String temp for(let i = 1; i < n; i++) { // Length of longest prefix // till less than i let len = lps[i - 1]; // Calculate length for i+1 while (len > 0 && temp[len] != temp[i]) { len = lps[len - 1]; } // If character at current index // len are same then increment // length by 1 if (temp[i] == temp[len]) { len++; } // Update the length at current // index to len lps[i] = len; } // Print the palindromic String // of max_len document.write(temp.substring(0, lps[n - 1]));} function reverse(input){ let a = input.split(''); let l, r = a.length - 1; for(l = 0; l < r; l++, r--) { let temp = a[l]; a[l] = a[r]; a[r] = temp; } return a.join("");} // Driver code // Given Stringlet str = "abaab"; // Function CalllongestPalindromicPrefix(str); // This code is contributed by mukesh07 </script> aba Time Complexity: O(N), where N is the length of the given string. Auxiliary Space: O(N), where N is the length of the given string. Rajput-Ji virusbuddha Amal Kumar Choubey himanshu77 sooda367 suresh07 mukesh07 ruhelaa48 gabaa406 palindrome prefix Strings Strings palindrome Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n07 Jul, 2021" }, { "code": null, "e": 144, "s": 52, "text": "Given a string str, the task is to find the longest palindromic prefix of the given string." }, { "code": null, "e": 155, "s": 144, "text": "Examples: " }, { "code": null, "e": 271, "s": 155, "text": "Input: str = “abaac” Output: aba Explanation: The longest prefix of the given string which is palindromic is “aba”." }, { "code": null, "e": 456, "s": 271, "text": "Input: str = “abacabaxyz” Output: abacaba Explanation: The prefixes of the given string which is palindromic are “aba” and “abacabaxyz”. But the longest of among two is “abacabaxyz”. " }, { "code": null, "e": 685, "s": 456, "text": "Naive Approach: The idea is to generate all the substring of the given string from the starting index and check whether the substrings are palindromic or not. The palindromic string with a maximum length is the resultant string." }, { "code": null, "e": 737, "s": 685, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 741, "s": 737, "text": "C++" }, { "code": null, "e": 746, "s": 741, "text": "Java" }, { "code": null, "e": 754, "s": 746, "text": "Python3" }, { "code": null, "e": 757, "s": 754, "text": "C#" }, { "code": null, "e": 768, "s": 757, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the longest prefix// which is palindromicvoid LongestPalindromicPrefix(string s){ // Find the length of the given string int n = s.length(); // For storing the length of longest // prefix palindrome int max_len = 0; // Loop to check the substring of all // length from 1 to N which is palindrome for (int len = 1; len <= n; len++) { // String of length i string temp = s.substr(0, len); // To store the reversed of temp string temp2 = temp; // Reversing string temp2 reverse(temp2.begin(), temp2.end()); // If string temp is palindromic // then update the length if (temp == temp2) { max_len = len; } } // Print the palindromic string of // max_len cout << s.substr(0, max_len);} // Driver Codeint main(){ // Given string string str = \"abaab\"; // Function Call LongestPalindromicPrefix(str);}", "e": 1802, "s": 768, "text": null }, { "code": "// Java program for the above approachimport java.util.*;class GFG{ // Function to find the longest prefix// which is palindromicstatic void LongestPalindromicPrefix(String s){ // Find the length of the given String int n = s.length(); // For storing the length of longest // prefix palindrome int max_len = 0; // Loop to check the subString of all // length from 1 to N which is palindrome for (int len = 1; len <= n; len++) { // String of length i String temp = s.substring(0, len); // To store the reversed of temp String temp2 = temp; // Reversing String temp2 temp2 = reverse(temp2); // If String temp is palindromic // then update the length if (temp.equals(temp2)) { max_len = len; } } // Print the palindromic String of // max_len System.out.print(s.substring(0, max_len));} static String reverse(String input){ char[] a = input.toCharArray(); int l, r = a.length - 1; for (l = 0; l < r; l++, r--) { char temp = a[l]; a[l] = a[r]; a[r] = temp; } return String.valueOf(a);} // Driver Codepublic static void main(String[] args){ // Given String String str = \"abaab\"; // Function Call LongestPalindromicPrefix(str);}} // This code is contributed by Rajput-Ji", "e": 3154, "s": 1802, "text": null }, { "code": "# Python3 program for the above approach # Function to find the longest prefix# which is palindromedef LongestPalindromicPrefix(string): # Find the length of the given string n = len(string) # For storing the length of longest # Prefix Palindrome max_len = 0 # Loop to check the substring of all # length from 1 to n which is palindrome for length in range(0, n + 1): # String of length i temp = string[0:length] # To store the value of temp temp2 = temp # Reversing the value of temp temp3 = temp2[::-1] # If string temp is palindromic # then update the length if temp == temp3: max_len = length # Print the palindromic string # of max_len print(string[0:max_len]) # Driver codeif __name__ == '__main__' : string = \"abaac\"; # Function call LongestPalindromicPrefix(string) # This code is contributed by virusbuddah_", "e": 4157, "s": 3154, "text": null }, { "code": "// C# program for the above approachusing System; class GFG{ // Function to find the longest prefix// which is palindromicstatic void longestPalindromicPrefix(String s){ // Find the length of the given String int n = s.Length; // For storing the length of longest // prefix palindrome int max_len = 0; // Loop to check the subString of all // length from 1 to N which is palindrome for (int len = 1; len <= n; len++) { // String of length i String temp = s.Substring(0, len); // To store the reversed of temp String temp2 = temp; // Reversing String temp2 temp2 = reverse(temp2); // If String temp is palindromic // then update the length if (temp.Equals(temp2)) { max_len = len; } } // Print the palindromic String of // max_len Console.Write(s.Substring(0, max_len));} static String reverse(String input){ char[] a = input.ToCharArray(); int l, r = a.Length - 1; for (l = 0; l < r; l++, r--) { char temp = a[l]; a[l] = a[r]; a[r] = temp; } return String.Join(\"\",a);} // Driver Codepublic static void Main(String[] args){ // Given String String str = \"abaab\"; // Function Call longestPalindromicPrefix(str);}} // This code is contributed by amal kumar choubey", "e": 5506, "s": 4157, "text": null }, { "code": "<script> // JavaScript program for the above approach // Function to find the longest prefix // which is palindromic function LongestPalindromicPrefix(s) { // Find the length of the given String let n = s.length; // For storing the length of longest // prefix palindrome let max_len = 0; // Loop to check the subString of all // length from 1 to N which is palindrome for (let len = 1; len <= n; len++) { // String of length i let temp = s.substring(0, len); // To store the reversed of temp let temp2 = temp; // Reversing String temp2 temp2 = reverse(temp2); // If String temp is palindromic // then update the length if (temp == temp2) { max_len = len; } } // Print the palindromic String of // max_len document.write(s.substring(0, max_len)); } function reverse(input) { let a = input.split(''); let l, r = a.length - 1; for (l = 0; l < r; l++, r--) { let temp = a[l]; a[l] = a[r]; a[r] = temp; } return a.join(\"\"); } // Given String let str = \"abaab\"; // Function Call LongestPalindromicPrefix(str); </script>", "e": 6883, "s": 5506, "text": null }, { "code": null, "e": 6887, "s": 6883, "text": "aba" }, { "code": null, "e": 6956, "s": 6889, "text": "Time Complexity: O(N2), where N is the length of the given string." }, { "code": null, "e": 7056, "s": 6956, "text": "Efficient Approach: The idea is to use preprocessing algorithm KMP Algorithm. Below are the steps: " }, { "code": null, "e": 7102, "s": 7056, "text": "Create a temporary string(say str2) which is:" }, { "code": null, "e": 7133, "s": 7102, "text": "str2 = str + '?' reverse(str);" }, { "code": null, "e": 7284, "s": 7133, "text": "Create an array(say lps[]) of size of length of the string str2 which will store the longest palindromic prefix which is also a suffix of string str2." }, { "code": null, "e": 7359, "s": 7284, "text": "Update the lps[] by using preprocessing algorithm of KMP Search Algorithm." }, { "code": null, "e": 7468, "s": 7359, "text": "lps[length(str2) – 1] will give the length of the longest palindromic prefix string of the given string str." }, { "code": null, "e": 7520, "s": 7468, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 7524, "s": 7520, "text": "C++" }, { "code": null, "e": 7529, "s": 7524, "text": "Java" }, { "code": null, "e": 7537, "s": 7529, "text": "Python3" }, { "code": null, "e": 7540, "s": 7537, "text": "C#" }, { "code": null, "e": 7551, "s": 7540, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the longest prefix// which is palindromicvoid LongestPalindromicPrefix(string str){ // Create temporary string string temp = str + '?'; // Reverse the string str reverse(str.begin(), str.end()); // Append string str to temp temp += str; // Find the length of string temp int n = temp.length(); // lps[] array for string temp int lps[n]; // Initialise every value with zero fill(lps, lps + n, 0); // Iterate the string temp for (int i = 1; i < n; i++) { // Length of longest prefix // till less than i int len = lps[i - 1]; // Calculate length for i+1 while (len > 0 && temp[len] != temp[i]) { len = lps[len - 1]; } // If character at current index // len are same then increment // length by 1 if (temp[i] == temp[len]) { len++; } // Update the length at current // index to len lps[i] = len; } // Print the palindromic string of // max_len cout << temp.substr(0, lps[n - 1]);} // Driver's Codeint main(){ // Given string string str = \"abaab\"; // Function Call LongestPalindromicPrefix(str);}", "e": 8860, "s": 7551, "text": null }, { "code": "// Java program for the above approachimport java.util.*; class GFG{ // Function to find the longest// prefix which is palindromicstatic void LongestPalindromicPrefix(String str){ // Create temporary String String temp = str + '?'; // Reverse the String str str = reverse(str); // Append String str to temp temp += str; // Find the length of String temp int n = temp.length(); // lps[] array for String temp int []lps = new int[n]; // Initialise every value with zero Arrays.fill(lps, 0); // Iterate the String temp for(int i = 1; i < n; i++) { // Length of longest prefix // till less than i int len = lps[i - 1]; // Calculate length for i+1 while (len > 0 && temp.charAt(len) != temp.charAt(i)) { len = lps[len - 1]; } // If character at current index // len are same then increment // length by 1 if (temp.charAt(i) == temp.charAt(len)) { len++; } // Update the length at current // index to len lps[i] = len; } // Print the palindromic String // of max_len System.out.print(temp.substring(0, lps[n - 1]));} static String reverse(String input){ char[] a = input.toCharArray(); int l, r = a.length - 1; for(l = 0; l < r; l++, r--) { char temp = a[l]; a[l] = a[r]; a[r] = temp; } return String.valueOf(a);} // Driver Codepublic static void main(String[] args){ // Given String String str = \"abaab\"; // Function Call LongestPalindromicPrefix(str);}} // This code is contributed by Rajput-Ji", "e": 10544, "s": 8860, "text": null }, { "code": "# Python3 program for the above approach # Function to find the longest prefix# which is palindromicdef LongestPalindromicPrefix(Str): # Create temporary string temp = Str + \"?\" # Reverse the string Str Str = Str[::-1] # Append string Str to temp temp = temp + Str # Find the length of string temp n = len(temp) # lps[] array for string temp lps = [0] * n # Iterate the string temp for i in range(1, n): # Length of longest prefix # till less than i Len = lps[i - 1] # Calculate length for i+1 while (Len > 0 and temp[Len] != temp[i]): Len = lps[Len - 1] # If character at current index # Len are same then increment # length by 1 if (temp[i] == temp[Len]): Len += 1 # Update the length at current # index to Len lps[i] = Len # Print the palindromic string # of max_len print(temp[0 : lps[n - 1]]) # Driver Codeif __name__ == '__main__': # Given string Str = \"abaab\" # Function call LongestPalindromicPrefix(Str) # This code is contributed by himanshu77", "e": 11678, "s": 10544, "text": null }, { "code": "// C# program for the above approachusing System; class GFG{ // Function to find the longest// prefix which is palindromicstatic void longestPalindromicPrefix(String str){ // Create temporary String String temp = str + '?'; // Reverse the String str str = reverse(str); // Append String str to temp temp += str; // Find the length of String temp int n = temp.Length; // lps[] array for String temp int []lps = new int[n]; // Iterate the String temp for(int i = 1; i < n; i++) { // Length of longest prefix // till less than i int len = lps[i - 1]; // Calculate length for i+1 while (len > 0 && temp[len] != temp[i]) { len = lps[len - 1]; } // If character at current index // len are same then increment // length by 1 if (temp[i] == temp[len]) { len++; } // Update the length at current // index to len lps[i] = len; } // Print the palindromic String // of max_len Console.Write(temp.Substring(0, lps[n - 1]));} static String reverse(String input){ char[] a = input.ToCharArray(); int l, r = a.Length - 1; for(l = 0; l < r; l++, r--) { char temp = a[l]; a[l] = a[r]; a[r] = temp; } return String.Join(\"\", a);} // Driver Codepublic static void Main(String[] args){ // Given String String str = \"abaab\"; // Function Call longestPalindromicPrefix(str);}} // This code is contributed by Rajput-Ji", "e": 13241, "s": 11678, "text": null }, { "code": "<script> // Javascript program for the above approach // Function to find the longest// prefix which is palindromicfunction longestPalindromicPrefix(str){ // Create temporary String let temp = str + '?'; // Reverse the String str str = reverse(str); // Append String str to temp temp += str; // Find the length of String temp let n = temp.length; // lps[] array for String temp let lps = new Array(n); lps.fill(0); // Iterate the String temp for(let i = 1; i < n; i++) { // Length of longest prefix // till less than i let len = lps[i - 1]; // Calculate length for i+1 while (len > 0 && temp[len] != temp[i]) { len = lps[len - 1]; } // If character at current index // len are same then increment // length by 1 if (temp[i] == temp[len]) { len++; } // Update the length at current // index to len lps[i] = len; } // Print the palindromic String // of max_len document.write(temp.substring(0, lps[n - 1]));} function reverse(input){ let a = input.split(''); let l, r = a.length - 1; for(l = 0; l < r; l++, r--) { let temp = a[l]; a[l] = a[r]; a[r] = temp; } return a.join(\"\");} // Driver code // Given Stringlet str = \"abaab\"; // Function CalllongestPalindromicPrefix(str); // This code is contributed by mukesh07 </script>", "e": 14739, "s": 13241, "text": null }, { "code": null, "e": 14743, "s": 14739, "text": "aba" }, { "code": null, "e": 14878, "s": 14745, "text": "Time Complexity: O(N), where N is the length of the given string. Auxiliary Space: O(N), where N is the length of the given string. " }, { "code": null, "e": 14888, "s": 14878, "text": "Rajput-Ji" }, { "code": null, "e": 14900, "s": 14888, "text": "virusbuddha" }, { "code": null, "e": 14919, "s": 14900, "text": "Amal Kumar Choubey" }, { "code": null, "e": 14930, "s": 14919, "text": "himanshu77" }, { "code": null, "e": 14939, "s": 14930, "text": "sooda367" }, { "code": null, "e": 14948, "s": 14939, "text": "suresh07" }, { "code": null, "e": 14957, "s": 14948, "text": "mukesh07" }, { "code": null, "e": 14967, "s": 14957, "text": "ruhelaa48" }, { "code": null, "e": 14976, "s": 14967, "text": "gabaa406" }, { "code": null, "e": 14987, "s": 14976, "text": "palindrome" }, { "code": null, "e": 14994, "s": 14987, "text": "prefix" }, { "code": null, "e": 15002, "s": 14994, "text": "Strings" }, { "code": null, "e": 15010, "s": 15002, "text": "Strings" }, { "code": null, "e": 15021, "s": 15010, "text": "palindrome" } ]
Wissen Interview Experience | Set 1 (On-Campus)
20 Sep, 2016 Wissen technology part of wissen Infotech came to our college for campus drive.Website- www.wissen.com Round 1- written test -1.5 hrs6 coding questions1. Find intersection of 2 sorted arrays. Note: required O(n) and no use of data structure. 2. Stock – buy and sell to gain max profit. You have to buy and sell stocks onceInput- 1 2 20 5 6O/p – 19(20-1) 3. Print Reverse linkedlist without changing linkedlist. Note: required O(n) 4. Find whether number is cube root or not with out using math lib functions. Note: required O(n) (Hint binary search) 5. Replace 3 with 5 in an integer with out converting int to string conversionInput- 134Output – 154 6. Check whether 2 strings are anagram of each other.Eg – abc & backOutput – anagramNote- required O(n)(Hint : use map) Round 2 – tech11. Data structure– detect Loop in linkedlist– check whether a binary tree is binary search tree or not 2. JAVAMultithreading and synchronization 3. OSprocess, threads, semaphore, mutex, deadlock and starvation 4. DBMSHow will you print all tuples of a table?What is foreign key and some questions on it. Round 3- tech21.C++– write struct for generic linkedlist– dangling pointer and steps to removeEg- struct node { void *data; node *next; } main() { node *p = new node; p->data = (int) new int; delete p; } remove dangling pointer caused by void* data.Ans – overload delete operator– destructor can be overload or notIf yes or no , why-Why constructor can be overloaded? -Explain whole project which is mentioned in ur resumeWhich data structure did you used on ur project apart of arraySince I told him I didn’t used at specific data structure externally but internally MySQL use B+ and B tree for indexing internally– what is B+ and B tree (I didnt know abt B+) 2. DBMS-joins and write below queryStudent tableId l name l deptIdDepartment tabledeptId l HODname Find the name of HOD who has more number of studentsHint- nested query / join – Given matrix 2*2 , 2*3 and 3*3how will u store in single table in database 3. JavaCollection and synchronization 4. Data structure– create special stack in which you can find min element in O(1)– Do you have any question? Some Questions which was asked to others-quicksort-arraylist vs linkedlist-heap memory vs stack memory-if u have given names of people and their respective countries and I need to access all names of a particular country by O(1)Ans- map> Round 4 – HRTypical HR questions If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Wissen Interview Experiences Wissen Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Amazon Interview Experience for SDE 1 Amazon Interview Experience SDE-2 (3 Years Experienced) Google Interview Questions Write It Up: Share Your Interview Experiences Samsung Interview Experience Research & Institute SRIB (Off-Campus) 2022 Amazon Interview Experience for SDE-1 Google SWE Interview Experience (Google Online Coding Challenge) 2022 Nagarro Interview Experience Tiger Analytics Interview Experience for Data Analyst (On-Campus) Goldman Sachs Interview Experience for FTE ( On-Campus) Virtual 2021-22
[ { "code": null, "e": 52, "s": 24, "text": "\n20 Sep, 2016" }, { "code": null, "e": 155, "s": 52, "text": "Wissen technology part of wissen Infotech came to our college for campus drive.Website- www.wissen.com" }, { "code": null, "e": 294, "s": 155, "text": "Round 1- written test -1.5 hrs6 coding questions1. Find intersection of 2 sorted arrays. Note: required O(n) and no use of data structure." }, { "code": null, "e": 406, "s": 294, "text": "2. Stock – buy and sell to gain max profit. You have to buy and sell stocks onceInput- 1 2 20 5 6O/p – 19(20-1)" }, { "code": null, "e": 483, "s": 406, "text": "3. Print Reverse linkedlist without changing linkedlist. Note: required O(n)" }, { "code": null, "e": 602, "s": 483, "text": "4. Find whether number is cube root or not with out using math lib functions. Note: required O(n) (Hint binary search)" }, { "code": null, "e": 703, "s": 602, "text": "5. Replace 3 with 5 in an integer with out converting int to string conversionInput- 134Output – 154" }, { "code": null, "e": 823, "s": 703, "text": "6. Check whether 2 strings are anagram of each other.Eg – abc & backOutput – anagramNote- required O(n)(Hint : use map)" }, { "code": null, "e": 941, "s": 823, "text": "Round 2 – tech11. Data structure– detect Loop in linkedlist– check whether a binary tree is binary search tree or not" }, { "code": null, "e": 983, "s": 941, "text": "2. JAVAMultithreading and synchronization" }, { "code": null, "e": 1048, "s": 983, "text": "3. OSprocess, threads, semaphore, mutex, deadlock and starvation" }, { "code": null, "e": 1142, "s": 1048, "text": "4. DBMSHow will you print all tuples of a table?What is foreign key and some questions on it." }, { "code": null, "e": 1240, "s": 1142, "text": "Round 3- tech21.C++– write struct for generic linkedlist– dangling pointer and steps to removeEg-" }, { "code": null, "e": 1364, "s": 1240, "text": "struct node\n{\n void *data;\n node *next;\n}\nmain()\n{\n node *p = new node;\n p->data = (int) new int;\n delete p;\n}" }, { "code": null, "e": 1528, "s": 1364, "text": "remove dangling pointer caused by void* data.Ans – overload delete operator– destructor can be overload or notIf yes or no , why-Why constructor can be overloaded?" }, { "code": null, "e": 1821, "s": 1528, "text": "-Explain whole project which is mentioned in ur resumeWhich data structure did you used on ur project apart of arraySince I told him I didn’t used at specific data structure externally but internally MySQL use B+ and B tree for indexing internally– what is B+ and B tree (I didnt know abt B+)" }, { "code": null, "e": 1920, "s": 1821, "text": "2. DBMS-joins and write below queryStudent tableId l name l deptIdDepartment tabledeptId l HODname" }, { "code": null, "e": 1998, "s": 1920, "text": "Find the name of HOD who has more number of studentsHint- nested query / join" }, { "code": null, "e": 2075, "s": 1998, "text": "– Given matrix 2*2 , 2*3 and 3*3how will u store in single table in database" }, { "code": null, "e": 2113, "s": 2075, "text": "3. JavaCollection and synchronization" }, { "code": null, "e": 2222, "s": 2113, "text": "4. Data structure– create special stack in which you can find min element in O(1)– Do you have any question?" }, { "code": null, "e": 2460, "s": 2222, "text": "Some Questions which was asked to others-quicksort-arraylist vs linkedlist-heap memory vs stack memory-if u have given names of people and their respective countries and I need to access all names of a particular country by O(1)Ans- map>" }, { "code": null, "e": 2493, "s": 2460, "text": "Round 4 – HRTypical HR questions" }, { "code": null, "e": 2714, "s": 2493, "text": "If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 2721, "s": 2714, "text": "Wissen" }, { "code": null, "e": 2743, "s": 2721, "text": "Interview Experiences" }, { "code": null, "e": 2750, "s": 2743, "text": "Wissen" }, { "code": null, "e": 2848, "s": 2750, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2886, "s": 2848, "text": "Amazon Interview Experience for SDE 1" }, { "code": null, "e": 2942, "s": 2886, "text": "Amazon Interview Experience SDE-2 (3 Years Experienced)" }, { "code": null, "e": 2969, "s": 2942, "text": "Google Interview Questions" }, { "code": null, "e": 3015, "s": 2969, "text": "Write It Up: Share Your Interview Experiences" }, { "code": null, "e": 3088, "s": 3015, "text": "Samsung Interview Experience Research & Institute SRIB (Off-Campus) 2022" }, { "code": null, "e": 3126, "s": 3088, "text": "Amazon Interview Experience for SDE-1" }, { "code": null, "e": 3196, "s": 3126, "text": "Google SWE Interview Experience (Google Online Coding Challenge) 2022" }, { "code": null, "e": 3225, "s": 3196, "text": "Nagarro Interview Experience" }, { "code": null, "e": 3291, "s": 3225, "text": "Tiger Analytics Interview Experience for Data Analyst (On-Campus)" } ]
Kali-Whoami – Stay anonymous on Kali Linux
14 Sep, 2021 In today’s life, we are surrounded by a lot of cyber security tools and we talk about our online anonymity, but are we really anonymous? A single mistake can reveal our anonymity, so here is a tool that can help us to make anonymity possible and it is called WHOAMI. It is very useful and has a very simple UI. Note: if you are a parrot user then you have to make few changes in the script of the tool. First, you have to open the script where you will get an error and just remove the “\kali-applications” from the path. Anti Man In The Middle Log killer IP changer Domain Name Server changer Mac Spoofer Anti cold boot Changes the timezone Changes the HostName Browser anonymization Before we start installing this tool on our Linux we have to check few tools which are mandatory for this tool, those tools are:-tar, git, tor, curl,python3,python3-scapy. Generally, these are pre-installed in our Linux but if you don’t have then you can just simply run the following command:- sudo apt update && sudo apt install tar tor curl python3 python3-scapy network-manager Now we are ready for further process, You can change your directory if you want and git clone the following URL in your terminal:- git clone https://github.com/omer-dogan/kali-whoami Now change the directory to kali-whoami and run this command sudo make install And now our tool is ready for use, we can open the interface of this tool by running this command sudo kali-whoami --help Now start the tool using this command:- sudo kali-whoami --start Here we have to choose options which we want to enable, for this just press numbers for enabling, and if you want to disable press that number again. We have chosen all the options and the chosen options have the right tick beside the options. The following are examples of the tool. To change the MAC address of our device To change the timezone of our system To change the hostname of our system In the following photo, you can see our previous details before using the tool:- And after enabling all the options:- Mac address is changed Timezone is changed, previously it was IST and now it is showing UTC Hostname is changed After this feature, we get directly connected with the tor browser and can browse anonymously. Here is a photo in where you can see that our system is connected with the tor browser. To check the status of this tool use the following command sudo kali-whoami --status The tool is perfectly started in your system and your system is connected through tor network, and you can browse anonymously, and after you are done using, you can easily stop it by running the following command: sudo kali-whoami --stop Again if we check the status: Kali-Linux Linux-Tools Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Docker - COPY Instruction scp command in Linux with Examples chown command in Linux with Examples SED command in Linux | Set 2 mv command in Linux with examples nohup Command in Linux with Examples chmod command in Linux with examples Introduction to Linux Operating System Array Basics in Shell Scripting | Set 1 Basic Operators in Shell Scripting
[ { "code": null, "e": 52, "s": 24, "text": "\n14 Sep, 2021" }, { "code": null, "e": 364, "s": 52, "text": "In today’s life, we are surrounded by a lot of cyber security tools and we talk about our online anonymity, but are we really anonymous? A single mistake can reveal our anonymity, so here is a tool that can help us to make anonymity possible and it is called WHOAMI. It is very useful and has a very simple UI. " }, { "code": null, "e": 575, "s": 364, "text": "Note: if you are a parrot user then you have to make few changes in the script of the tool. First, you have to open the script where you will get an error and just remove the “\\kali-applications” from the path." }, { "code": null, "e": 598, "s": 575, "text": "Anti Man In The Middle" }, { "code": null, "e": 609, "s": 598, "text": "Log killer" }, { "code": null, "e": 620, "s": 609, "text": "IP changer" }, { "code": null, "e": 647, "s": 620, "text": "Domain Name Server changer" }, { "code": null, "e": 659, "s": 647, "text": "Mac Spoofer" }, { "code": null, "e": 674, "s": 659, "text": "Anti cold boot" }, { "code": null, "e": 695, "s": 674, "text": "Changes the timezone" }, { "code": null, "e": 716, "s": 695, "text": "Changes the HostName" }, { "code": null, "e": 740, "s": 716, "text": " Browser anonymization " }, { "code": null, "e": 912, "s": 740, "text": "Before we start installing this tool on our Linux we have to check few tools which are mandatory for this tool, those tools are:-tar, git, tor, curl,python3,python3-scapy." }, { "code": null, "e": 1035, "s": 912, "text": "Generally, these are pre-installed in our Linux but if you don’t have then you can just simply run the following command:-" }, { "code": null, "e": 1122, "s": 1035, "text": "sudo apt update && sudo apt install tar tor curl python3 python3-scapy network-manager" }, { "code": null, "e": 1253, "s": 1122, "text": "Now we are ready for further process, You can change your directory if you want and git clone the following URL in your terminal:-" }, { "code": null, "e": 1305, "s": 1253, "text": "git clone https://github.com/omer-dogan/kali-whoami" }, { "code": null, "e": 1366, "s": 1305, "text": "Now change the directory to kali-whoami and run this command" }, { "code": null, "e": 1384, "s": 1366, "text": "sudo make install" }, { "code": null, "e": 1482, "s": 1384, "text": "And now our tool is ready for use, we can open the interface of this tool by running this command" }, { "code": null, "e": 1506, "s": 1482, "text": "sudo kali-whoami --help" }, { "code": null, "e": 1546, "s": 1506, "text": "Now start the tool using this command:-" }, { "code": null, "e": 1571, "s": 1546, "text": "sudo kali-whoami --start" }, { "code": null, "e": 1721, "s": 1571, "text": "Here we have to choose options which we want to enable, for this just press numbers for enabling, and if you want to disable press that number again." }, { "code": null, "e": 1816, "s": 1721, "text": "We have chosen all the options and the chosen options have the right tick beside the options. " }, { "code": null, "e": 1856, "s": 1816, "text": "The following are examples of the tool." }, { "code": null, "e": 1896, "s": 1856, "text": "To change the MAC address of our device" }, { "code": null, "e": 1933, "s": 1896, "text": "To change the timezone of our system" }, { "code": null, "e": 1970, "s": 1933, "text": "To change the hostname of our system" }, { "code": null, "e": 2051, "s": 1970, "text": "In the following photo, you can see our previous details before using the tool:-" }, { "code": null, "e": 2088, "s": 2051, "text": "And after enabling all the options:-" }, { "code": null, "e": 2113, "s": 2088, "text": " Mac address is changed" }, { "code": null, "e": 2182, "s": 2113, "text": "Timezone is changed, previously it was IST and now it is showing UTC" }, { "code": null, "e": 2203, "s": 2182, "text": " Hostname is changed" }, { "code": null, "e": 2299, "s": 2203, "text": "After this feature, we get directly connected with the tor browser and can browse anonymously. " }, { "code": null, "e": 2387, "s": 2299, "text": "Here is a photo in where you can see that our system is connected with the tor browser." }, { "code": null, "e": 2448, "s": 2387, "text": " To check the status of this tool use the following command " }, { "code": null, "e": 2475, "s": 2448, "text": "sudo kali-whoami --status " }, { "code": null, "e": 2689, "s": 2475, "text": "The tool is perfectly started in your system and your system is connected through tor network, and you can browse anonymously, and after you are done using, you can easily stop it by running the following command:" }, { "code": null, "e": 2714, "s": 2689, "text": "sudo kali-whoami --stop " }, { "code": null, "e": 2744, "s": 2714, "text": "Again if we check the status:" }, { "code": null, "e": 2755, "s": 2744, "text": "Kali-Linux" }, { "code": null, "e": 2767, "s": 2755, "text": "Linux-Tools" }, { "code": null, "e": 2778, "s": 2767, "text": "Linux-Unix" }, { "code": null, "e": 2876, "s": 2778, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2902, "s": 2876, "text": "Docker - COPY Instruction" }, { "code": null, "e": 2937, "s": 2902, "text": "scp command in Linux with Examples" }, { "code": null, "e": 2974, "s": 2937, "text": "chown command in Linux with Examples" }, { "code": null, "e": 3003, "s": 2974, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 3037, "s": 3003, "text": "mv command in Linux with examples" }, { "code": null, "e": 3074, "s": 3037, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 3111, "s": 3074, "text": "chmod command in Linux with examples" }, { "code": null, "e": 3150, "s": 3111, "text": "Introduction to Linux Operating System" }, { "code": null, "e": 3190, "s": 3150, "text": "Array Basics in Shell Scripting | Set 1" } ]
What is tools:context in Android Layout Files?
12 Apr, 2021 Android Studio provides a much richer variety of functions in the form of various XML attributes in the tools namespace which enables design-time features or compile-time behaviors. When the app is being built, the build tools remove these attributes so that there is no effect on runtime behavior or APK size. tools:context is such an attribute that is defined in any root view and declares which activity or fragment the layout is associated with. This declaration helps in enabling various features in the layout preview which demands the knowledge of the activity such as automatically choosing the necessary theme for preview. Let’s see a small demonstration of the above stated. Now, whenever a project is created in android studio or any activity or fragment is added the following code gets generated automatically in the layout file: XML <!--To demonstrate the automatically generated code and usasge of tools:context--><?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" <!--It means that the layout is associated with MainActivity--> tools:context=".MainActivity"> <!--Other Views--> </androidx.constraintlayout.widget.ConstraintLayout> You can also specify the activity class name yourself using the same dot prefix as stated in the manifest file. Another use of the tools:context is in the form of figuring out where to place the onClick handlers (to respond to touch events) when you implement it using the quickfix. showcasing the use of tools:context in using the quickfix Now if you were to delete the tools:context attribute then there would be no recommendation for the quickfix. So to summarize, tools:context attribute is declared in the rootview of the layout file and it declares which activity or fragment the layout file is associated with. It is also used for better visualization of the current layout and view. Picked Android Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Add Views Dynamically and Store Data in Arraylist in Android? Android SDK and it's Components Flutter - Custom Bottom Navigation Bar How to Communicate Between Fragments in Android? Retrofit with Kotlin Coroutine in Android How to Post Data to API using Retrofit in Android? Flutter - Stack Widget Introduction to Android Development Activity Lifecycle in Android with Demo App Fragment Lifecycle in Android
[ { "code": null, "e": 28, "s": 0, "text": "\n12 Apr, 2021" }, { "code": null, "e": 478, "s": 28, "text": "Android Studio provides a much richer variety of functions in the form of various XML attributes in the tools namespace which enables design-time features or compile-time behaviors. When the app is being built, the build tools remove these attributes so that there is no effect on runtime behavior or APK size. tools:context is such an attribute that is defined in any root view and declares which activity or fragment the layout is associated with." }, { "code": null, "e": 871, "s": 478, "text": "This declaration helps in enabling various features in the layout preview which demands the knowledge of the activity such as automatically choosing the necessary theme for preview. Let’s see a small demonstration of the above stated. Now, whenever a project is created in android studio or any activity or fragment is added the following code gets generated automatically in the layout file:" }, { "code": null, "e": 875, "s": 871, "text": "XML" }, { "code": "<!--To demonstrate the automatically generated code and usasge of tools:context--><?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" <!--It means that the layout is associated with MainActivity--> tools:context=\".MainActivity\"> <!--Other Views--> </androidx.constraintlayout.widget.ConstraintLayout>", "e": 1476, "s": 875, "text": null }, { "code": null, "e": 1759, "s": 1476, "text": "You can also specify the activity class name yourself using the same dot prefix as stated in the manifest file. Another use of the tools:context is in the form of figuring out where to place the onClick handlers (to respond to touch events) when you implement it using the quickfix." }, { "code": null, "e": 1817, "s": 1759, "text": "showcasing the use of tools:context in using the quickfix" }, { "code": null, "e": 2168, "s": 1817, "text": "Now if you were to delete the tools:context attribute then there would be no recommendation for the quickfix. So to summarize, tools:context attribute is declared in the rootview of the layout file and it declares which activity or fragment the layout file is associated with. It is also used for better visualization of the current layout and view. " }, { "code": null, "e": 2175, "s": 2168, "text": "Picked" }, { "code": null, "e": 2183, "s": 2175, "text": "Android" }, { "code": null, "e": 2191, "s": 2183, "text": "Android" }, { "code": null, "e": 2289, "s": 2191, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2358, "s": 2289, "text": "How to Add Views Dynamically and Store Data in Arraylist in Android?" }, { "code": null, "e": 2390, "s": 2358, "text": "Android SDK and it's Components" }, { "code": null, "e": 2429, "s": 2390, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 2478, "s": 2429, "text": "How to Communicate Between Fragments in Android?" }, { "code": null, "e": 2520, "s": 2478, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 2571, "s": 2520, "text": "How to Post Data to API using Retrofit in Android?" }, { "code": null, "e": 2594, "s": 2571, "text": "Flutter - Stack Widget" }, { "code": null, "e": 2630, "s": 2594, "text": "Introduction to Android Development" }, { "code": null, "e": 2674, "s": 2630, "text": "Activity Lifecycle in Android with Demo App" } ]
PostgreSQL – Drop Function
28 Aug, 2020 In PostgreSQL, the Drop function statement is used to remove a function. Syntax: drop function [if exists] function_name(argument_list) [cascade | restrict] Let’s analyze the above syntax: First, specify the name of the function that you want to remove after the drop function keywords. Second, use the if exists option if you want to instruct PostgreSQL to issue a notice instead of an error in case the function does not exist. Third, specify the argument list of the function. Since functions can be overloaded PostgreSQL needs to know which function you want to remove by checking the argument list. If a function is unique within the schema, you do not need to specify the argument list. When a function has any dependent objects such as operators or triggers, you cannot drop that function. To drop the function and its dependent objects, you need to specify the cascade option. The drop function with the cascade option will recursively remove the function, its dependent objects, and the objects that depend on those objects, and so on. By default, the drop function statement uses the restrict option that rejects the removal of a function when it has any dependent objects. To drop multiple functions using a single drop function statement, you specify a comma-separated list of function name after the drop function keyword like this: drop function [if exists] function1, function2, ...; For the sake of example, we will use the sample database ie, dvdrental. Example : The following statement uses the create function statement to define a function that returns a set of films including film_id, title, and actor: create or replace function get_film_actors() returns setof record as $$ declare rec record; begin for rec in select film_id, title, (first_name || ' ' || last_name)::varchar from film inner join film_actor using(film_id) inner join actor using (actor_id) order by title loop return next rec; end loop; return; end; $$ language plpgsql; The following statement defines a function with the same name get_film_actors. However, it accepts a film id as the argument: create or replace function get_film_actors(p_fiml_id int) returns setof record as $$ declare rec record; begin for rec in select film_id, title, (first_name || ' ' || last_name)::varchar from film inner join film_actor using(film_id) inner join actor using (actor_id) where film_id = p_fiml_id order by title loop return next rec; end loop; return; end; $$ language plpgsql; The following statement attempts to drop the get_film_actors function: drop function get_film_actors; Output: Since the get_film_actors stored procedure is not unique, you need to specify which function you want to drop. The following statement drops the get_film_actors function that has zero parameters: drop function get_film_actors(); Now, there is only one get_film_actors function left. Since it is unique in the database, you can drop it without specifying its argument list like this: drop function get_film_actors; Or if you want to specify the exact function, you can use the following statement: drop function get_film_actors(int); Use the drop function statement to remove a function. Specify the argument list in the function if the function is overloaded. Use the drop function statement with the cascade option to drop a function and its dependent objects and objects that depends on those objects, and so on. PostgreSQL-function PostgreSQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Aug, 2020" }, { "code": null, "e": 101, "s": 28, "text": "In PostgreSQL, the Drop function statement is used to remove a function." }, { "code": null, "e": 186, "s": 101, "text": "Syntax:\ndrop function [if exists] function_name(argument_list)\n[cascade | restrict]\n" }, { "code": null, "e": 218, "s": 186, "text": "Let’s analyze the above syntax:" }, { "code": null, "e": 316, "s": 218, "text": "First, specify the name of the function that you want to remove after the drop function keywords." }, { "code": null, "e": 459, "s": 316, "text": "Second, use the if exists option if you want to instruct PostgreSQL to issue a notice instead of an error in case the function does not exist." }, { "code": null, "e": 722, "s": 459, "text": "Third, specify the argument list of the function. Since functions can be overloaded PostgreSQL needs to know which function you want to remove by checking the argument list. If a function is unique within the schema, you do not need to specify the argument list." }, { "code": null, "e": 1074, "s": 722, "text": "When a function has any dependent objects such as operators or triggers, you cannot drop that function. To drop the function and its dependent objects, you need to specify the cascade option. The drop function with the cascade option will recursively remove the function, its dependent objects, and the objects that depend on those objects, and so on." }, { "code": null, "e": 1375, "s": 1074, "text": "By default, the drop function statement uses the restrict option that rejects the removal of a function when it has any dependent objects. To drop multiple functions using a single drop function statement, you specify a comma-separated list of function name after the drop function keyword like this:" }, { "code": null, "e": 1429, "s": 1375, "text": "drop function [if exists] function1, function2, ...;\n" }, { "code": null, "e": 1501, "s": 1429, "text": "For the sake of example, we will use the sample database ie, dvdrental." }, { "code": null, "e": 1511, "s": 1501, "text": "Example :" }, { "code": null, "e": 1656, "s": 1511, "text": "The following statement uses the create function statement to define a function that returns a set of films including film_id, title, and actor:" }, { "code": null, "e": 2100, "s": 1656, "text": "create or replace function get_film_actors()\n returns setof record\nas $$\ndeclare\n rec record;\nbegin\n for rec in select \n film_id, \n title, \n (first_name || ' ' || last_name)::varchar\n from film\n inner join film_actor using(film_id)\n inner join actor using (actor_id)\n order by title\n loop\n return next rec;\n end loop;\n \n return;\nend;\n$$ \nlanguage plpgsql;\n" }, { "code": null, "e": 2226, "s": 2100, "text": "The following statement defines a function with the same name get_film_actors. However, it accepts a film id as the argument:" }, { "code": null, "e": 2664, "s": 2226, "text": "create or replace function get_film_actors(p_fiml_id int)\n returns setof record\n as $$\ndeclare\n rec record;\nbegin\nfor rec in select \nfilm_id, \ntitle, \n (first_name || ' ' || last_name)::varchar\n from film\n inner join film_actor using(film_id)\n inner join actor using (actor_id)\n where film_id = p_fiml_id\n order by title\n loop\n return next rec;\n end loop;\n\n return;\nend;\n$$ \nlanguage plpgsql;\n" }, { "code": null, "e": 2735, "s": 2664, "text": "The following statement attempts to drop the get_film_actors function:" }, { "code": null, "e": 2767, "s": 2735, "text": "drop function get_film_actors;\n" }, { "code": null, "e": 2775, "s": 2767, "text": "Output:" }, { "code": null, "e": 2886, "s": 2775, "text": "Since the get_film_actors stored procedure is not unique, you need to specify which function you want to drop." }, { "code": null, "e": 2971, "s": 2886, "text": "The following statement drops the get_film_actors function that has zero parameters:" }, { "code": null, "e": 3005, "s": 2971, "text": "drop function get_film_actors();\n" }, { "code": null, "e": 3159, "s": 3005, "text": "Now, there is only one get_film_actors function left. Since it is unique in the database, you can drop it without specifying its argument list like this:" }, { "code": null, "e": 3191, "s": 3159, "text": "drop function get_film_actors;\n" }, { "code": null, "e": 3274, "s": 3191, "text": "Or if you want to specify the exact function, you can use the following statement:" }, { "code": null, "e": 3311, "s": 3274, "text": "drop function get_film_actors(int);\n" }, { "code": null, "e": 3365, "s": 3311, "text": "Use the drop function statement to remove a function." }, { "code": null, "e": 3438, "s": 3365, "text": "Specify the argument list in the function if the function is overloaded." }, { "code": null, "e": 3593, "s": 3438, "text": "Use the drop function statement with the cascade option to drop a function and its dependent objects and objects that depends on those objects, and so on." }, { "code": null, "e": 3613, "s": 3593, "text": "PostgreSQL-function" }, { "code": null, "e": 3624, "s": 3613, "text": "PostgreSQL" } ]
The Two Water Jug Puzzle
31 May, 2022 You are on the side of the river. You are given a m liter jug and a n liter jug where 0 < m < n. Both the jugs are initially empty. The jugs don’t have markings to allow measuring smaller quantities. You have to use the jugs to measure d liters of water where d < n. Determine the minimum no of operations to be performed to obtain d liters of water in one of jug. The operations you can perform are: Empty a JugFill a JugPour water from one jug to the other until one of the jugs is either empty or full. Empty a Jug Fill a Jug Pour water from one jug to the other until one of the jugs is either empty or full. There are several ways of solving this problem including BFS and DP. In this article, an arithmetic approach to solving the problem is discussed. The problem can be modeled by means of the Diophantine equation of the form mx + ny = d which is solvable if and only if gcd(m, n) divides d. Also, the solution x,y for which equation is satisfied can be given using the Extended Euclid algorithm for GCD. For example, if we have a jug J1 of 5 liters (n = 5) and another jug J2 of 3 liters (m = 3) and we have to measure 1 liter of water using them. The associated equation will be 5n + 3m = 1. First of all this problem can be solved since gcd(3,5) = 1 which divides 1 (See this for detailed explanation). Using the Extended Euclid algorithm, we get values of n and m for which the equation is satisfied which are n = 2 and m = -3. These values of n, m also have some meaning like here n = 2 and m = -3 means that we have to fill J1 twice and empty J2 thrice. Now to find the minimum no of operations to be performed we have to decide which jug should be filled first. Depending upon which jug is chosen to be filled and which to be emptied we have two different solutions and the minimum among them would be our answer. Solution 1 (Always pour from m liter jug into n liter jug) Fill the m litre jug and empty it into n liter jug.Whenever the m liter jug becomes empty fill it.Whenever the n liter jug becomes full empty it.Repeat steps 1,2,3 till either n liter jug or the m liter jug contains d litres of water. Fill the m litre jug and empty it into n liter jug. Whenever the m liter jug becomes empty fill it. Whenever the n liter jug becomes full empty it. Repeat steps 1,2,3 till either n liter jug or the m liter jug contains d litres of water. Each of steps 1, 2 and 3 are counted as one operation that we perform. Let us say algorithm 1 achieves the task in C1 no of operations. Solution 2 (Always pour from n liter jug into m liter jug) Fill the n liter jug and empty it into m liter jug.Whenever the n liter jug becomes empty fill it.Whenever the m liter jug becomes full empty it.Repeat steps 1, 2 and 3 till either n liter jug or the m liter jug contains d liters of water. Fill the n liter jug and empty it into m liter jug. Whenever the n liter jug becomes empty fill it. Whenever the m liter jug becomes full empty it. Repeat steps 1, 2 and 3 till either n liter jug or the m liter jug contains d liters of water. Let us say solution 2 achieves the task in C2 no of operations.Now our final solution will be a minimum of C1 and C2.Now we illustrate how both of the solutions work. Suppose there are a 3 liter jug and a 5 liter jug to measure 4 liters water so m = 3,n = 5 and d = 4. The associated Diophantine equation will be 3m + 5n = 4. We use pair (x, y) to represent amounts of water inside the 3-liter jug and 5-liter jug respectively in each pouring step. Using Solution 1, successive pouring steps are: (0,0)->(3,0)->(0,3)->(3,3)->(1,5)->(1,0)->(0,1)->(3,1)->(0,4) Hence the no of operations you need to perform are 8. Using Solution 2, successive pouring steps are: (0,0)->(0,5)->(3,2)->(0,2)->(2,0)->(2,5)->(3,4) Hence the no of operations you need to perform are 6.Therefore, we would use solution 2 to measure 4 liters of water in 6 operations or moves. Based on the explanation here is the implementation. C++ Java Python3 C# Javascript // C++ program to count minimum number of steps// required to measure d litres water using jugs// of m liters and n liters capacity.#include <bits/stdc++.h>using namespace std; // Utility function to return GCD of 'a'// and 'b'.int gcd(int a, int b){ if (b==0) return a; return gcd(b, a%b);} /* fromCap -- Capacity of jug from which water is poured toCap -- Capacity of jug to which water is poured d -- Amount to be measured */int pour(int fromCap, int toCap, int d){ // Initialize current amount of water // in source and destination jugs int from = fromCap; int to = 0; // Initialize count of steps required int step = 1; // Needed to fill "from" Jug // Break the loop when either of the two // jugs has d litre water while (from != d && to != d) { // Find the maximum amount that can be // poured int temp = min(from, toCap - to); // Pour "temp" liters from "from" to "to" to += temp; from -= temp; // Increment count of steps step++; if (from == d || to == d) break; // If first jug becomes empty, fill it if (from == 0) { from = fromCap; step++; } // If second jug becomes full, empty it if (to == toCap) { to = 0; step++; } } return step;} // Returns count of minimum steps needed to// measure d literint minSteps(int m, int n, int d){ // To make sure that m is smaller than n if (m > n) swap(m, n); // For d > n we cant measure the water // using the jugs if (d > n) return -1; // If gcd of n and m does not divide d // then solution is not possible if ((d % gcd(n,m)) != 0) return -1; // Return minimum two cases: // a) Water of n liter jug is poured into // m liter jug // b) Vice versa of "a" return min(pour(n,m,d), // n to m pour(m,n,d)); // m to n} // Driver code to test aboveint main(){ int n = 3, m = 5, d = 4; printf("Minimum number of steps required is %d", minSteps(m, n, d)); return 0;} // Java program to count minimum number of// steps required to measure d litres water// using jugs of m liters and n liters capacity.import java.io.*; class GFG{ // Utility function to return GCD of 'a'// and 'b'.public static int gcd(int a, int b){ if (b == 0) return a; return gcd(b, a % b);} /* fromCap -- Capacity of jug from which water is poured toCap -- Capacity of jug to which water is poured d -- Amount to be measured */public static int pour(int fromCap, int toCap, int d){ // Initialize current amount of water // in source and destination jugs int from = fromCap; int to = 0; // Initialize count of steps required int step = 1; // Needed to fill "from" Jug // Break the loop when either of the two // jugs has d litre water while (from != d && to != d) { // Find the maximum amount that can be // poured int temp = Math.min(from, toCap - to); // Pour "temp" liters from "from" to "to" to += temp; from -= temp; // Increment count of steps step++; if (from == d || to == d) break; // If first jug becomes empty, fill it if (from == 0) { from = fromCap; step++; } // If second jug becomes full, empty it if (to == toCap) { to = 0; step++; } } return step;} // Returns count of minimum steps needed to// measure d literpublic static int minSteps(int m, int n, int d){ // To make sure that m is smaller than n if (m > n) { int t = m; m = n; n = t; } // For d > n we cant measure the water // using the jugs if (d > n) return -1; // If gcd of n and m does not divide d // then solution is not possible if ((d % gcd(n, m)) != 0) return -1; // Return minimum two cases: // a) Water of n liter jug is poured into // m liter jug // b) Vice versa of "a" return Math.min(pour(n, m, d), // n to m pour(m, n, d)); // m to n} // Driver codepublic static void main(String[] args){ int n = 3, m = 5, d = 4; System.out.println("Minimum number of " + "steps required is " + minSteps(m, n, d));}} // This code is contributed by RohitOberoi # Python3 implementation of program to count# minimum number of steps required to measure# d litre water using jugs of m liters and n# liters capacity.def gcd(a, b): if b==0: return a return gcd(b, a%b) ''' fromCap -- Capacity of jug from which water is poured toCap -- Capacity of jug to which water is poured d -- Amount to be measured '''def Pour(toJugCap, fromJugCap, d): # Initialize current amount of water # in source and destination jugs fromJug = fromJugCap toJug = 0 # Initialize steps required step = 1 while ((fromJug is not d) and (toJug is not d)): # Find the maximum amount that can be # poured temp = min(fromJug, toJugCap-toJug) # Pour 'temp' liter from 'fromJug' to 'toJug' toJug = toJug + temp fromJug = fromJug - temp step = step + 1 if ((fromJug == d) or (toJug == d)): break # If first jug becomes empty, fill it if fromJug == 0: fromJug = fromJugCap step = step + 1 # If second jug becomes full, empty it if toJug == toJugCap: toJug = 0 step = step + 1 return step # Returns count of minimum steps needed to# measure d literdef minSteps(n, m, d): if m> n: temp = m m = n n = temp if (d%(gcd(n,m)) is not 0): return -1 # Return minimum two cases: # a) Water of n liter jug is poured into # m liter jug return(min(Pour(n,m,d), Pour(m,n,d))) # Driver codeif __name__ == '__main__': n = 3 m = 5 d = 4 print('Minimum number of steps required is', minSteps(n, m, d)) # This code is contributed by Sanket Badhe // C# program to implement// the above approachusing System; class GFG{ // Utility function to return GCD of 'a'// and 'b'.public static int gcd(int a, int b){ if (b == 0) return a; return gcd(b, a % b);} /* fromCap -- Capacity of jug from which water is poured toCap -- Capacity of jug to which water is poured d -- Amount to be measured */public static int pour(int fromCap, int toCap, int d){ // Initialize current amount of water // in source and destination jugs int from = fromCap; int to = 0; // Initialize count of steps required int step = 1; // Needed to fill "from" Jug // Break the loop when either of the two // jugs has d litre water while (from != d && to != d) { // Find the maximum amount that can be // poured int temp = Math.Min(from, toCap - to); // Pour "temp" liters from "from" to "to" to += temp; from -= temp; // Increment count of steps step++; if (from == d || to == d) break; // If first jug becomes empty, fill it if (from == 0) { from = fromCap; step++; } // If second jug becomes full, empty it if (to == toCap) { to = 0; step++; } } return step;} // Returns count of minimum steps needed to// measure d literpublic static int minSteps(int m, int n, int d){ // To make sure that m is smaller than n if (m > n) { int t = m; m = n; n = t; } // For d > n we cant measure the water // using the jugs if (d > n) return -1; // If gcd of n and m does not divide d // then solution is not possible if ((d % gcd(n, m)) != 0) return -1; // Return minimum two cases: // a) Water of n liter jug is poured into // m liter jug // b) Vice versa of "a" return Math.Min(pour(n, m, d), // n to m pour(m, n, d)); // m to n} // Driver Codepublic static void Main(){ int n = 3, m = 5, d = 4; Console.Write("Minimum number of " + "steps required is " + minSteps(m, n, d));}} // This code is contributed by code_hunt. <script> // Javascript program to count minimum number of// steps required to measure d litres water// using jugs of m liters and n liters capacity. // Utility function to return GCD of 'a' // and 'b'. function gcd(a , b) { if (b == 0) return a; return gcd(b, a % b); } /* fromCap -- Capacity of jug from which water is poured toCap -- Capacity of jug to which water is poured d -- Amount to be measured */ function pour(fromCap , toCap , d) { // Initialize current amount of water // in source and destination jugs var from = fromCap; var to = 0; // Initialize count of steps required var step = 1; // Needed to fill "from" Jug // Break the loop when either of the two // jugs has d litre water while (from != d && to != d) { // Find the maximum amount that can be // poured var temp = Math.min(from, toCap - to); // Pour "temp" liters from "from" to "to" to += temp; from -= temp; // Increment count of steps step++; if (from == d || to == d) break; // If first jug becomes empty, fill it if (from == 0) { from = fromCap; step++; } // If second jug becomes full, empty it if (to == toCap) { to = 0; step++; } } return step; } // Returns count of minimum steps needed to // measure d liter function minSteps(m , n , d) { // To make sure that m is smaller than n if (m > n) { var t = m; m = n; n = t; } // For d > n we cant measure the water // using the jugs if (d > n) return -1; // If gcd of n and m does not divide d // then solution is not possible if ((d % gcd(n, m)) != 0) return -1; // Return minimum two cases: // a) Water of n liter jug is poured into // m liter jug // b) Vice versa of "a" return Math.min(pour(n, m, d), // n to m pour(m, n, d)); // m to n } // Driver code var n = 3, m = 5, d = 4; document.write("Minimum number of " + "steps required is " + minSteps(m, n, d)); // This code contributed by Rajput-Ji </script> Output: Minimum number of steps required is 6 Time Complexity: O(N + M)Auxiliary Space: O(1) Another detailed Explanation:http://web.mit.edu/neboat/Public/6.042/numbertheory1.pdf This article is contributed by Madhur Modi. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above Sanket Badhe cosine1509 hackr4india RohitOberoi Rajput-Ji pankajsharmagfg choudharyrajat1311 code_hunt MakeMyTrip MAQ Software Algorithms Dynamic Programming MakeMyTrip MAQ Software Dynamic Programming Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. DSA Sheet by Love Babbar SDE SHEET - A Complete Guide for SDE Preparation What is Hashing | A Complete Tutorial Understanding Time Complexity with Simple Examples CPU Scheduling in Operating Systems Largest Sum Contiguous Subarray Program for Fibonacci numbers 0-1 Knapsack Problem | DP-10 Longest Common Subsequence | DP-4 Subset Sum Problem | DP-25
[ { "code": null, "e": 52, "s": 24, "text": "\n31 May, 2022" }, { "code": null, "e": 454, "s": 52, "text": "You are on the side of the river. You are given a m liter jug and a n liter jug where 0 < m < n. Both the jugs are initially empty. The jugs don’t have markings to allow measuring smaller quantities. You have to use the jugs to measure d liters of water where d < n. Determine the minimum no of operations to be performed to obtain d liters of water in one of jug. The operations you can perform are: " }, { "code": null, "e": 559, "s": 454, "text": "Empty a JugFill a JugPour water from one jug to the other until one of the jugs is either empty or full." }, { "code": null, "e": 571, "s": 559, "text": "Empty a Jug" }, { "code": null, "e": 582, "s": 571, "text": "Fill a Jug" }, { "code": null, "e": 666, "s": 582, "text": "Pour water from one jug to the other until one of the jugs is either empty or full." }, { "code": null, "e": 1883, "s": 666, "text": "There are several ways of solving this problem including BFS and DP. In this article, an arithmetic approach to solving the problem is discussed. The problem can be modeled by means of the Diophantine equation of the form mx + ny = d which is solvable if and only if gcd(m, n) divides d. Also, the solution x,y for which equation is satisfied can be given using the Extended Euclid algorithm for GCD. For example, if we have a jug J1 of 5 liters (n = 5) and another jug J2 of 3 liters (m = 3) and we have to measure 1 liter of water using them. The associated equation will be 5n + 3m = 1. First of all this problem can be solved since gcd(3,5) = 1 which divides 1 (See this for detailed explanation). Using the Extended Euclid algorithm, we get values of n and m for which the equation is satisfied which are n = 2 and m = -3. These values of n, m also have some meaning like here n = 2 and m = -3 means that we have to fill J1 twice and empty J2 thrice. Now to find the minimum no of operations to be performed we have to decide which jug should be filled first. Depending upon which jug is chosen to be filled and which to be emptied we have two different solutions and the minimum among them would be our answer." }, { "code": null, "e": 1943, "s": 1883, "text": "Solution 1 (Always pour from m liter jug into n liter jug) " }, { "code": null, "e": 2178, "s": 1943, "text": "Fill the m litre jug and empty it into n liter jug.Whenever the m liter jug becomes empty fill it.Whenever the n liter jug becomes full empty it.Repeat steps 1,2,3 till either n liter jug or the m liter jug contains d litres of water." }, { "code": null, "e": 2230, "s": 2178, "text": "Fill the m litre jug and empty it into n liter jug." }, { "code": null, "e": 2278, "s": 2230, "text": "Whenever the m liter jug becomes empty fill it." }, { "code": null, "e": 2326, "s": 2278, "text": "Whenever the n liter jug becomes full empty it." }, { "code": null, "e": 2416, "s": 2326, "text": "Repeat steps 1,2,3 till either n liter jug or the m liter jug contains d litres of water." }, { "code": null, "e": 2552, "s": 2416, "text": "Each of steps 1, 2 and 3 are counted as one operation that we perform. Let us say algorithm 1 achieves the task in C1 no of operations." }, { "code": null, "e": 2613, "s": 2552, "text": "Solution 2 (Always pour from n liter jug into m liter jug) " }, { "code": null, "e": 2853, "s": 2613, "text": "Fill the n liter jug and empty it into m liter jug.Whenever the n liter jug becomes empty fill it.Whenever the m liter jug becomes full empty it.Repeat steps 1, 2 and 3 till either n liter jug or the m liter jug contains d liters of water." }, { "code": null, "e": 2905, "s": 2853, "text": "Fill the n liter jug and empty it into m liter jug." }, { "code": null, "e": 2953, "s": 2905, "text": "Whenever the n liter jug becomes empty fill it." }, { "code": null, "e": 3001, "s": 2953, "text": "Whenever the m liter jug becomes full empty it." }, { "code": null, "e": 3096, "s": 3001, "text": "Repeat steps 1, 2 and 3 till either n liter jug or the m liter jug contains d liters of water." }, { "code": null, "e": 3545, "s": 3096, "text": "Let us say solution 2 achieves the task in C2 no of operations.Now our final solution will be a minimum of C1 and C2.Now we illustrate how both of the solutions work. Suppose there are a 3 liter jug and a 5 liter jug to measure 4 liters water so m = 3,n = 5 and d = 4. The associated Diophantine equation will be 3m + 5n = 4. We use pair (x, y) to represent amounts of water inside the 3-liter jug and 5-liter jug respectively in each pouring step." }, { "code": null, "e": 3594, "s": 3545, "text": "Using Solution 1, successive pouring steps are: " }, { "code": null, "e": 3656, "s": 3594, "text": "(0,0)->(3,0)->(0,3)->(3,3)->(1,5)->(1,0)->(0,1)->(3,1)->(0,4)" }, { "code": null, "e": 3710, "s": 3656, "text": "Hence the no of operations you need to perform are 8." }, { "code": null, "e": 3760, "s": 3710, "text": "Using Solution 2, successive pouring steps are: " }, { "code": null, "e": 3808, "s": 3760, "text": "(0,0)->(0,5)->(3,2)->(0,2)->(2,0)->(2,5)->(3,4)" }, { "code": null, "e": 3952, "s": 3808, "text": "Hence the no of operations you need to perform are 6.Therefore, we would use solution 2 to measure 4 liters of water in 6 operations or moves. " }, { "code": null, "e": 4006, "s": 3952, "text": "Based on the explanation here is the implementation. " }, { "code": null, "e": 4010, "s": 4006, "text": "C++" }, { "code": null, "e": 4015, "s": 4010, "text": "Java" }, { "code": null, "e": 4023, "s": 4015, "text": "Python3" }, { "code": null, "e": 4026, "s": 4023, "text": "C#" }, { "code": null, "e": 4037, "s": 4026, "text": "Javascript" }, { "code": "// C++ program to count minimum number of steps// required to measure d litres water using jugs// of m liters and n liters capacity.#include <bits/stdc++.h>using namespace std; // Utility function to return GCD of 'a'// and 'b'.int gcd(int a, int b){ if (b==0) return a; return gcd(b, a%b);} /* fromCap -- Capacity of jug from which water is poured toCap -- Capacity of jug to which water is poured d -- Amount to be measured */int pour(int fromCap, int toCap, int d){ // Initialize current amount of water // in source and destination jugs int from = fromCap; int to = 0; // Initialize count of steps required int step = 1; // Needed to fill \"from\" Jug // Break the loop when either of the two // jugs has d litre water while (from != d && to != d) { // Find the maximum amount that can be // poured int temp = min(from, toCap - to); // Pour \"temp\" liters from \"from\" to \"to\" to += temp; from -= temp; // Increment count of steps step++; if (from == d || to == d) break; // If first jug becomes empty, fill it if (from == 0) { from = fromCap; step++; } // If second jug becomes full, empty it if (to == toCap) { to = 0; step++; } } return step;} // Returns count of minimum steps needed to// measure d literint minSteps(int m, int n, int d){ // To make sure that m is smaller than n if (m > n) swap(m, n); // For d > n we cant measure the water // using the jugs if (d > n) return -1; // If gcd of n and m does not divide d // then solution is not possible if ((d % gcd(n,m)) != 0) return -1; // Return minimum two cases: // a) Water of n liter jug is poured into // m liter jug // b) Vice versa of \"a\" return min(pour(n,m,d), // n to m pour(m,n,d)); // m to n} // Driver code to test aboveint main(){ int n = 3, m = 5, d = 4; printf(\"Minimum number of steps required is %d\", minSteps(m, n, d)); return 0;}", "e": 6218, "s": 4037, "text": null }, { "code": "// Java program to count minimum number of// steps required to measure d litres water// using jugs of m liters and n liters capacity.import java.io.*; class GFG{ // Utility function to return GCD of 'a'// and 'b'.public static int gcd(int a, int b){ if (b == 0) return a; return gcd(b, a % b);} /* fromCap -- Capacity of jug from which water is poured toCap -- Capacity of jug to which water is poured d -- Amount to be measured */public static int pour(int fromCap, int toCap, int d){ // Initialize current amount of water // in source and destination jugs int from = fromCap; int to = 0; // Initialize count of steps required int step = 1; // Needed to fill \"from\" Jug // Break the loop when either of the two // jugs has d litre water while (from != d && to != d) { // Find the maximum amount that can be // poured int temp = Math.min(from, toCap - to); // Pour \"temp\" liters from \"from\" to \"to\" to += temp; from -= temp; // Increment count of steps step++; if (from == d || to == d) break; // If first jug becomes empty, fill it if (from == 0) { from = fromCap; step++; } // If second jug becomes full, empty it if (to == toCap) { to = 0; step++; } } return step;} // Returns count of minimum steps needed to// measure d literpublic static int minSteps(int m, int n, int d){ // To make sure that m is smaller than n if (m > n) { int t = m; m = n; n = t; } // For d > n we cant measure the water // using the jugs if (d > n) return -1; // If gcd of n and m does not divide d // then solution is not possible if ((d % gcd(n, m)) != 0) return -1; // Return minimum two cases: // a) Water of n liter jug is poured into // m liter jug // b) Vice versa of \"a\" return Math.min(pour(n, m, d), // n to m pour(m, n, d)); // m to n} // Driver codepublic static void main(String[] args){ int n = 3, m = 5, d = 4; System.out.println(\"Minimum number of \" + \"steps required is \" + minSteps(m, n, d));}} // This code is contributed by RohitOberoi", "e": 8627, "s": 6218, "text": null }, { "code": "# Python3 implementation of program to count# minimum number of steps required to measure# d litre water using jugs of m liters and n# liters capacity.def gcd(a, b): if b==0: return a return gcd(b, a%b) ''' fromCap -- Capacity of jug from which water is poured toCap -- Capacity of jug to which water is poured d -- Amount to be measured '''def Pour(toJugCap, fromJugCap, d): # Initialize current amount of water # in source and destination jugs fromJug = fromJugCap toJug = 0 # Initialize steps required step = 1 while ((fromJug is not d) and (toJug is not d)): # Find the maximum amount that can be # poured temp = min(fromJug, toJugCap-toJug) # Pour 'temp' liter from 'fromJug' to 'toJug' toJug = toJug + temp fromJug = fromJug - temp step = step + 1 if ((fromJug == d) or (toJug == d)): break # If first jug becomes empty, fill it if fromJug == 0: fromJug = fromJugCap step = step + 1 # If second jug becomes full, empty it if toJug == toJugCap: toJug = 0 step = step + 1 return step # Returns count of minimum steps needed to# measure d literdef minSteps(n, m, d): if m> n: temp = m m = n n = temp if (d%(gcd(n,m)) is not 0): return -1 # Return minimum two cases: # a) Water of n liter jug is poured into # m liter jug return(min(Pour(n,m,d), Pour(m,n,d))) # Driver codeif __name__ == '__main__': n = 3 m = 5 d = 4 print('Minimum number of steps required is', minSteps(n, m, d)) # This code is contributed by Sanket Badhe", "e": 10414, "s": 8627, "text": null }, { "code": "// C# program to implement// the above approachusing System; class GFG{ // Utility function to return GCD of 'a'// and 'b'.public static int gcd(int a, int b){ if (b == 0) return a; return gcd(b, a % b);} /* fromCap -- Capacity of jug from which water is poured toCap -- Capacity of jug to which water is poured d -- Amount to be measured */public static int pour(int fromCap, int toCap, int d){ // Initialize current amount of water // in source and destination jugs int from = fromCap; int to = 0; // Initialize count of steps required int step = 1; // Needed to fill \"from\" Jug // Break the loop when either of the two // jugs has d litre water while (from != d && to != d) { // Find the maximum amount that can be // poured int temp = Math.Min(from, toCap - to); // Pour \"temp\" liters from \"from\" to \"to\" to += temp; from -= temp; // Increment count of steps step++; if (from == d || to == d) break; // If first jug becomes empty, fill it if (from == 0) { from = fromCap; step++; } // If second jug becomes full, empty it if (to == toCap) { to = 0; step++; } } return step;} // Returns count of minimum steps needed to// measure d literpublic static int minSteps(int m, int n, int d){ // To make sure that m is smaller than n if (m > n) { int t = m; m = n; n = t; } // For d > n we cant measure the water // using the jugs if (d > n) return -1; // If gcd of n and m does not divide d // then solution is not possible if ((d % gcd(n, m)) != 0) return -1; // Return minimum two cases: // a) Water of n liter jug is poured into // m liter jug // b) Vice versa of \"a\" return Math.Min(pour(n, m, d), // n to m pour(m, n, d)); // m to n} // Driver Codepublic static void Main(){ int n = 3, m = 5, d = 4; Console.Write(\"Minimum number of \" + \"steps required is \" + minSteps(m, n, d));}} // This code is contributed by code_hunt.", "e": 12731, "s": 10414, "text": null }, { "code": "<script> // Javascript program to count minimum number of// steps required to measure d litres water// using jugs of m liters and n liters capacity. // Utility function to return GCD of 'a' // and 'b'. function gcd(a , b) { if (b == 0) return a; return gcd(b, a % b); } /* fromCap -- Capacity of jug from which water is poured toCap -- Capacity of jug to which water is poured d -- Amount to be measured */ function pour(fromCap , toCap , d) { // Initialize current amount of water // in source and destination jugs var from = fromCap; var to = 0; // Initialize count of steps required var step = 1; // Needed to fill \"from\" Jug // Break the loop when either of the two // jugs has d litre water while (from != d && to != d) { // Find the maximum amount that can be // poured var temp = Math.min(from, toCap - to); // Pour \"temp\" liters from \"from\" to \"to\" to += temp; from -= temp; // Increment count of steps step++; if (from == d || to == d) break; // If first jug becomes empty, fill it if (from == 0) { from = fromCap; step++; } // If second jug becomes full, empty it if (to == toCap) { to = 0; step++; } } return step; } // Returns count of minimum steps needed to // measure d liter function minSteps(m , n , d) { // To make sure that m is smaller than n if (m > n) { var t = m; m = n; n = t; } // For d > n we cant measure the water // using the jugs if (d > n) return -1; // If gcd of n and m does not divide d // then solution is not possible if ((d % gcd(n, m)) != 0) return -1; // Return minimum two cases: // a) Water of n liter jug is poured into // m liter jug // b) Vice versa of \"a\" return Math.min(pour(n, m, d), // n to m pour(m, n, d)); // m to n } // Driver code var n = 3, m = 5, d = 4; document.write(\"Minimum number of \" + \"steps required is \" + minSteps(m, n, d)); // This code contributed by Rajput-Ji </script>", "e": 15186, "s": 12731, "text": null }, { "code": null, "e": 15194, "s": 15186, "text": "Output:" }, { "code": null, "e": 15232, "s": 15194, "text": "Minimum number of steps required is 6" }, { "code": null, "e": 15367, "s": 15232, "text": "Time Complexity: O(N + M)Auxiliary Space: O(1) Another detailed Explanation:http://web.mit.edu/neboat/Public/6.042/numbertheory1.pdf " }, { "code": null, "e": 15756, "s": 15367, "text": "This article is contributed by Madhur Modi. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 15769, "s": 15756, "text": "Sanket Badhe" }, { "code": null, "e": 15780, "s": 15769, "text": "cosine1509" }, { "code": null, "e": 15792, "s": 15780, "text": "hackr4india" }, { "code": null, "e": 15804, "s": 15792, "text": "RohitOberoi" }, { "code": null, "e": 15814, "s": 15804, "text": "Rajput-Ji" }, { "code": null, "e": 15830, "s": 15814, "text": "pankajsharmagfg" }, { "code": null, "e": 15849, "s": 15830, "text": "choudharyrajat1311" }, { "code": null, "e": 15859, "s": 15849, "text": "code_hunt" }, { "code": null, "e": 15870, "s": 15859, "text": "MakeMyTrip" }, { "code": null, "e": 15883, "s": 15870, "text": "MAQ Software" }, { "code": null, "e": 15894, "s": 15883, "text": "Algorithms" }, { "code": null, "e": 15914, "s": 15894, "text": "Dynamic Programming" }, { "code": null, "e": 15925, "s": 15914, "text": "MakeMyTrip" }, { "code": null, "e": 15938, "s": 15925, "text": "MAQ Software" }, { "code": null, "e": 15958, "s": 15938, "text": "Dynamic Programming" }, { "code": null, "e": 15969, "s": 15958, "text": "Algorithms" }, { "code": null, "e": 16067, "s": 15969, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 16092, "s": 16067, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 16141, "s": 16092, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 16179, "s": 16141, "text": "What is Hashing | A Complete Tutorial" }, { "code": null, "e": 16230, "s": 16179, "text": "Understanding Time Complexity with Simple Examples" }, { "code": null, "e": 16266, "s": 16230, "text": "CPU Scheduling in Operating Systems" }, { "code": null, "e": 16298, "s": 16266, "text": "Largest Sum Contiguous Subarray" }, { "code": null, "e": 16328, "s": 16298, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 16357, "s": 16328, "text": "0-1 Knapsack Problem | DP-10" }, { "code": null, "e": 16391, "s": 16357, "text": "Longest Common Subsequence | DP-4" } ]
How to check a string starts/ends with a specific string in jQuery ?
21 Jul, 2021 JavaScript provides a lot of string methods that check whether a string is a substring of other string. So, jQuery wouldn’t be necessary at all to perform this task. However, we will cover all the different ways of checking whether a string starts or ends with a string: startsWith() and endsWith() method search() method indexOf() method substring() method substr() method slice() method Let’s consider a string str = “Welcome to GEEKS FOR GEEKS!!!”. Now we have to find whether the string str starts with startword = “Welcome” and ends with endword = “!!!”. Approaches: startsWith() and endsWith() method: It checks whether a string starts or ends with the specific substring. Example: Javascript if (str.startsWith(startword) && str.endsWith(endword)) { // case sensitive console.log("Yes, The string " + str + " starts with " + startword + " and ends with " + endword);} search() method: It checks whether a particular string is contained in another string and returns the starting index of that substring. Example: Javascript if (str.search(startword)==0 && str.search(endword)==stringlength-endwordlength ) { // case sensitive console.log("Yes, The string " + str + " starts with " + startword + " and ends with " + endword);} indexOf() method: As the name suggests, it finds the starting index of a substring in the string. Example: Javascript if (str.indexOf(startword)==0 && str.indexOf(endword)==stringlength-endwordlength) { console.log("Yes, The string " + str + " starts with " + startword + " and ends with " + endword);} substring() method: It returns a string present between start and end index. Example: Javascript if(str.substring(0, startwordlength)==startword && str.substring(stringlength-endwordlength, stringlength)==endword) { console.log("Yes, The string " + str + " starts with " + startword + " and ends with " + endword);} substr() method: It is similar to substring() method but takes start index and length of substring as parameters. Example: Javascript if(str.substr(0, startwordlength)==startword && str.substr(stringlength-endwordlength, endwordlength)==endword) { console.log("Yes, The string " + str + " starts with " + startword + " and ends with " + endword);} slice() method: This method returns the slices of string between any two indices in a string. Example: Javascript if(str.slice(0, startwordlength)==startword && str.slice(stringlength-endwordlength, stringlength)==endword) { console.log("Yes, The string " + str + " starts with " + startword + " and ends with " + endword);} Let’s take an example of text in h1 element and check whether it starts and ends with the given substring. Javascript <!DOCTYPE html><html> <head> <title> How to know that a string starts/ends with a specific string in jQuery? </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script></head> <body> <h1 id="text"> Welcome To GEEKS FOR GEEKS!!! </h1> <h2> Check whether a word is present in the above sentence </h2> <input type="text" id="startkey"> <input type="text" id="endkey"> <button onclick="MyFunction()"> Check </button> <h2> startsWith() and endsWith() method </h2> <h2 id="startswith"> </h2> <h2> indexOf() method </h2> <h2 id="indexOf"></h2> <h2> search() method </h2> <h2 id="search"></h2> <h2> substring() method </h2> <h2 id="substring"></h2> <h2> substr() method </h2> <h2 id="substr"> </h2> <h2> slice() method </h2> <h2 id="slice"></h2> <script> var str = document.getElementById("text").innerText; stringlength = str.length; var startword = ""; var endword = ""; function MyFunction() { startword = document.getElementById("startkey").value; endword = document.getElementById("endkey").value; console.log(startword); console.log(endword) startwordlength = startword.length; endwordlength = endword.length; if (str.startsWith(startword) && str.endsWith(endword)) { // case sensitive var h2 = document.getElementById("startswith"); h2.innerHTML = "Yes, The string " + str + " starts with " + startword + " and ends with " + endword; } else { var h2 = document.getElementById("startswith"); h2.innerHTML = "No, The string " + str + " doesn't start and endwith the given words"; } //Js if (str.indexOf(startword) == 0 && str.indexOf( endword) == stringlength - endwordlength) { var h2 = document.getElementById("indexOf"); h2.innerHTML = "Yes, The string " + str + " starts with " + startword + " and ends with " + endword; } else { var h2 = document.getElementById("indexOf"); h2.innerHTML = "No, The string " + str + " doesn't start and endwith the given words"; } //Js if (str.search( startword) == 0 && str.search(endword) == stringlength - endwordlength) { // case sensitive var h2 = document.getElementById("search"); h2.innerHTML = "Yes, The string " + str + " starts with " + startword + " and ends with " + endword; } else { var h2 = document.getElementById("search"); h2.innerHTML = "No, The string " + str + " doesn't start and endwith the given words"; } //Js if (str.substring( 0, startwordlength) == startword && str.substring( stringlength - endwordlength, stringlength) == endword) { var h2 = document.getElementById("substring"); h2.innerHTML = "Yes, The string " + str + " starts with " + startword + " and ends with " + endword; } else { var h2 = document.getElementById("substring"); h2.innerHTML = "No, The string " + str + " doesn't start and endwith the given words"; } if (str.substr( 0, startwordlength) == startword && str.substr( stringlength - endwordlength, endwordlength) == endword) { var h2 = document.getElementById("substr"); h2.innerHTML = "Yes, The string " + str + " starts with " + startword + " and ends with " + endword; } else { var h2 = document.getElementById("substr"); h2.innerHTML = "No, The string " + str + " doesn't start and endwith the given words"; } if (str.slice( 0, startwordlength) == startword && str.slice( stringlength - endwordlength, stringlength) == endword) { var h2 = document.getElementById("slice"); h2.innerHTML = "Yes, The string " + str + " starts with " + startword + " and ends with " + endword; } else { var h2 = document.getElementById("slice"); h2.innerHTML = "No, The string " + str + " doesn't start and endwith the given words"; } } </script></body> </html> Output: varshagumber28 HTML-Misc JavaScript-Misc jQuery-Misc Picked HTML JavaScript JQuery Web technologies Questions Write From Home HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? REST API (Introduction) Hide or show elements in HTML using display property Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Hide or show elements in HTML using display property Roadmap to Learn JavaScript For Beginners
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Jul, 2021" }, { "code": null, "e": 300, "s": 28, "text": "JavaScript provides a lot of string methods that check whether a string is a substring of other string. So, jQuery wouldn’t be necessary at all to perform this task. However, we will cover all the different ways of checking whether a string starts or ends with a string: " }, { "code": null, "e": 335, "s": 300, "text": "startsWith() and endsWith() method" }, { "code": null, "e": 351, "s": 335, "text": "search() method" }, { "code": null, "e": 368, "s": 351, "text": "indexOf() method" }, { "code": null, "e": 387, "s": 368, "text": "substring() method" }, { "code": null, "e": 403, "s": 387, "text": "substr() method" }, { "code": null, "e": 418, "s": 403, "text": "slice() method" }, { "code": null, "e": 589, "s": 418, "text": "Let’s consider a string str = “Welcome to GEEKS FOR GEEKS!!!”. Now we have to find whether the string str starts with startword = “Welcome” and ends with endword = “!!!”." }, { "code": null, "e": 708, "s": 589, "text": "Approaches: startsWith() and endsWith() method: It checks whether a string starts or ends with the specific substring." }, { "code": null, "e": 719, "s": 708, "text": "Example: " }, { "code": null, "e": 730, "s": 719, "text": "Javascript" }, { "code": "if (str.startsWith(startword) && str.endsWith(endword)) { // case sensitive console.log(\"Yes, The string \" + str + \" starts with \" + startword + \" and ends with \" + endword);}", "e": 924, "s": 730, "text": null }, { "code": null, "e": 1060, "s": 924, "text": "search() method: It checks whether a particular string is contained in another string and returns the starting index of that substring." }, { "code": null, "e": 1071, "s": 1060, "text": "Example: " }, { "code": null, "e": 1082, "s": 1071, "text": "Javascript" }, { "code": "if (str.search(startword)==0 && str.search(endword)==stringlength-endwordlength ) { // case sensitive console.log(\"Yes, The string \" + str + \" starts with \" + startword + \" and ends with \" + endword);}", "e": 1305, "s": 1082, "text": null }, { "code": null, "e": 1403, "s": 1305, "text": "indexOf() method: As the name suggests, it finds the starting index of a substring in the string." }, { "code": null, "e": 1413, "s": 1403, "text": "Example: " }, { "code": null, "e": 1424, "s": 1413, "text": "Javascript" }, { "code": "if (str.indexOf(startword)==0 && str.indexOf(endword)==stringlength-endwordlength) { console.log(\"Yes, The string \" + str + \" starts with \" + startword + \" and ends with \" + endword);}", "e": 1639, "s": 1424, "text": null }, { "code": null, "e": 1716, "s": 1639, "text": "substring() method: It returns a string present between start and end index." }, { "code": null, "e": 1727, "s": 1716, "text": "Example: " }, { "code": null, "e": 1738, "s": 1727, "text": "Javascript" }, { "code": "if(str.substring(0, startwordlength)==startword && str.substring(stringlength-endwordlength, stringlength)==endword) { console.log(\"Yes, The string \" + str + \" starts with \" + startword + \" and ends with \" + endword);}", "e": 1994, "s": 1738, "text": null }, { "code": null, "e": 2108, "s": 1994, "text": "substr() method: It is similar to substring() method but takes start index and length of substring as parameters." }, { "code": null, "e": 2118, "s": 2108, "text": "Example: " }, { "code": null, "e": 2129, "s": 2118, "text": "Javascript" }, { "code": "if(str.substr(0, startwordlength)==startword && str.substr(stringlength-endwordlength, endwordlength)==endword) { console.log(\"Yes, The string \" + str + \" starts with \" + startword + \" and ends with \" + endword);}", "e": 2372, "s": 2129, "text": null }, { "code": null, "e": 2466, "s": 2372, "text": "slice() method: This method returns the slices of string between any two indices in a string." }, { "code": null, "e": 2477, "s": 2466, "text": "Example: " }, { "code": null, "e": 2488, "s": 2477, "text": "Javascript" }, { "code": "if(str.slice(0, startwordlength)==startword && str.slice(stringlength-endwordlength, stringlength)==endword) { console.log(\"Yes, The string \" + str + \" starts with \" + startword + \" and ends with \" + endword);}", "e": 2728, "s": 2488, "text": null }, { "code": null, "e": 2836, "s": 2728, "text": "Let’s take an example of text in h1 element and check whether it starts and ends with the given substring. " }, { "code": null, "e": 2847, "s": 2836, "text": "Javascript" }, { "code": "<!DOCTYPE html><html> <head> <title> How to know that a string starts/ends with a specific string in jQuery? </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script></head> <body> <h1 id=\"text\"> Welcome To GEEKS FOR GEEKS!!! </h1> <h2> Check whether a word is present in the above sentence </h2> <input type=\"text\" id=\"startkey\"> <input type=\"text\" id=\"endkey\"> <button onclick=\"MyFunction()\"> Check </button> <h2> startsWith() and endsWith() method </h2> <h2 id=\"startswith\"> </h2> <h2> indexOf() method </h2> <h2 id=\"indexOf\"></h2> <h2> search() method </h2> <h2 id=\"search\"></h2> <h2> substring() method </h2> <h2 id=\"substring\"></h2> <h2> substr() method </h2> <h2 id=\"substr\"> </h2> <h2> slice() method </h2> <h2 id=\"slice\"></h2> <script> var str = document.getElementById(\"text\").innerText; stringlength = str.length; var startword = \"\"; var endword = \"\"; function MyFunction() { startword = document.getElementById(\"startkey\").value; endword = document.getElementById(\"endkey\").value; console.log(startword); console.log(endword) startwordlength = startword.length; endwordlength = endword.length; if (str.startsWith(startword) && str.endsWith(endword)) { // case sensitive var h2 = document.getElementById(\"startswith\"); h2.innerHTML = \"Yes, The string \" + str + \" starts with \" + startword + \" and ends with \" + endword; } else { var h2 = document.getElementById(\"startswith\"); h2.innerHTML = \"No, The string \" + str + \" doesn't start and endwith the given words\"; } //Js if (str.indexOf(startword) == 0 && str.indexOf( endword) == stringlength - endwordlength) { var h2 = document.getElementById(\"indexOf\"); h2.innerHTML = \"Yes, The string \" + str + \" starts with \" + startword + \" and ends with \" + endword; } else { var h2 = document.getElementById(\"indexOf\"); h2.innerHTML = \"No, The string \" + str + \" doesn't start and endwith the given words\"; } //Js if (str.search( startword) == 0 && str.search(endword) == stringlength - endwordlength) { // case sensitive var h2 = document.getElementById(\"search\"); h2.innerHTML = \"Yes, The string \" + str + \" starts with \" + startword + \" and ends with \" + endword; } else { var h2 = document.getElementById(\"search\"); h2.innerHTML = \"No, The string \" + str + \" doesn't start and endwith the given words\"; } //Js if (str.substring( 0, startwordlength) == startword && str.substring( stringlength - endwordlength, stringlength) == endword) { var h2 = document.getElementById(\"substring\"); h2.innerHTML = \"Yes, The string \" + str + \" starts with \" + startword + \" and ends with \" + endword; } else { var h2 = document.getElementById(\"substring\"); h2.innerHTML = \"No, The string \" + str + \" doesn't start and endwith the given words\"; } if (str.substr( 0, startwordlength) == startword && str.substr( stringlength - endwordlength, endwordlength) == endword) { var h2 = document.getElementById(\"substr\"); h2.innerHTML = \"Yes, The string \" + str + \" starts with \" + startword + \" and ends with \" + endword; } else { var h2 = document.getElementById(\"substr\"); h2.innerHTML = \"No, The string \" + str + \" doesn't start and endwith the given words\"; } if (str.slice( 0, startwordlength) == startword && str.slice( stringlength - endwordlength, stringlength) == endword) { var h2 = document.getElementById(\"slice\"); h2.innerHTML = \"Yes, The string \" + str + \" starts with \" + startword + \" and ends with \" + endword; } else { var h2 = document.getElementById(\"slice\"); h2.innerHTML = \"No, The string \" + str + \" doesn't start and endwith the given words\"; } } </script></body> </html>", "e": 7934, "s": 2847, "text": null }, { "code": null, "e": 7943, "s": 7934, "text": "Output: " }, { "code": null, "e": 7960, "s": 7945, "text": "varshagumber28" }, { "code": null, "e": 7970, "s": 7960, "text": "HTML-Misc" }, { "code": null, "e": 7986, "s": 7970, "text": "JavaScript-Misc" }, { "code": null, "e": 7998, "s": 7986, "text": "jQuery-Misc" }, { "code": null, "e": 8005, "s": 7998, "text": "Picked" }, { "code": null, "e": 8010, "s": 8005, "text": "HTML" }, { "code": null, "e": 8021, "s": 8010, "text": "JavaScript" }, { "code": null, "e": 8028, "s": 8021, "text": "JQuery" }, { "code": null, "e": 8055, "s": 8028, "text": "Web technologies Questions" }, { "code": null, "e": 8071, "s": 8055, "text": "Write From Home" }, { "code": null, "e": 8076, "s": 8071, "text": "HTML" }, { "code": null, "e": 8174, "s": 8076, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8222, "s": 8174, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 8284, "s": 8222, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 8334, "s": 8284, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 8358, "s": 8334, "text": "REST API (Introduction)" }, { "code": null, "e": 8411, "s": 8358, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 8472, "s": 8411, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 8544, "s": 8472, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 8584, "s": 8544, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 8637, "s": 8584, "text": "Hide or show elements in HTML using display property" } ]
COVID-19 Tracker using ReactJS and real time API
09 Sep, 2021 In this article, we will create a web application COVID-19 Tracker using ReactJS and real-time API. In this web application or website, when the user enters the name of the country, it will display the number of active cases, recovered cases, today’s cases, etc. Pre-requisites: Basic JavaScript such as functions, types of variables, objects, etc. ReactJS development setup for web development. ReactJS Hooks such as useState Hook and useEffect Hook. APIs knowledge to fetch real-time data. Basic CSS properties for styling and designing for the web application. Approach: Set up the development environment, install all the required dependencies. In the App.js file, create and initialise a component that is used to hold the code of the web application. In that JavaScript file, create a form to take the input from the user and fetch and display the details using real-time API and react useState Hook and useEffect Hook. Use CSS for stylings of the component file and import the CSS file in the component file. Note: Please refer to the ReactJS Setting up article to set up the development environment. Below is the step by the step implementation of the above approach. Step 1: Create a React application using the following command: npx create-react-app foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command: cd foldername In that created folder go to src folder and delete App.test.js, logo.svg and setupTests.js because these files are not required in this project and add component files used to hold the code for the application. Our component name is CovidData and file name is CovidData.js and for stylings add CSS file CovidData.css. Project Structure: It will look like the following. Project Structure Step 3: Now, in App.js, we will create the component file, that will hold the code for the application. App.js Javascript import "./App.css";import CovidData from "./CovidData"; function App() { return <div className="App"> <CovidData/> </div>;} export default App; Note: Our component name is CovidData and we have imported this component file in App.js. Step 4: In the CovidData.js file, we will create the form to take the input and when the form is submitted then we will fetch the data from the API with the help of useEffect Hook and set the fetched the in the variable objects using useState Hook. When the data is fetched then pass the variable objects using JSX expression to display the data. To get data, real-time API we have used the “https://disease.sh/v3/covid-19/countries” API. CovidData.js Javascript import React, { useEffect, useState } from "react";import "./CovidData.css"; function CovidData() { const [country, setCountry] = useState(""); const [cases, setCases] = useState(""); const [recovered, setRecovered] = useState(""); const [deaths, setDeaths] = useState(""); const [todayCases, setTodayCases] = useState(""); const [deathCases, setDeathCases] = useState(""); const [recoveredCases, setRecoveredCases] = useState(""); const [userInput, setUserInput] = useState(""); useEffect(() => { fetch("https://disease.sh/v3/covid-19/countries") .then((res) => res.json()) .then((data) => { setData(data); }); }, []); const setData = ({ country, cases, deaths, recovered, todayCases, todayDeaths, todayRecovered, }) => { setCountry(country); setCases(cases); setRecovered(recovered); setDeaths(deaths); setTodayCases(todayCases); setDeathCases(todayDeaths); setRecoveredCases(todayRecovered); }; const handleSearch = (e) => { setUserInput(e.target.value); }; const handleSubmit = (props) => { props.preventDefault(); fetch(`https://disease.sh/v3/covid-19/countries/${userInput}`) .then((res) => res.json()) .then((data) => { setData(data); }); }; return ( <div className="covidData"> <h1>COVID-19 CASES COUNTRY WISE</h1> <div className="covidData__input"> <form onSubmit={handleSubmit}> {/* input county name */} <input onChange={handleSearch} placeholder="Enter Country Name" /> <br /> <button type="submit">Search</button> </form> </div> {/* Showing the details of the country */} <div className="covidData__country__info"> <p>Country Name : {country} </p> <p>Cases : {cases}</p> <p>Deaths : {deaths}</p> <p>Recovered : {recovered}</p> <p>Cases Today : {todayCases}</p> <p>Deaths Today : {deathCases}</p> <p>Recovered Today : {recoveredCases}</p> </div> </div> );} export default CovidData; Step 5: For stylings, we have used basic CSS properties such as alignment, font style, etc. CovidData.css CSS body { background-color: rgb(102, 226, 102);}.covidData { background-color: green; width: 30%; margin: auto; margin-top: 15px; border-radius: 6px; padding: 10px;} /* input stylings */ .covidData__form { padding: 10px; margin: 20px;}.covidData__input input { width: 400px; height: 50px; text-align: center; font-size: 25px; font-family: Verdana, Geneva, Tahoma, sans-serif;}.covidData__input button { width: 80px; height: 50px; margin-top: 10px; background-color: black; color: white; font-size: 20px; border-radius: 10px; border: none; box-shadow: 5px 5px 5px rgb(71, 67, 67); cursor: pointer;} /* detail stylings */ .covidData__country__info { font-size: 20px; font-family: Verdana, Geneva, Tahoma, sans-serif; width: 500px; margin-left: auto; margin-right: auto; height: auto; padding-left: 10px; background-color: white; margin-top: 20px; padding: 2px; text-shadow: 1px 1px 1px rgb(71, 67, 67); box-shadow: 5px 5px 5px rgb(71, 67, 67);} Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: CSS-Properties React-Questions ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Axios in React: A Guide for Beginners ReactJS useNavigate() Hook How to install bootstrap in React.js ? How to create a multi-page website using React.js ? How to do crud operations in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? Differences between Functional Components and Class Components in React
[ { "code": null, "e": 54, "s": 26, "text": "\n09 Sep, 2021" }, { "code": null, "e": 317, "s": 54, "text": "In this article, we will create a web application COVID-19 Tracker using ReactJS and real-time API. In this web application or website, when the user enters the name of the country, it will display the number of active cases, recovered cases, today’s cases, etc." }, { "code": null, "e": 333, "s": 317, "text": "Pre-requisites:" }, { "code": null, "e": 403, "s": 333, "text": "Basic JavaScript such as functions, types of variables, objects, etc." }, { "code": null, "e": 450, "s": 403, "text": "ReactJS development setup for web development." }, { "code": null, "e": 506, "s": 450, "text": "ReactJS Hooks such as useState Hook and useEffect Hook." }, { "code": null, "e": 546, "s": 506, "text": "APIs knowledge to fetch real-time data." }, { "code": null, "e": 618, "s": 546, "text": "Basic CSS properties for styling and designing for the web application." }, { "code": null, "e": 628, "s": 618, "text": "Approach:" }, { "code": null, "e": 703, "s": 628, "text": "Set up the development environment, install all the required dependencies." }, { "code": null, "e": 811, "s": 703, "text": "In the App.js file, create and initialise a component that is used to hold the code of the web application." }, { "code": null, "e": 980, "s": 811, "text": "In that JavaScript file, create a form to take the input from the user and fetch and display the details using real-time API and react useState Hook and useEffect Hook." }, { "code": null, "e": 1070, "s": 980, "text": "Use CSS for stylings of the component file and import the CSS file in the component file." }, { "code": null, "e": 1162, "s": 1070, "text": "Note: Please refer to the ReactJS Setting up article to set up the development environment." }, { "code": null, "e": 1230, "s": 1162, "text": "Below is the step by the step implementation of the above approach." }, { "code": null, "e": 1294, "s": 1230, "text": "Step 1: Create a React application using the following command:" }, { "code": null, "e": 1326, "s": 1294, "text": "npx create-react-app foldername" }, { "code": null, "e": 1426, "s": 1326, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:" }, { "code": null, "e": 1440, "s": 1426, "text": "cd foldername" }, { "code": null, "e": 1758, "s": 1440, "text": "In that created folder go to src folder and delete App.test.js, logo.svg and setupTests.js because these files are not required in this project and add component files used to hold the code for the application. Our component name is CovidData and file name is CovidData.js and for stylings add CSS file CovidData.css." }, { "code": null, "e": 1810, "s": 1758, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 1828, "s": 1810, "text": "Project Structure" }, { "code": null, "e": 1932, "s": 1828, "text": "Step 3: Now, in App.js, we will create the component file, that will hold the code for the application." }, { "code": null, "e": 1939, "s": 1932, "text": "App.js" }, { "code": null, "e": 1950, "s": 1939, "text": "Javascript" }, { "code": "import \"./App.css\";import CovidData from \"./CovidData\"; function App() { return <div className=\"App\"> <CovidData/> </div>;} export default App;", "e": 2101, "s": 1950, "text": null }, { "code": null, "e": 2191, "s": 2101, "text": "Note: Our component name is CovidData and we have imported this component file in App.js." }, { "code": null, "e": 2630, "s": 2191, "text": "Step 4: In the CovidData.js file, we will create the form to take the input and when the form is submitted then we will fetch the data from the API with the help of useEffect Hook and set the fetched the in the variable objects using useState Hook. When the data is fetched then pass the variable objects using JSX expression to display the data. To get data, real-time API we have used the “https://disease.sh/v3/covid-19/countries” API." }, { "code": null, "e": 2643, "s": 2630, "text": "CovidData.js" }, { "code": null, "e": 2654, "s": 2643, "text": "Javascript" }, { "code": "import React, { useEffect, useState } from \"react\";import \"./CovidData.css\"; function CovidData() { const [country, setCountry] = useState(\"\"); const [cases, setCases] = useState(\"\"); const [recovered, setRecovered] = useState(\"\"); const [deaths, setDeaths] = useState(\"\"); const [todayCases, setTodayCases] = useState(\"\"); const [deathCases, setDeathCases] = useState(\"\"); const [recoveredCases, setRecoveredCases] = useState(\"\"); const [userInput, setUserInput] = useState(\"\"); useEffect(() => { fetch(\"https://disease.sh/v3/covid-19/countries\") .then((res) => res.json()) .then((data) => { setData(data); }); }, []); const setData = ({ country, cases, deaths, recovered, todayCases, todayDeaths, todayRecovered, }) => { setCountry(country); setCases(cases); setRecovered(recovered); setDeaths(deaths); setTodayCases(todayCases); setDeathCases(todayDeaths); setRecoveredCases(todayRecovered); }; const handleSearch = (e) => { setUserInput(e.target.value); }; const handleSubmit = (props) => { props.preventDefault(); fetch(`https://disease.sh/v3/covid-19/countries/${userInput}`) .then((res) => res.json()) .then((data) => { setData(data); }); }; return ( <div className=\"covidData\"> <h1>COVID-19 CASES COUNTRY WISE</h1> <div className=\"covidData__input\"> <form onSubmit={handleSubmit}> {/* input county name */} <input onChange={handleSearch} placeholder=\"Enter Country Name\" /> <br /> <button type=\"submit\">Search</button> </form> </div> {/* Showing the details of the country */} <div className=\"covidData__country__info\"> <p>Country Name : {country} </p> <p>Cases : {cases}</p> <p>Deaths : {deaths}</p> <p>Recovered : {recovered}</p> <p>Cases Today : {todayCases}</p> <p>Deaths Today : {deathCases}</p> <p>Recovered Today : {recoveredCases}</p> </div> </div> );} export default CovidData;", "e": 4725, "s": 2654, "text": null }, { "code": null, "e": 4817, "s": 4725, "text": "Step 5: For stylings, we have used basic CSS properties such as alignment, font style, etc." }, { "code": null, "e": 4831, "s": 4817, "text": "CovidData.css" }, { "code": null, "e": 4835, "s": 4831, "text": "CSS" }, { "code": "body { background-color: rgb(102, 226, 102);}.covidData { background-color: green; width: 30%; margin: auto; margin-top: 15px; border-radius: 6px; padding: 10px;} /* input stylings */ .covidData__form { padding: 10px; margin: 20px;}.covidData__input input { width: 400px; height: 50px; text-align: center; font-size: 25px; font-family: Verdana, Geneva, Tahoma, sans-serif;}.covidData__input button { width: 80px; height: 50px; margin-top: 10px; background-color: black; color: white; font-size: 20px; border-radius: 10px; border: none; box-shadow: 5px 5px 5px rgb(71, 67, 67); cursor: pointer;} /* detail stylings */ .covidData__country__info { font-size: 20px; font-family: Verdana, Geneva, Tahoma, sans-serif; width: 500px; margin-left: auto; margin-right: auto; height: auto; padding-left: 10px; background-color: white; margin-top: 20px; padding: 2px; text-shadow: 1px 1px 1px rgb(71, 67, 67); box-shadow: 5px 5px 5px rgb(71, 67, 67);}", "e": 5815, "s": 4835, "text": null }, { "code": null, "e": 5928, "s": 5815, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 5938, "s": 5928, "text": "npm start" }, { "code": null, "e": 6037, "s": 5938, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 6052, "s": 6037, "text": "CSS-Properties" }, { "code": null, "e": 6068, "s": 6052, "text": "React-Questions" }, { "code": null, "e": 6076, "s": 6068, "text": "ReactJS" }, { "code": null, "e": 6093, "s": 6076, "text": "Web Technologies" }, { "code": null, "e": 6191, "s": 6093, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6229, "s": 6191, "text": "Axios in React: A Guide for Beginners" }, { "code": null, "e": 6256, "s": 6229, "text": "ReactJS useNavigate() Hook" }, { "code": null, "e": 6295, "s": 6256, "text": "How to install bootstrap in React.js ?" }, { "code": null, "e": 6347, "s": 6295, "text": "How to create a multi-page website using React.js ?" }, { "code": null, "e": 6386, "s": 6347, "text": "How to do crud operations in ReactJS ?" }, { "code": null, "e": 6448, "s": 6386, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 6481, "s": 6448, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 6542, "s": 6481, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 6592, "s": 6542, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Sorting Custom Object by Implementing Comparable Interface in Java
28 Dec, 2020 Java provides two interfaces to sort objects using data members of the class which are Comparable and Comparator. In this article, we will focus on a Comparable interface. A Comparable object is capable of comparing itself with another object by natural ordering. The class must implement the java.lang.Comparable interface to compare its instances. Using Comparable interface we can sort: String objects Wrapper class objects User-defined objects Syntax public interface Comparable<T> { public int compareTo(T o); } Where T is the type of Object to be sorted. compareTo() method For any class to support sorting, it should implement the Comparable interface and override it’s compareTo() method. It returns a negative integer if an object is less than the specified object, returns zero if an object is equal, and returns a positive integer if an object is greater than the specified object. Example 1: Sort the given data according to the student marks. Java // Java program to sort student// data according to their marks import java.util.*; // implementing comparable interfaceclass StudentData implements Comparable<StudentData> { String name; int marks; // Constructor StudentData(String name, int marks) { this.name = name; this.marks = marks; } // overriding method to sort // the student data public int compareTo(StudentData sd) { return this.marks - sd.marks; }} // Driver classclass GFG { public static void main(String[] args) { ArrayList<StudentData> list = new ArrayList<StudentData>(); // Inserting data list.add(new StudentData("Ram", 98)); list.add(new StudentData("Shyam", 84)); list.add(new StudentData("Lokesh", 90)); Collections.sort(list); // Displaying data for (StudentData sd : list) System.out.println(sd.name + " " + sd.marks); }} Shyam 84 Lokesh 90 Ram 98 Example 2: Sort the given data according to the names. Java // Java program to sort student// data according to their names import java.util.*; // implementing comparable interfaceclass StudentData implements Comparable<StudentData> { int roll; String name; int marks; // Constructor StudentData(int roll, String name, int marks) { this.roll = roll; this.name = name; this.marks = marks; } // overriding method to sort // the student data public int compareTo(StudentData sd) { // compareTo is a string method return this.name.compareTo(sd.name); }} // Driver classclass GFG { public static void main(String[] args) { ArrayList<StudentData> list = new ArrayList<StudentData>(); // Inserting data list.add(new StudentData(1, "Ram", 98)); list.add(new StudentData(2, "Shyam", 84)); list.add(new StudentData(3, "Lokesh", 90)); Collections.sort(list); // Displaying data for (StudentData sd : list) System.out.println(sd.roll + " " + sd.name + " " + sd.marks); }} 3 Lokesh 90 1 Ram 98 2 Shyam 84 Picked Technical Scripter 2020 Java Java Programs Technical Scripter Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Introduction to Java Constructors in Java Exceptions in Java Generics in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class Factory method design pattern in Java Java Program to Remove Duplicate Elements From the Array
[ { "code": null, "e": 52, "s": 24, "text": "\n28 Dec, 2020" }, { "code": null, "e": 403, "s": 52, "text": "Java provides two interfaces to sort objects using data members of the class which are Comparable and Comparator. In this article, we will focus on a Comparable interface. A Comparable object is capable of comparing itself with another object by natural ordering. The class must implement the java.lang.Comparable interface to compare its instances. " }, { "code": null, "e": 443, "s": 403, "text": "Using Comparable interface we can sort:" }, { "code": null, "e": 458, "s": 443, "text": "String objects" }, { "code": null, "e": 480, "s": 458, "text": "Wrapper class objects" }, { "code": null, "e": 501, "s": 480, "text": "User-defined objects" }, { "code": null, "e": 508, "s": 501, "text": "Syntax" }, { "code": null, "e": 575, "s": 508, "text": "public interface Comparable<T> \n{\n public int compareTo(T o);\n}" }, { "code": null, "e": 619, "s": 575, "text": "Where T is the type of Object to be sorted." }, { "code": null, "e": 638, "s": 619, "text": "compareTo() method" }, { "code": null, "e": 951, "s": 638, "text": "For any class to support sorting, it should implement the Comparable interface and override it’s compareTo() method. It returns a negative integer if an object is less than the specified object, returns zero if an object is equal, and returns a positive integer if an object is greater than the specified object." }, { "code": null, "e": 1014, "s": 951, "text": "Example 1: Sort the given data according to the student marks." }, { "code": null, "e": 1019, "s": 1014, "text": "Java" }, { "code": "// Java program to sort student// data according to their marks import java.util.*; // implementing comparable interfaceclass StudentData implements Comparable<StudentData> { String name; int marks; // Constructor StudentData(String name, int marks) { this.name = name; this.marks = marks; } // overriding method to sort // the student data public int compareTo(StudentData sd) { return this.marks - sd.marks; }} // Driver classclass GFG { public static void main(String[] args) { ArrayList<StudentData> list = new ArrayList<StudentData>(); // Inserting data list.add(new StudentData(\"Ram\", 98)); list.add(new StudentData(\"Shyam\", 84)); list.add(new StudentData(\"Lokesh\", 90)); Collections.sort(list); // Displaying data for (StudentData sd : list) System.out.println(sd.name + \" \" + sd.marks); }}", "e": 1975, "s": 1019, "text": null }, { "code": null, "e": 2001, "s": 1975, "text": "Shyam 84\nLokesh 90\nRam 98" }, { "code": null, "e": 2056, "s": 2001, "text": "Example 2: Sort the given data according to the names." }, { "code": null, "e": 2061, "s": 2056, "text": "Java" }, { "code": "// Java program to sort student// data according to their names import java.util.*; // implementing comparable interfaceclass StudentData implements Comparable<StudentData> { int roll; String name; int marks; // Constructor StudentData(int roll, String name, int marks) { this.roll = roll; this.name = name; this.marks = marks; } // overriding method to sort // the student data public int compareTo(StudentData sd) { // compareTo is a string method return this.name.compareTo(sd.name); }} // Driver classclass GFG { public static void main(String[] args) { ArrayList<StudentData> list = new ArrayList<StudentData>(); // Inserting data list.add(new StudentData(1, \"Ram\", 98)); list.add(new StudentData(2, \"Shyam\", 84)); list.add(new StudentData(3, \"Lokesh\", 90)); Collections.sort(list); // Displaying data for (StudentData sd : list) System.out.println(sd.roll + \" \" + sd.name + \" \" + sd.marks); }}", "e": 3168, "s": 2061, "text": null }, { "code": null, "e": 3200, "s": 3168, "text": "3 Lokesh 90\n1 Ram 98\n2 Shyam 84" }, { "code": null, "e": 3207, "s": 3200, "text": "Picked" }, { "code": null, "e": 3231, "s": 3207, "text": "Technical Scripter 2020" }, { "code": null, "e": 3236, "s": 3231, "text": "Java" }, { "code": null, "e": 3250, "s": 3236, "text": "Java Programs" }, { "code": null, "e": 3269, "s": 3250, "text": "Technical Scripter" }, { "code": null, "e": 3274, "s": 3269, "text": "Java" }, { "code": null, "e": 3372, "s": 3274, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3387, "s": 3372, "text": "Stream In Java" }, { "code": null, "e": 3408, "s": 3387, "text": "Introduction to Java" }, { "code": null, "e": 3429, "s": 3408, "text": "Constructors in Java" }, { "code": null, "e": 3448, "s": 3429, "text": "Exceptions in Java" }, { "code": null, "e": 3465, "s": 3448, "text": "Generics in Java" }, { "code": null, "e": 3491, "s": 3465, "text": "Java Programming Examples" }, { "code": null, "e": 3525, "s": 3491, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 3572, "s": 3525, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 3610, "s": 3572, "text": "Factory method design pattern in Java" } ]
How to Convert a String value to Byte value in Java with Examples
29 Jan, 2020 Given a String “str” in Java, the task is to convert this string to byte type. Examples: Input: str = "1" Output: 1 Input: str = "3" Output: 3 Approach 1: (Naive Method)One method is to traverse the string and add the numbers one by one to the byte type. This method is not an efficient approach. Approach 2: (Using Byte.parseByte() method)The simplest way to do so is using parseByte() method of Byte class in java.lang package. This method takes the string to be parsed and returns the byte type from it. If not convertible, this method throws error. Syntax: Byte.parseByte(str); Below is the implementation of the above approach: Example 1: To show successful conversion // Java Program to convert string to byte class GFG { // Function to convert String to Byte public static byte convertStringToByte(String str) { // Convert string to byte // using parseByte() method return Byte.parseByte(str); } // Driver code public static void main(String[] args) { // The string value String stringValue = "1"; // The expected byte value byte byteValue; // Convert string to byte byteValue = convertStringToByte(stringValue); // Print the expected byte value System.out.println( stringValue + " after converting into byte = " + byteValue); }} 1 after converting into byte = 1 Approach 3: (Using Byte.valueOf() method)The valueOf() method of Byte class converts data from its internal form into human-readable form. Syntax: Byte.valueOf(str); Below is the implementation of the above approach: Example 1: To show successful conversion // Java Program to convert string to byte class GFG { // Function to convert String to Byte public static byte convertStringToByte(String str) { // Convert string to byte // using valueOf() method return Byte.valueOf(str); } // Driver code public static void main(String[] args) { // The string value String stringValue = "1"; // The expected byte value byte byteValue; // Convert string to byte byteValue = convertStringToByte(stringValue); // Print the expected byte value System.out.println( stringValue + " after converting into byte = " + byteValue); }} 1 after converting into byte = 1 Java-Byte Java-Data Types Java-String-Programs Java-Strings Java Java Programs Java-Strings Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Jan, 2020" }, { "code": null, "e": 107, "s": 28, "text": "Given a String “str” in Java, the task is to convert this string to byte type." }, { "code": null, "e": 117, "s": 107, "text": "Examples:" }, { "code": null, "e": 173, "s": 117, "text": "Input: str = \"1\"\nOutput: 1\n\nInput: str = \"3\"\nOutput: 3\n" }, { "code": null, "e": 327, "s": 173, "text": "Approach 1: (Naive Method)One method is to traverse the string and add the numbers one by one to the byte type. This method is not an efficient approach." }, { "code": null, "e": 583, "s": 327, "text": "Approach 2: (Using Byte.parseByte() method)The simplest way to do so is using parseByte() method of Byte class in java.lang package. This method takes the string to be parsed and returns the byte type from it. If not convertible, this method throws error." }, { "code": null, "e": 591, "s": 583, "text": "Syntax:" }, { "code": null, "e": 613, "s": 591, "text": "Byte.parseByte(str);\n" }, { "code": null, "e": 664, "s": 613, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 705, "s": 664, "text": "Example 1: To show successful conversion" }, { "code": "// Java Program to convert string to byte class GFG { // Function to convert String to Byte public static byte convertStringToByte(String str) { // Convert string to byte // using parseByte() method return Byte.parseByte(str); } // Driver code public static void main(String[] args) { // The string value String stringValue = \"1\"; // The expected byte value byte byteValue; // Convert string to byte byteValue = convertStringToByte(stringValue); // Print the expected byte value System.out.println( stringValue + \" after converting into byte = \" + byteValue); }}", "e": 1417, "s": 705, "text": null }, { "code": null, "e": 1451, "s": 1417, "text": "1 after converting into byte = 1\n" }, { "code": null, "e": 1590, "s": 1451, "text": "Approach 3: (Using Byte.valueOf() method)The valueOf() method of Byte class converts data from its internal form into human-readable form." }, { "code": null, "e": 1598, "s": 1590, "text": "Syntax:" }, { "code": null, "e": 1618, "s": 1598, "text": "Byte.valueOf(str);\n" }, { "code": null, "e": 1669, "s": 1618, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 1710, "s": 1669, "text": "Example 1: To show successful conversion" }, { "code": "// Java Program to convert string to byte class GFG { // Function to convert String to Byte public static byte convertStringToByte(String str) { // Convert string to byte // using valueOf() method return Byte.valueOf(str); } // Driver code public static void main(String[] args) { // The string value String stringValue = \"1\"; // The expected byte value byte byteValue; // Convert string to byte byteValue = convertStringToByte(stringValue); // Print the expected byte value System.out.println( stringValue + \" after converting into byte = \" + byteValue); }}", "e": 2418, "s": 1710, "text": null }, { "code": null, "e": 2452, "s": 2418, "text": "1 after converting into byte = 1\n" }, { "code": null, "e": 2462, "s": 2452, "text": "Java-Byte" }, { "code": null, "e": 2478, "s": 2462, "text": "Java-Data Types" }, { "code": null, "e": 2499, "s": 2478, "text": "Java-String-Programs" }, { "code": null, "e": 2512, "s": 2499, "text": "Java-Strings" }, { "code": null, "e": 2517, "s": 2512, "text": "Java" }, { "code": null, "e": 2531, "s": 2517, "text": "Java Programs" }, { "code": null, "e": 2544, "s": 2531, "text": "Java-Strings" }, { "code": null, "e": 2549, "s": 2544, "text": "Java" } ]
How to remove the first character of string in PHP?
To remove the first character of a string in PHP, the code is as follows− Live Demo <?php $str = "Test"; echo "Before removing the first character = ".$str; $res = substr($str, 1); echo "\nAfter removing the first character = ".$res; ?> This will produce the following output − Before removing the first character = Test After removing the first character = est Let us now see another example Live Demo <?php $str = "Demo"; echo "Before removing the first character = ".$str; $res = ltrim($str, 'D'); echo "\nAfter removing the first character = ".$res; ?> This will produce the following output− Before removing the first character = Demo After removing the first character = emo
[ { "code": null, "e": 1261, "s": 1187, "text": "To remove the first character of a string in PHP, the code is as follows−" }, { "code": null, "e": 1272, "s": 1261, "text": " Live Demo" }, { "code": null, "e": 1437, "s": 1272, "text": "<?php\n $str = \"Test\";\n echo \"Before removing the first character = \".$str;\n $res = substr($str, 1);\n echo \"\\nAfter removing the first character = \".$res;\n?>" }, { "code": null, "e": 1478, "s": 1437, "text": "This will produce the following output −" }, { "code": null, "e": 1562, "s": 1478, "text": "Before removing the first character = Test\nAfter removing the first character = est" }, { "code": null, "e": 1593, "s": 1562, "text": "Let us now see another example" }, { "code": null, "e": 1604, "s": 1593, "text": " Live Demo" }, { "code": null, "e": 1770, "s": 1604, "text": "<?php\n $str = \"Demo\";\n echo \"Before removing the first character = \".$str;\n $res = ltrim($str, 'D');\n echo \"\\nAfter removing the first character = \".$res;\n?>" }, { "code": null, "e": 1810, "s": 1770, "text": "This will produce the following output−" }, { "code": null, "e": 1895, "s": 1810, "text": "Before removing the first character = Demo \nAfter removing the first character = emo" } ]
CharsetDecoder charset() in Java with examples
23 Jul, 2020 CharsetDecoder.charset() is an in-built method in Java of CharsetDecoder class that returns the charset that created this decoder. Syntax: public final Charset charset() Parameter: The function does not accepts any parameter. Return value: The function returns the decoder’s charset. Program below demonstrate the above mentioned function: Program 1: // Java program below demonstrate// CharsetDecoder.charset function import java.nio.charset.Charset;import java.nio.charset.CharsetDecoder; public class Main { public static void main(String[] argv) throws Exception { Charset charset = Charset.forName("ISO-8859-1"); // initialising CharsetDecoder cd CharsetDecoder cd = charset.newDecoder(); // print charset of decoder cd System.out.println(cd.charset()); }} ISO-8859-1 Program 2: // Java program below demonstrate// CharsetDecoder.charset function import java.nio.charset.Charset;import java.nio.charset.CharsetDecoder; public class Main { public static void main(String[] argv) throws Exception { Charset charset = Charset.forName("ISO-8859-2"); // initialising CharsetDecoder cd CharsetDecoder cd = charset.newDecoder(); // print charset of decoder cd System.out.println(cd.charset()); }} ISO-8859-2 nidhi_biet Java-CharsetDecoder Java-Functions Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Interfaces in Java ArrayList in Java Stream In Java Collections in Java Singleton Class in Java Stack Class in Java Set in Java Introduction to Java Constructors in Java Initializing a List in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Jul, 2020" }, { "code": null, "e": 159, "s": 28, "text": "CharsetDecoder.charset() is an in-built method in Java of CharsetDecoder class that returns the charset that created this decoder." }, { "code": null, "e": 167, "s": 159, "text": "Syntax:" }, { "code": null, "e": 199, "s": 167, "text": "public final Charset charset()\n" }, { "code": null, "e": 255, "s": 199, "text": "Parameter: The function does not accepts any parameter." }, { "code": null, "e": 313, "s": 255, "text": "Return value: The function returns the decoder’s charset." }, { "code": null, "e": 369, "s": 313, "text": "Program below demonstrate the above mentioned function:" }, { "code": null, "e": 380, "s": 369, "text": "Program 1:" }, { "code": "// Java program below demonstrate// CharsetDecoder.charset function import java.nio.charset.Charset;import java.nio.charset.CharsetDecoder; public class Main { public static void main(String[] argv) throws Exception { Charset charset = Charset.forName(\"ISO-8859-1\"); // initialising CharsetDecoder cd CharsetDecoder cd = charset.newDecoder(); // print charset of decoder cd System.out.println(cd.charset()); }}", "e": 839, "s": 380, "text": null }, { "code": null, "e": 851, "s": 839, "text": "ISO-8859-1\n" }, { "code": null, "e": 862, "s": 851, "text": "Program 2:" }, { "code": "// Java program below demonstrate// CharsetDecoder.charset function import java.nio.charset.Charset;import java.nio.charset.CharsetDecoder; public class Main { public static void main(String[] argv) throws Exception { Charset charset = Charset.forName(\"ISO-8859-2\"); // initialising CharsetDecoder cd CharsetDecoder cd = charset.newDecoder(); // print charset of decoder cd System.out.println(cd.charset()); }}", "e": 1321, "s": 862, "text": null }, { "code": null, "e": 1333, "s": 1321, "text": "ISO-8859-2\n" }, { "code": null, "e": 1344, "s": 1333, "text": "nidhi_biet" }, { "code": null, "e": 1364, "s": 1344, "text": "Java-CharsetDecoder" }, { "code": null, "e": 1379, "s": 1364, "text": "Java-Functions" }, { "code": null, "e": 1384, "s": 1379, "text": "Java" }, { "code": null, "e": 1389, "s": 1384, "text": "Java" }, { "code": null, "e": 1487, "s": 1389, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1506, "s": 1487, "text": "Interfaces in Java" }, { "code": null, "e": 1524, "s": 1506, "text": "ArrayList in Java" }, { "code": null, "e": 1539, "s": 1524, "text": "Stream In Java" }, { "code": null, "e": 1559, "s": 1539, "text": "Collections in Java" }, { "code": null, "e": 1583, "s": 1559, "text": "Singleton Class in Java" }, { "code": null, "e": 1603, "s": 1583, "text": "Stack Class in Java" }, { "code": null, "e": 1615, "s": 1603, "text": "Set in Java" }, { "code": null, "e": 1636, "s": 1615, "text": "Introduction to Java" }, { "code": null, "e": 1657, "s": 1636, "text": "Constructors in Java" } ]
Speak the meaning of the word using Python
28 Jun, 2022 The following article shows how by the use of two modules named, pyttsx3 and PyDictionary, we can make our system say out the meaning of the word given as input. It is module which speak the meaning when we want to have the meaning of the particular word. PyDictionary: It is a Dictionary Module for Python 2-3 to get meanings, translations, synonyms and Antonyms of words. It uses WordNet for doing as its functionality suggests and has dependencies on modules named Requests, BeautifulSoup4 and goslate . pyttsx3: It is a text to speech library. This module is what gives our system voice so that they can communicate with us. Pyttsx3 uses sapi5 in windows and espeak in windows. Both modules can be installed by using pip in the following way: pip install PyDictionary pip install pyttsx3 As mentioned above, by the combination of two modules we will generate the functionality required and to do that the following steps were taken: A method is defined to make the system search for the meaning of the word provided as input Another method is defined to make the system say out loud the output generated corresponding to the input provided. The output returned in this may be a dictionary, so we have to extract each meaning of the word provided as it will be in a key-value format. Below is the Implementation. Python3 import pyttsx3from PyDictionary import PyDictionary class Speaking: def speak(self, audio): # Having the initial constructor of pyttsx3 # and having the sapi5 in it as a parameter engine = pyttsx3.init('sapi5') # Calling the getter and setter of pyttsx3 voices = engine.getProperty('voices') # Method for the speaking of the assistant engine.setProperty('voice', voices[0].id) engine.say(audio) engine.runAndWait() class GFG: def Dictionary(self): speak = Speaking() dic = PyDictionary() speak.speak("Which word do u want to find the meaning sir") # Taking the string input query = str(input()) word = dic.meaning(query) print(len(word)) for state in word: print(word[state]) speak.speak("the meaning is" + str(word[state])) if __name__ == '__main__': GFG() GFG.Dictionary(self=None) Output: anikakapoor simmytarika5 python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Create a directory in Python
[ { "code": null, "e": 52, "s": 24, "text": "\n28 Jun, 2022" }, { "code": null, "e": 308, "s": 52, "text": "The following article shows how by the use of two modules named, pyttsx3 and PyDictionary, we can make our system say out the meaning of the word given as input. It is module which speak the meaning when we want to have the meaning of the particular word." }, { "code": null, "e": 559, "s": 308, "text": "PyDictionary: It is a Dictionary Module for Python 2-3 to get meanings, translations, synonyms and Antonyms of words. It uses WordNet for doing as its functionality suggests and has dependencies on modules named Requests, BeautifulSoup4 and goslate ." }, { "code": null, "e": 734, "s": 559, "text": "pyttsx3: It is a text to speech library. This module is what gives our system voice so that they can communicate with us. Pyttsx3 uses sapi5 in windows and espeak in windows." }, { "code": null, "e": 799, "s": 734, "text": "Both modules can be installed by using pip in the following way:" }, { "code": null, "e": 846, "s": 799, "text": "pip install PyDictionary\npip install pyttsx3 " }, { "code": null, "e": 991, "s": 846, "text": "As mentioned above, by the combination of two modules we will generate the functionality required and to do that the following steps were taken:" }, { "code": null, "e": 1083, "s": 991, "text": "A method is defined to make the system search for the meaning of the word provided as input" }, { "code": null, "e": 1199, "s": 1083, "text": "Another method is defined to make the system say out loud the output generated corresponding to the input provided." }, { "code": null, "e": 1341, "s": 1199, "text": "The output returned in this may be a dictionary, so we have to extract each meaning of the word provided as it will be in a key-value format." }, { "code": null, "e": 1370, "s": 1341, "text": "Below is the Implementation." }, { "code": null, "e": 1378, "s": 1370, "text": "Python3" }, { "code": "import pyttsx3from PyDictionary import PyDictionary class Speaking: def speak(self, audio): # Having the initial constructor of pyttsx3 # and having the sapi5 in it as a parameter engine = pyttsx3.init('sapi5') # Calling the getter and setter of pyttsx3 voices = engine.getProperty('voices') # Method for the speaking of the assistant engine.setProperty('voice', voices[0].id) engine.say(audio) engine.runAndWait() class GFG: def Dictionary(self): speak = Speaking() dic = PyDictionary() speak.speak(\"Which word do u want to find the meaning sir\") # Taking the string input query = str(input()) word = dic.meaning(query) print(len(word)) for state in word: print(word[state]) speak.speak(\"the meaning is\" + str(word[state])) if __name__ == '__main__': GFG() GFG.Dictionary(self=None)", "e": 2363, "s": 1378, "text": null }, { "code": null, "e": 2371, "s": 2363, "text": "Output:" }, { "code": null, "e": 2383, "s": 2371, "text": "anikakapoor" }, { "code": null, "e": 2396, "s": 2383, "text": "simmytarika5" }, { "code": null, "e": 2411, "s": 2396, "text": "python-utility" }, { "code": null, "e": 2418, "s": 2411, "text": "Python" }, { "code": null, "e": 2516, "s": 2418, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2548, "s": 2516, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2575, "s": 2548, "text": "Python Classes and Objects" }, { "code": null, "e": 2596, "s": 2575, "text": "Python OOPs Concepts" }, { "code": null, "e": 2619, "s": 2596, "text": "Introduction To PYTHON" }, { "code": null, "e": 2675, "s": 2619, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2706, "s": 2675, "text": "Python | os.path.join() method" }, { "code": null, "e": 2748, "s": 2706, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2790, "s": 2748, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2829, "s": 2790, "text": "Python | Get unique values from a list" } ]