title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Conditional Inheritance in Python - GeeksforGeeks
25 Aug, 2020 It happens most of the time that given a condition we need to decide whether a particular class should inherit a class or not, for example given a person, if he/she is eligible for an admission in a university only then they should be a student otherwise they should not be a student. Let’s consider an example, where given a condition, we want a class (say C) to dynamically inherit from either class A or class B. We need to create two different classes C_A and C_B, which inherit from A and B respectively, However if the conditional inheritance is to either inherit or not based on a condition then we can use a different approach as discussed below Example 1: Conditional Inheritance between 2 classes: Create two classes C_A and C_B, and based on the condition return the respective class object. Python3 class A(object): def __init__(self, x): self.x = x def getX(self): return self.X class B(object): def __init__(self, x, y): self.x = x self.y = y def getSum(self): return self.X + self.y # inherits from A class C_A(A): def isA(self): return True def isB(self): return False # inherits from B class C_B(B): def isA(self): return False def isB(self): return True # return required Object of C based on cond def getC(cond): if cond: return C_A(1) else: return C_B(1,2) # Object of C_Aca = getC(True)print(ca.isA())print(ca.isB()) # Object of C_B cb = getC(False)print(cb.isA())print(cb.isB()) Output: True False False True Example 2: For Either inheriting or not from A: The approach is to use conditional statements while declaring the classes the given class C inherits. The below code executes and returns True Python3 class A(object): def __init__(self, x): self.x = x def getX(self): return self.X # Based on condition C inherits # from A or it inherits from # object i.e. does not inherit Acond = True # inherits from A or Bclass C(A if cond else object): def isA(self): return True # Object of C_Aca = C(1)print(ca.isA()) Output: True Example 3: The following code won’t run, as C does not inherit from A, thus has a default constructor that does not take any argument Python3 class A(object): def __init__(self, x): self.x = x def getX(self): return self.X # Based on condition C inherits from# A or it inherits from object i.e.# does not inherit Acond = False ## inherits from A or Bclass C(A if cond else object): def isA(self): return True # Object of C_Aca = C(1)print(ca.isA()) Output: TypeError Traceback (most recent call last)<ipython-input-16-f0efc5a814d9> in <module> 17 18 # Object of C_A—> 19 ca = C(1) 20 print(ca.isA()) 21 TypeError: object() takes no parameters Python-OOP python-oop-concepts Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() Reading and Writing to text files in Python *args and **kwargs in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 26384, "s": 26356, "text": "\n25 Aug, 2020" }, { "code": null, "e": 26669, "s": 26384, "text": "It happens most of the time that given a condition we need to decide whether a particular class should inherit a class or not, for example given a person, if he/she is eligible for an admission in a university only then they should be a student otherwise they should not be a student." }, { "code": null, "e": 27038, "s": 26669, "text": "Let’s consider an example, where given a condition, we want a class (say C) to dynamically inherit from either class A or class B. We need to create two different classes C_A and C_B, which inherit from A and B respectively, However if the conditional inheritance is to either inherit or not based on a condition then we can use a different approach as discussed below" }, { "code": null, "e": 27092, "s": 27038, "text": "Example 1: Conditional Inheritance between 2 classes:" }, { "code": null, "e": 27187, "s": 27092, "text": "Create two classes C_A and C_B, and based on the condition return the respective class object." }, { "code": null, "e": 27195, "s": 27187, "text": "Python3" }, { "code": "class A(object): def __init__(self, x): self.x = x def getX(self): return self.X class B(object): def __init__(self, x, y): self.x = x self.y = y def getSum(self): return self.X + self.y # inherits from A class C_A(A): def isA(self): return True def isB(self): return False # inherits from B class C_B(B): def isA(self): return False def isB(self): return True # return required Object of C based on cond def getC(cond): if cond: return C_A(1) else: return C_B(1,2) # Object of C_Aca = getC(True)print(ca.isA())print(ca.isB()) # Object of C_B cb = getC(False)print(cb.isA())print(cb.isB())", "e": 27930, "s": 27195, "text": null }, { "code": null, "e": 27938, "s": 27930, "text": "Output:" }, { "code": null, "e": 27960, "s": 27938, "text": "True\nFalse\nFalse\nTrue" }, { "code": null, "e": 28008, "s": 27960, "text": "Example 2: For Either inheriting or not from A:" }, { "code": null, "e": 28151, "s": 28008, "text": "The approach is to use conditional statements while declaring the classes the given class C inherits. The below code executes and returns True" }, { "code": null, "e": 28159, "s": 28151, "text": "Python3" }, { "code": "class A(object): def __init__(self, x): self.x = x def getX(self): return self.X # Based on condition C inherits # from A or it inherits from # object i.e. does not inherit Acond = True # inherits from A or Bclass C(A if cond else object): def isA(self): return True # Object of C_Aca = C(1)print(ca.isA())", "e": 28510, "s": 28159, "text": null }, { "code": null, "e": 28518, "s": 28510, "text": "Output:" }, { "code": null, "e": 28523, "s": 28518, "text": "True" }, { "code": null, "e": 28657, "s": 28523, "text": "Example 3: The following code won’t run, as C does not inherit from A, thus has a default constructor that does not take any argument" }, { "code": null, "e": 28665, "s": 28657, "text": "Python3" }, { "code": "class A(object): def __init__(self, x): self.x = x def getX(self): return self.X # Based on condition C inherits from# A or it inherits from object i.e.# does not inherit Acond = False ## inherits from A or Bclass C(A if cond else object): def isA(self): return True # Object of C_Aca = C(1)print(ca.isA())", "e": 29014, "s": 28665, "text": null }, { "code": null, "e": 29022, "s": 29014, "text": "Output:" }, { "code": null, "e": 29212, "s": 29022, "text": "TypeError Traceback (most recent call last)<ipython-input-16-f0efc5a814d9> in <module> 17 18 # Object of C_A—> 19 ca = C(1) 20 print(ca.isA()) 21" }, { "code": null, "e": 29252, "s": 29212, "text": "TypeError: object() takes no parameters" }, { "code": null, "e": 29263, "s": 29252, "text": "Python-OOP" }, { "code": null, "e": 29283, "s": 29263, "text": "python-oop-concepts" }, { "code": null, "e": 29290, "s": 29283, "text": "Python" }, { "code": null, "e": 29388, "s": 29290, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29406, "s": 29388, "text": "Python Dictionary" }, { "code": null, "e": 29441, "s": 29406, "text": "Read a file line by line in Python" }, { "code": null, "e": 29473, "s": 29441, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29495, "s": 29473, "text": "Enumerate() in Python" }, { "code": null, "e": 29537, "s": 29495, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 29567, "s": 29537, "text": "Iterate over a list in Python" }, { "code": null, "e": 29593, "s": 29567, "text": "Python String | replace()" }, { "code": null, "e": 29637, "s": 29593, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 29666, "s": 29637, "text": "*args and **kwargs in Python" } ]
C++ Signal Handling
Signals are the interrupts delivered to a process by the operating system which can terminate a program prematurely. You can generate interrupts by pressing Ctrl+C on a UNIX, LINUX, Mac OS X or Windows system. There are signals which can not be caught by the program but there is a following list of signals which you can catch in your program and can take appropriate actions based on the signal. These signals are defined in C++ header file <csignal>. SIGABRT Abnormal termination of the program, such as a call to abort. SIGFPE An erroneous arithmetic operation, such as a divide by zero or an operation resulting in overflow. SIGILL Detection of an illegal instruction. SIGINT Receipt of an interactive attention signal. SIGSEGV An invalid access to storage. SIGTERM A termination request sent to the program. C++ signal-handling library provides function signal to trap unexpected events. Following is the syntax of the signal() function − void (*signal (int sig, void (*func)(int)))(int); Keeping it simple, this function receives two arguments: first argument as an integer which represents signal number and second argument as a pointer to the signal-handling function. Let us write a simple C++ program where we will catch SIGINT signal using signal() function. Whatever signal you want to catch in your program, you must register that signal using signal function and associate it with a signal handler. Examine the following example − #include <iostream> #include <csignal> using namespace std; void signalHandler( int signum ) { cout << "Interrupt signal (" << signum << ") received.\n"; // cleanup and close up stuff here // terminate program exit(signum); } int main () { // register signal SIGINT and signal handler signal(SIGINT, signalHandler); while(1) { cout << "Going to sleep...." << endl; sleep(1); } return 0; } When the above code is compiled and executed, it produces the following result − Going to sleep.... Going to sleep.... Going to sleep.... Now, press Ctrl+c to interrupt the program and you will see that your program will catch the signal and would come out by printing something as follows − Going to sleep.... Going to sleep.... Going to sleep.... Interrupt signal (2) received. You can generate signals by function raise(), which takes an integer signal number as an argument and has the following syntax. int raise (signal sig); Here, sig is the signal number to send any of the signals: SIGINT, SIGABRT, SIGFPE, SIGILL, SIGSEGV, SIGTERM, SIGHUP. Following is the example where we raise a signal internally using raise() function as follows − #include <iostream> #include <csignal> using namespace std; void signalHandler( int signum ) { cout << "Interrupt signal (" << signum << ") received.\n"; // cleanup and close up stuff here // terminate program exit(signum); } int main () { int i = 0; // register signal SIGINT and signal handler signal(SIGINT, signalHandler); while(++i) { cout << "Going to sleep...." << endl; if( i == 3 ) { raise( SIGINT); } sleep(1); } return 0; } When the above code is compiled and executed, it produces the following result and would come out automatically − Going to sleep.... Going to sleep.... Going to sleep.... Interrupt signal (2) received. 154 Lectures 11.5 hours Arnab Chakraborty 14 Lectures 57 mins Kaushik Roy Chowdhury 30 Lectures 12.5 hours Frahaan Hussain 54 Lectures 3.5 hours Frahaan Hussain 77 Lectures 5.5 hours Frahaan Hussain 12 Lectures 3.5 hours Frahaan Hussain Print Add Notes Bookmark this page
[ { "code": null, "e": 2528, "s": 2318, "text": "Signals are the interrupts delivered to a process by the operating system which can terminate a program prematurely. You can generate interrupts by pressing Ctrl+C on a UNIX, LINUX, Mac OS X or Windows system." }, { "code": null, "e": 2772, "s": 2528, "text": "There are signals which can not be caught by the program but there is a following list of signals which you can catch in your program and can take appropriate actions based on the signal. These signals are defined in C++ header file <csignal>." }, { "code": null, "e": 2780, "s": 2772, "text": "SIGABRT" }, { "code": null, "e": 2842, "s": 2780, "text": "Abnormal termination of the program, such as a call to abort." }, { "code": null, "e": 2849, "s": 2842, "text": "SIGFPE" }, { "code": null, "e": 2948, "s": 2849, "text": "An erroneous arithmetic operation, such as a divide by zero or an operation resulting in overflow." }, { "code": null, "e": 2955, "s": 2948, "text": "SIGILL" }, { "code": null, "e": 2992, "s": 2955, "text": "Detection of an illegal instruction." }, { "code": null, "e": 2999, "s": 2992, "text": "SIGINT" }, { "code": null, "e": 3043, "s": 2999, "text": "Receipt of an interactive attention signal." }, { "code": null, "e": 3051, "s": 3043, "text": "SIGSEGV" }, { "code": null, "e": 3081, "s": 3051, "text": "An invalid access to storage." }, { "code": null, "e": 3089, "s": 3081, "text": "SIGTERM" }, { "code": null, "e": 3132, "s": 3089, "text": "A termination request sent to the program." }, { "code": null, "e": 3263, "s": 3132, "text": "C++ signal-handling library provides function signal to trap unexpected events. Following is the syntax of the signal() function −" }, { "code": null, "e": 3315, "s": 3263, "text": "void (*signal (int sig, void (*func)(int)))(int); \n" }, { "code": null, "e": 3498, "s": 3315, "text": "Keeping it simple, this function receives two arguments: first argument as an integer which represents signal number and second argument as a pointer to the signal-handling function." }, { "code": null, "e": 3766, "s": 3498, "text": "Let us write a simple C++ program where we will catch SIGINT signal using signal() function. Whatever signal you want to catch in your program, you must register that signal using signal function and associate it with a signal handler. Examine the following example −" }, { "code": null, "e": 4211, "s": 3766, "text": "#include <iostream>\n#include <csignal>\n\nusing namespace std;\n\nvoid signalHandler( int signum ) {\n cout << \"Interrupt signal (\" << signum << \") received.\\n\";\n\n // cleanup and close up stuff here \n // terminate program \n\n exit(signum); \n}\n\nint main () {\n // register signal SIGINT and signal handler \n signal(SIGINT, signalHandler); \n\n while(1) {\n cout << \"Going to sleep....\" << endl;\n sleep(1);\n }\n\n return 0;\n}" }, { "code": null, "e": 4292, "s": 4211, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 4350, "s": 4292, "text": "Going to sleep....\nGoing to sleep....\nGoing to sleep....\n" }, { "code": null, "e": 4504, "s": 4350, "text": "Now, press Ctrl+c to interrupt the program and you will see that your program will catch the signal and would come out by printing something as follows −" }, { "code": null, "e": 4593, "s": 4504, "text": "Going to sleep....\nGoing to sleep....\nGoing to sleep....\nInterrupt signal (2) received.\n" }, { "code": null, "e": 4721, "s": 4593, "text": "You can generate signals by function raise(), which takes an integer signal number as an argument and has the following syntax." }, { "code": null, "e": 4746, "s": 4721, "text": "int raise (signal sig);\n" }, { "code": null, "e": 4960, "s": 4746, "text": "Here, sig is the signal number to send any of the signals: SIGINT, SIGABRT, SIGFPE, SIGILL, SIGSEGV, SIGTERM, SIGHUP. Following is the example where we raise a signal internally using raise() function as follows −" }, { "code": null, "e": 5475, "s": 4960, "text": "#include <iostream>\n#include <csignal>\n\nusing namespace std;\n\nvoid signalHandler( int signum ) {\n cout << \"Interrupt signal (\" << signum << \") received.\\n\";\n\n // cleanup and close up stuff here \n // terminate program \n\n exit(signum); \n}\n\nint main () {\n int i = 0;\n // register signal SIGINT and signal handler \n signal(SIGINT, signalHandler); \n\n while(++i) {\n cout << \"Going to sleep....\" << endl;\n if( i == 3 ) {\n raise( SIGINT);\n }\n sleep(1);\n }\n\n return 0;\n}" }, { "code": null, "e": 5589, "s": 5475, "text": "When the above code is compiled and executed, it produces the following result and would come out automatically −" }, { "code": null, "e": 5678, "s": 5589, "text": "Going to sleep....\nGoing to sleep....\nGoing to sleep....\nInterrupt signal (2) received.\n" }, { "code": null, "e": 5715, "s": 5678, "text": "\n 154 Lectures \n 11.5 hours \n" }, { "code": null, "e": 5734, "s": 5715, "text": " Arnab Chakraborty" }, { "code": null, "e": 5766, "s": 5734, "text": "\n 14 Lectures \n 57 mins\n" }, { "code": null, "e": 5789, "s": 5766, "text": " Kaushik Roy Chowdhury" }, { "code": null, "e": 5825, "s": 5789, "text": "\n 30 Lectures \n 12.5 hours \n" }, { "code": null, "e": 5842, "s": 5825, "text": " Frahaan Hussain" }, { "code": null, "e": 5877, "s": 5842, "text": "\n 54 Lectures \n 3.5 hours \n" }, { "code": null, "e": 5894, "s": 5877, "text": " Frahaan Hussain" }, { "code": null, "e": 5929, "s": 5894, "text": "\n 77 Lectures \n 5.5 hours \n" }, { "code": null, "e": 5946, "s": 5929, "text": " Frahaan Hussain" }, { "code": null, "e": 5981, "s": 5946, "text": "\n 12 Lectures \n 3.5 hours \n" }, { "code": null, "e": 5998, "s": 5981, "text": " Frahaan Hussain" }, { "code": null, "e": 6005, "s": 5998, "text": " Print" }, { "code": null, "e": 6016, "s": 6005, "text": " Add Notes" } ]
How to change semi-structured text into a Pandas dataframe | by Alan Jones | Towards Data Science
These days much of the data you find on the internet are nicely formatted as JSON, Excel files or CSV. But some aren’t. I needed a simple dataset to illustrate my articles on data visualisation in Python and Julia and decided upon weather data (for London, UK) that was publicly available from the UK Met Office. The problem was that it was a text file that looked like a CSV file but it was actually really formatted for a human reader. So, I needed to do a bit of cleaning and tidying in order to be able to create a Pandas dataframe and plot graphs. This article is about the different techniques that I used to transform this semi-structured text file into a Pandas dataframe with which I could perform data analysis and plot graphs. I could, no doubt, have converted the file with a text editor — that would have been very tedious. But I decided it would be more fun to do it programmatically with Python and Pandas. Also, and perhaps more importantly, writing a program to download and format the data meant that I could automatically keep it up to date with no extra effort. There were a number of problems. First, there was the structure of the file. The data were tabulated but preceded by a free format description, so this was the first thing that had to go. Secondly, the column names were in two rows rather than the one that is conventional in a spreadsheet file. Then, although it looked a bit like a CSV file, there were no delimiters: the data were separated by a variable number of blank spaces. Lastly, the number of data columns changed part way through the file. The data ranges from 1948 to the current time but the figures for 2020 were labelled ‘Provisional’ in an additional column. Then there was the form of the data. In the early years some data were missing and that missing data was represented by a string of dashes. Other columns had a ‘#’ attached to what was otherwise numeric data. Neither of these could be recognised as numerical data by Pandas. Each of these problems had to be addressed for Pandas to make sense of the data. The data is in the public domain and provided by the Met Office as a simple text file. You can see the format in the image at the top of this article (along with the resulting dataframe and a graph drawn from the data). Reading a csv file in Pandas is quite straightforward and, although this is not a conventional csv file, I was going to use that functionality as a starting point. The function read_csv from Pandas is generally the thing to use to read either a local file or a remote one. Unfortunately, this did not work with the Met Office file because the web site refuses the connection. I’m not 100% sure but I imagine it is because it doesn’t like the ‘User Agent’ in the HTTP header supplied by the function (the user agent is normally the name/description of the browser that is accessing the web page — I don’t know, offhand, what read_csv sets it to). I’m not aware of any mechanism that will allow me to change the User Agent for read_csv but there is a fairly simple way around this: use the requests library. (The requests library lets you set the HTTP headers including the User Agent.) Using requests you can download the file to a Python file object and then use read_csv to import it to a dataframe. Here’s the code. First import the libraries that we will use: import pandas as pdimport matplotlib.pyplot as pltimport requestsimport io (If you have any missing you’ll have to conda/pip install them.) And here is the code to download the data: url = 'https://www.metoffice.gov.uk/pub/data/weather/uk/climate/stationdata/heathrowdata.txt'file = io.StringIO(requests.get(url).text) Just a minute, didn’t I say that I was going to set the User Agent? Well, as it happens, the default setting that requests uses appears to be acceptable to the Met Office web site, so without any further investigation, I just used the simple function call you see above. The requests call gets the file and returns the text. That is then converted to a file object by StringIO. Now we are nearly ready to read the file. I needed to take a look at the raw file first and this showed me that the first 5 lines were unstructured text. I would need to skip those lines to read the file as csv. The next two lines were the column names. I decided to skip those, too, and provide my own names. Those names are ‘Year’, ‘Month’, ‘Tmax’, ‘Tmin’, ‘AF’, ‘Rain’, ‘Sun’. The first two are obvious, Tmax and Tmin are the maximum and minimum temperatures in a month, AF is the number of days when there was air frost in a month, Rain is the number of millimeters of rain and Sun is the number of hours of sunshine. I recorded these things in variables like this: col_names = ('Year','Month','Tmax','Tmin','AF','Rain','Sun')comment_lines = 5header = 2 These will be used in the read_csv call. read_csv needs some other parameters set for this particular job. It needs to know the delimiter used in the file, the default is a comma (what else?) but here the delimiter is a space character, in fact more than one space character. So, I need to tell pandas this (delimiter=` ́). And because there are several spaces between the fields, Pandas needs to know to ignore these (skipinitialspace=True). I need to tell it that it should skip the first few rows (skiprows=comment_lines+header), not regard any row in the file as a header (header=None) and the names of the columns (names=col_names). Finally, I know that when it gets to the year 2020 the number of columns change. This would normally throw an exception and no dataframe would be returned. But setting error_bad_lines=False suppresses the error and ignores the bad lines. Here is the resulting code that creates the dataframe weather. weather = pd.read_csv(file, skiprows=comment_lines + header, header=None, names=col_names, delimiter=' ', skipinitialspace=True, error_bad_lines=False) That produces a dataframe that contains all the data up the first bad line (the one with the extra column). The individual data items need fixing but the next job is to append the rest of the file. This time I’ll read the file again, using similar parameters but I’ll find the length of the dataframe that I’ve just read and skip all of those lines. The remaining part of the file contains 8 columns, so I need to add a new column name as well. Otherwise the call to read_csv is similar to before. file.seek(0)col_names = ('Year','Month','Tmax','Tmin','AF','Rain','Sun', 'Status')rows_to_skip = comment_lines+header+len(weather)weather2 = pd.read_csv(file, skiprows=rows_to_skip, header=None, names=col_names, delimiter=' ', skipinitialspace=True, error_bad_lines=False) Also, notice that I had to set the pointer back to the beginning of the file using seek(0) otherwise there would be nothing to read as we already had reached the end of the file. Here’s the result: Similar to the other dataframe but with an extra column. The next trick is to merge the two dataframes and to do this properly I have to make them the same shape. So, I have a choice, delete the Status column in the second dataframe or add one to the first dataframe. For the purposes of this exercise, I’ve decided to not lose the status information and add a column to the first. The extra column is called Status and for the 2020 data its value is ‘Provisional’. So, I’ll create a Status column in the first dataframe and set all the values to ‘Final’. weather['Status']='Final' And now I’ll append the second dataframe to the first and add the parameter ignore_index=True in order not to duplicate the indices but rather create a new index for the combined dataframe. weather = weather.append(weather2, ignore_index=True) Now we have to deal with the data in each column. Let’s take a look at the data types. weather.dtypes As you can see, Pandas has done its best to interpret the data types: Tmax, Tmin and Rain are correctly identified as floats and Status is an object (basically a string). But AF and Sun have been interpreted as strings, too, although in reality they ought to be numbers. The reason for this is that some of the values in the Sun and AF columns are the string ‘ — -’ (meaning no data) or the number has a # symbol attached to it. It’s only the Sun column that has the # symbol attached to the number of hours of sunshine, so the first thing is to just get rid of that character in that column. A string-replace does the job; the code below removes the character by replacing it with an empty string. weather['Sun']=weather['Sun'].str.replace('#','') Now the numbers in the Sun column are correctly formatted but Pandas still regards the Sun and AF columns data as strings so we can’t read the column as numbers and cannot therefore draw charts using this data. Changing the representation of the data is straightforward; we use the function to_numeric to convert the string values to numbers. Using this function the string would convert the string “123.4” to a floating point number 123.4. But some of the values in the columns that we want to convert are the string ‘ — -’, which cannot be reasonably interpreted as a number. The trick is to set the parameter errors to coerce. This will force any strings that cannot be interpreted as numbers to the value NaN (not a number) which is the Python equivalent of a null numeric value. And this is exactly what we want because the string ‘ — -’ in this dataframe means ‘no data’. Here is the code to correct the values in the two columns. weather['AF']=pd.to_numeric(weather['AF'], errors='coerce')weather['Sun']=pd.to_numeric(weather['Sun'], errors='coerce') The dataframe now looks like this: You can see the NaN values and if we look at the data types again we see this: Now all of the numeric data are floating point values — exactly what is needed. To illustrate that this is what we want here is a plot of the rainfall for the year 2000. weather[weather.Year==2000].plot(x='Month', y='Rain') Job done! And if you are wondering where the graph at the top of this article comes from, here is the code that plots the monthly maximum temperatures for 1950, 1960, 1970, 1980,1990, 2000 and 2010. ax = weather[weather.Year==1950].plot(x='Month', y='Tmax', label='1950')ax = weather[weather.Year==1960].plot(x='Month', y='Tmax', label='1960',ax=ax)ax = weather[weather.Year==1970].plot(x='Month', y='Tmax', label='1970',ax=ax)ax = weather[weather.Year==1980].plot(x='Month', y='Tmax', label='1980',ax=ax)ax = weather[weather.Year==1990].plot(x='Month', y='Tmax', label='1990',ax=ax)ax = weather[weather.Year==2000].plot(x='Month', y='Tmax', label='2000',ax=ax)weather[weather.Year==2019].plot(x='Month', y='Tmax', label = '2010', ax=ax, figsize=(15,10)); It is unlikely that you will find that you need to do exactly the same manipulations on a text file that I have demonstrated here but I hope that you may have found my experience useful and that you may be able to adapt the techniques that I have used here for your own purposes. Thanks for reading and if you would like to keep up to date with the articles that I publish, please consider subscribing to my free newsletter here. Update: I have written a new more generic version of the above program here.
[ { "code": null, "e": 292, "s": 172, "text": "These days much of the data you find on the internet are nicely formatted as JSON, Excel files or CSV. But some aren’t." }, { "code": null, "e": 485, "s": 292, "text": "I needed a simple dataset to illustrate my articles on data visualisation in Python and Julia and decided upon weather data (for London, UK) that was publicly available from the UK Met Office." }, { "code": null, "e": 725, "s": 485, "text": "The problem was that it was a text file that looked like a CSV file but it was actually really formatted for a human reader. So, I needed to do a bit of cleaning and tidying in order to be able to create a Pandas dataframe and plot graphs." }, { "code": null, "e": 910, "s": 725, "text": "This article is about the different techniques that I used to transform this semi-structured text file into a Pandas dataframe with which I could perform data analysis and plot graphs." }, { "code": null, "e": 1254, "s": 910, "text": "I could, no doubt, have converted the file with a text editor — that would have been very tedious. But I decided it would be more fun to do it programmatically with Python and Pandas. Also, and perhaps more importantly, writing a program to download and format the data meant that I could automatically keep it up to date with no extra effort." }, { "code": null, "e": 1686, "s": 1254, "text": "There were a number of problems. First, there was the structure of the file. The data were tabulated but preceded by a free format description, so this was the first thing that had to go. Secondly, the column names were in two rows rather than the one that is conventional in a spreadsheet file. Then, although it looked a bit like a CSV file, there were no delimiters: the data were separated by a variable number of blank spaces." }, { "code": null, "e": 1880, "s": 1686, "text": "Lastly, the number of data columns changed part way through the file. The data ranges from 1948 to the current time but the figures for 2020 were labelled ‘Provisional’ in an additional column." }, { "code": null, "e": 2155, "s": 1880, "text": "Then there was the form of the data. In the early years some data were missing and that missing data was represented by a string of dashes. Other columns had a ‘#’ attached to what was otherwise numeric data. Neither of these could be recognised as numerical data by Pandas." }, { "code": null, "e": 2236, "s": 2155, "text": "Each of these problems had to be addressed for Pandas to make sense of the data." }, { "code": null, "e": 2456, "s": 2236, "text": "The data is in the public domain and provided by the Met Office as a simple text file. You can see the format in the image at the top of this article (along with the resulting dataframe and a graph drawn from the data)." }, { "code": null, "e": 2620, "s": 2456, "text": "Reading a csv file in Pandas is quite straightforward and, although this is not a conventional csv file, I was going to use that functionality as a starting point." }, { "code": null, "e": 3102, "s": 2620, "text": "The function read_csv from Pandas is generally the thing to use to read either a local file or a remote one. Unfortunately, this did not work with the Met Office file because the web site refuses the connection. I’m not 100% sure but I imagine it is because it doesn’t like the ‘User Agent’ in the HTTP header supplied by the function (the user agent is normally the name/description of the browser that is accessing the web page — I don’t know, offhand, what read_csv sets it to)." }, { "code": null, "e": 3341, "s": 3102, "text": "I’m not aware of any mechanism that will allow me to change the User Agent for read_csv but there is a fairly simple way around this: use the requests library. (The requests library lets you set the HTTP headers including the User Agent.)" }, { "code": null, "e": 3474, "s": 3341, "text": "Using requests you can download the file to a Python file object and then use read_csv to import it to a dataframe. Here’s the code." }, { "code": null, "e": 3519, "s": 3474, "text": "First import the libraries that we will use:" }, { "code": null, "e": 3594, "s": 3519, "text": "import pandas as pdimport matplotlib.pyplot as pltimport requestsimport io" }, { "code": null, "e": 3659, "s": 3594, "text": "(If you have any missing you’ll have to conda/pip install them.)" }, { "code": null, "e": 3702, "s": 3659, "text": "And here is the code to download the data:" }, { "code": null, "e": 3838, "s": 3702, "text": "url = 'https://www.metoffice.gov.uk/pub/data/weather/uk/climate/stationdata/heathrowdata.txt'file = io.StringIO(requests.get(url).text)" }, { "code": null, "e": 4216, "s": 3838, "text": "Just a minute, didn’t I say that I was going to set the User Agent? Well, as it happens, the default setting that requests uses appears to be acceptable to the Met Office web site, so without any further investigation, I just used the simple function call you see above. The requests call gets the file and returns the text. That is then converted to a file object by StringIO." }, { "code": null, "e": 4428, "s": 4216, "text": "Now we are nearly ready to read the file. I needed to take a look at the raw file first and this showed me that the first 5 lines were unstructured text. I would need to skip those lines to read the file as csv." }, { "code": null, "e": 4838, "s": 4428, "text": "The next two lines were the column names. I decided to skip those, too, and provide my own names. Those names are ‘Year’, ‘Month’, ‘Tmax’, ‘Tmin’, ‘AF’, ‘Rain’, ‘Sun’. The first two are obvious, Tmax and Tmin are the maximum and minimum temperatures in a month, AF is the number of days when there was air frost in a month, Rain is the number of millimeters of rain and Sun is the number of hours of sunshine." }, { "code": null, "e": 4886, "s": 4838, "text": "I recorded these things in variables like this:" }, { "code": null, "e": 4974, "s": 4886, "text": "col_names = ('Year','Month','Tmax','Tmin','AF','Rain','Sun')comment_lines = 5header = 2" }, { "code": null, "e": 5015, "s": 4974, "text": "These will be used in the read_csv call." }, { "code": null, "e": 5418, "s": 5015, "text": "read_csv needs some other parameters set for this particular job. It needs to know the delimiter used in the file, the default is a comma (what else?) but here the delimiter is a space character, in fact more than one space character. So, I need to tell pandas this (delimiter=` ́). And because there are several spaces between the fields, Pandas needs to know to ignore these (skipinitialspace=True)." }, { "code": null, "e": 5613, "s": 5418, "text": "I need to tell it that it should skip the first few rows (skiprows=comment_lines+header), not regard any row in the file as a header (header=None) and the names of the columns (names=col_names)." }, { "code": null, "e": 5851, "s": 5613, "text": "Finally, I know that when it gets to the year 2020 the number of columns change. This would normally throw an exception and no dataframe would be returned. But setting error_bad_lines=False suppresses the error and ignores the bad lines." }, { "code": null, "e": 5914, "s": 5851, "text": "Here is the resulting code that creates the dataframe weather." }, { "code": null, "e": 6078, "s": 5914, "text": "weather = pd.read_csv(file, skiprows=comment_lines + header, header=None, names=col_names, delimiter=' ', skipinitialspace=True, error_bad_lines=False)" }, { "code": null, "e": 6186, "s": 6078, "text": "That produces a dataframe that contains all the data up the first bad line (the one with the extra column)." }, { "code": null, "e": 6576, "s": 6186, "text": "The individual data items need fixing but the next job is to append the rest of the file. This time I’ll read the file again, using similar parameters but I’ll find the length of the dataframe that I’ve just read and skip all of those lines. The remaining part of the file contains 8 columns, so I need to add a new column name as well. Otherwise the call to read_csv is similar to before." }, { "code": null, "e": 6861, "s": 6576, "text": "file.seek(0)col_names = ('Year','Month','Tmax','Tmin','AF','Rain','Sun', 'Status')rows_to_skip = comment_lines+header+len(weather)weather2 = pd.read_csv(file, skiprows=rows_to_skip, header=None, names=col_names, delimiter=' ', skipinitialspace=True, error_bad_lines=False)" }, { "code": null, "e": 7040, "s": 6861, "text": "Also, notice that I had to set the pointer back to the beginning of the file using seek(0) otherwise there would be nothing to read as we already had reached the end of the file." }, { "code": null, "e": 7059, "s": 7040, "text": "Here’s the result:" }, { "code": null, "e": 7116, "s": 7059, "text": "Similar to the other dataframe but with an extra column." }, { "code": null, "e": 7615, "s": 7116, "text": "The next trick is to merge the two dataframes and to do this properly I have to make them the same shape. So, I have a choice, delete the Status column in the second dataframe or add one to the first dataframe. For the purposes of this exercise, I’ve decided to not lose the status information and add a column to the first. The extra column is called Status and for the 2020 data its value is ‘Provisional’. So, I’ll create a Status column in the first dataframe and set all the values to ‘Final’." }, { "code": null, "e": 7641, "s": 7615, "text": "weather['Status']='Final'" }, { "code": null, "e": 7831, "s": 7641, "text": "And now I’ll append the second dataframe to the first and add the parameter ignore_index=True in order not to duplicate the indices but rather create a new index for the combined dataframe." }, { "code": null, "e": 7885, "s": 7831, "text": "weather = weather.append(weather2, ignore_index=True)" }, { "code": null, "e": 7972, "s": 7885, "text": "Now we have to deal with the data in each column. Let’s take a look at the data types." }, { "code": null, "e": 7987, "s": 7972, "text": "weather.dtypes" }, { "code": null, "e": 8416, "s": 7987, "text": "As you can see, Pandas has done its best to interpret the data types: Tmax, Tmin and Rain are correctly identified as floats and Status is an object (basically a string). But AF and Sun have been interpreted as strings, too, although in reality they ought to be numbers. The reason for this is that some of the values in the Sun and AF columns are the string ‘ — -’ (meaning no data) or the number has a # symbol attached to it." }, { "code": null, "e": 8686, "s": 8416, "text": "It’s only the Sun column that has the # symbol attached to the number of hours of sunshine, so the first thing is to just get rid of that character in that column. A string-replace does the job; the code below removes the character by replacing it with an empty string." }, { "code": null, "e": 8736, "s": 8686, "text": "weather['Sun']=weather['Sun'].str.replace('#','')" }, { "code": null, "e": 8947, "s": 8736, "text": "Now the numbers in the Sun column are correctly formatted but Pandas still regards the Sun and AF columns data as strings so we can’t read the column as numbers and cannot therefore draw charts using this data." }, { "code": null, "e": 9314, "s": 8947, "text": "Changing the representation of the data is straightforward; we use the function to_numeric to convert the string values to numbers. Using this function the string would convert the string “123.4” to a floating point number 123.4. But some of the values in the columns that we want to convert are the string ‘ — -’, which cannot be reasonably interpreted as a number." }, { "code": null, "e": 9614, "s": 9314, "text": "The trick is to set the parameter errors to coerce. This will force any strings that cannot be interpreted as numbers to the value NaN (not a number) which is the Python equivalent of a null numeric value. And this is exactly what we want because the string ‘ — -’ in this dataframe means ‘no data’." }, { "code": null, "e": 9673, "s": 9614, "text": "Here is the code to correct the values in the two columns." }, { "code": null, "e": 9794, "s": 9673, "text": "weather['AF']=pd.to_numeric(weather['AF'], errors='coerce')weather['Sun']=pd.to_numeric(weather['Sun'], errors='coerce')" }, { "code": null, "e": 9829, "s": 9794, "text": "The dataframe now looks like this:" }, { "code": null, "e": 9908, "s": 9829, "text": "You can see the NaN values and if we look at the data types again we see this:" }, { "code": null, "e": 9988, "s": 9908, "text": "Now all of the numeric data are floating point values — exactly what is needed." }, { "code": null, "e": 10078, "s": 9988, "text": "To illustrate that this is what we want here is a plot of the rainfall for the year 2000." }, { "code": null, "e": 10132, "s": 10078, "text": "weather[weather.Year==2000].plot(x='Month', y='Rain')" }, { "code": null, "e": 10142, "s": 10132, "text": "Job done!" }, { "code": null, "e": 10331, "s": 10142, "text": "And if you are wondering where the graph at the top of this article comes from, here is the code that plots the monthly maximum temperatures for 1950, 1960, 1970, 1980,1990, 2000 and 2010." }, { "code": null, "e": 10909, "s": 10331, "text": "ax = weather[weather.Year==1950].plot(x='Month', y='Tmax', label='1950')ax = weather[weather.Year==1960].plot(x='Month', y='Tmax', label='1960',ax=ax)ax = weather[weather.Year==1970].plot(x='Month', y='Tmax', label='1970',ax=ax)ax = weather[weather.Year==1980].plot(x='Month', y='Tmax', label='1980',ax=ax)ax = weather[weather.Year==1990].plot(x='Month', y='Tmax', label='1990',ax=ax)ax = weather[weather.Year==2000].plot(x='Month', y='Tmax', label='2000',ax=ax)weather[weather.Year==2019].plot(x='Month', y='Tmax', label = '2010', ax=ax, figsize=(15,10));" }, { "code": null, "e": 11189, "s": 10909, "text": "It is unlikely that you will find that you need to do exactly the same manipulations on a text file that I have demonstrated here but I hope that you may have found my experience useful and that you may be able to adapt the techniques that I have used here for your own purposes." }, { "code": null, "e": 11339, "s": 11189, "text": "Thanks for reading and if you would like to keep up to date with the articles that I publish, please consider subscribing to my free newsletter here." } ]
HTML <fieldset> disabled Attribute - GeeksforGeeks
04 Jan, 2019 The disabled attribute for <fieldset> element in HTML is used to specify that the group of related form elements is disabled. A disabled fieldset is un-clickable and unusable. It is a boolean attribute. Syntax: <fieldset disabled>fieldset content...</fieldset> Example: <!DOCTYPE html> <html> <head> <title>HTML fieldset disabled Attribute</title> </head> <body style = "text-align:center"> <h1 style = "color: green;">GeeksforGeeks</h1> <h2>HTML fieldset disabled Attribute</h2> <p>This field set is disabled.</p> <!--A disabled fieldset--> <fieldset disabled> Name: <input type="text"><br> </fieldset> </body> </html> Output: Supported Browsers: The browser supported by <fieldset> disabled attribute are listed below: Apple Safari 8.0 Google Chrome Firefox Opera Internet Explorer Not supported Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. HTML-Attributes HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to Insert Form Data into Database using PHP ? REST API (Introduction) Form validation using HTML and JavaScript Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? Express.js express.Router() Function
[ { "code": null, "e": 23739, "s": 23711, "text": "\n04 Jan, 2019" }, { "code": null, "e": 23942, "s": 23739, "text": "The disabled attribute for <fieldset> element in HTML is used to specify that the group of related form elements is disabled. A disabled fieldset is un-clickable and unusable. It is a boolean attribute." }, { "code": null, "e": 23950, "s": 23942, "text": "Syntax:" }, { "code": null, "e": 24001, "s": 23950, "text": "<fieldset disabled>fieldset content...</fieldset>\n" }, { "code": null, "e": 24010, "s": 24001, "text": "Example:" }, { "code": "<!DOCTYPE html> <html> <head> <title>HTML fieldset disabled Attribute</title> </head> <body style = \"text-align:center\"> <h1 style = \"color: green;\">GeeksforGeeks</h1> <h2>HTML fieldset disabled Attribute</h2> <p>This field set is disabled.</p> <!--A disabled fieldset--> <fieldset disabled> Name: <input type=\"text\"><br> </fieldset> </body> </html> ", "e": 24452, "s": 24010, "text": null }, { "code": null, "e": 24460, "s": 24452, "text": "Output:" }, { "code": null, "e": 24553, "s": 24460, "text": "Supported Browsers: The browser supported by <fieldset> disabled attribute are listed below:" }, { "code": null, "e": 24570, "s": 24553, "text": "Apple Safari 8.0" }, { "code": null, "e": 24584, "s": 24570, "text": "Google Chrome" }, { "code": null, "e": 24592, "s": 24584, "text": "Firefox" }, { "code": null, "e": 24598, "s": 24592, "text": "Opera" }, { "code": null, "e": 24630, "s": 24598, "text": "Internet Explorer Not supported" }, { "code": null, "e": 24767, "s": 24630, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 24783, "s": 24767, "text": "HTML-Attributes" }, { "code": null, "e": 24788, "s": 24783, "text": "HTML" }, { "code": null, "e": 24805, "s": 24788, "text": "Web Technologies" }, { "code": null, "e": 24810, "s": 24805, "text": "HTML" }, { "code": null, "e": 24908, "s": 24810, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 24917, "s": 24908, "text": "Comments" }, { "code": null, "e": 24930, "s": 24917, "text": "Old Comments" }, { "code": null, "e": 24992, "s": 24930, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 25042, "s": 24992, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 25092, "s": 25042, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 25116, "s": 25092, "text": "REST API (Introduction)" }, { "code": null, "e": 25158, "s": 25116, "text": "Form validation using HTML and JavaScript" }, { "code": null, "e": 25191, "s": 25158, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 25234, "s": 25191, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 25296, "s": 25234, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 25346, "s": 25296, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
How to count the number of checkboxes in a page in Selenium with python?
We can count the total number of checkboxes in a page in Selenium with the help of find_elements method. While working on any checkboxes, we will always find an attribute type in the html code and its value should be checkbox. This characteristic is only applicable to checkboxes on that particular page and to no other types of UI elements like edit box, link and so on. To retrieve all the elements with attribute type = 'checkbox', we will use find_elements_by_xpath() method. This method returns a list of web elements with the type of xpath specified in the method argument. In case there are no matching elements, an empty list will be returned. After the list of checkboxes are fetched, in order to count its total numbers, we need to get the size of that list. The size of the list can be obtained from the len() method of the list data structure. Finally this length is printed on the console. driver.find_elements_by_xpath("//input[@type='checkbox']") Code Implementation for counting checkbox. from selenium import webdriver #browser exposes an executable file #Through Selenium test we will invoke the executable file which will then #invoke actual browser driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe") # to maximize the browser window driver.maximize_window() #get method to launch the URL driver.get("https://www.tutorialspoint.com/selenium/selenium_automation_practice.htm") #to refresh the browser driver.refresh() # identifying the checkboxes with type attribute in a list chk =driver.find_elements_by_xpath("//input[@type='checkbox']") # len method is used to get the size of that list print(len(chk)) #to close the browser driver.close()
[ { "code": null, "e": 1289, "s": 1062, "text": "We can count the total number of checkboxes in a page in Selenium with the help of find_elements method. While working on any checkboxes, we will always find an attribute type in the html code and its value should be checkbox." }, { "code": null, "e": 1434, "s": 1289, "text": "This characteristic is only applicable to checkboxes on that particular page and to no other types of UI elements like edit box, link and so on." }, { "code": null, "e": 1714, "s": 1434, "text": "To retrieve all the elements with attribute type = 'checkbox', we will use find_elements_by_xpath() method. This method returns a list of web elements with the type of xpath specified in the method argument. In case there are no matching elements, an empty list will be returned." }, { "code": null, "e": 1918, "s": 1714, "text": "After the list of checkboxes are fetched, in order to count its total numbers, we need to get the size of that list. The size of the list can be obtained from the len() method of the list data structure." }, { "code": null, "e": 1965, "s": 1918, "text": "Finally this length is printed on the console." }, { "code": null, "e": 2024, "s": 1965, "text": "driver.find_elements_by_xpath(\"//input[@type='checkbox']\")" }, { "code": null, "e": 2067, "s": 2024, "text": "Code Implementation for counting checkbox." }, { "code": null, "e": 2739, "s": 2067, "text": "from selenium import webdriver\n#browser exposes an executable file\n#Through Selenium test we will invoke the executable file which will then #invoke actual browser\ndriver = webdriver.Chrome(executable_path=\"C:\\\\chromedriver.exe\")\n# to maximize the browser window\ndriver.maximize_window()\n#get method to launch the URL\ndriver.get(\"https://www.tutorialspoint.com/selenium/selenium_automation_practice.htm\")\n#to refresh the browser\ndriver.refresh()\n# identifying the checkboxes with type attribute in a list\nchk =driver.find_elements_by_xpath(\"//input[@type='checkbox']\")\n# len method is used to get the size of that list\nprint(len(chk))\n#to close the browser\ndriver.close()" } ]
How to add a variable description in R?
To add a variable description in R, we can use comment function and if we want to have a look at the description then structure call of the data frame will be used. For example, if we have a data frame say df that contains a column x then we can describe x by using the command comment(df$x)<-c("The name of this variable is x"). Now to have a look at it, we can use str(df). Consider the below data frame − Live Demo x1<-rnorm(20,21,3.24) x2<-rnorm(20,5,2.1) df1<-data.frame(x1,x2) df1 x1 x2 1 23.12252 5.085650 2 19.81415 5.180194 3 14.41423 2.756885 4 21.34914 5.714200 5 18.34662 3.814034 6 21.37762 9.538720 7 21.48240 4.838389 8 22.58701 2.185943 9 15.68257 5.084348 10 20.86272 5.732107 11 19.84529 3.430304 12 26.23832 3.684373 13 25.35179 5.001748 14 19.83831 3.393473 15 23.57819 5.057545 16 15.69374 7.442210 17 15.69028 6.722865 18 18.94718 8.046787 19 25.26722 2.776823 20 23.32905 3.561213 str(df1) 'data.frame': 20 obs. of 2 variables: $ x1: num 23.1 19.8 14.4 21.3 18.3 ... $ x2: num 5.09 5.18 2.76 5.71 3.81 ... Adding description of variables in df1 − comment(df1$x1)<-c("This variable follows normal distribution") comment(df1$x2)<-c("This variable follows normal distribution") str(df1) 'data.frame': 20 obs. of 2 variables − $ x1: num 23.1 19.8 14.4 21.3 18.3 ... ..- attr(*, "comment")= chr "This variable follows normal distribution" $ x2: num 5.09 5.18 2.76 5.71 3.81 ... ..- attr(*, "comment")= chr "This variable follows normal distribution" Live Demo y1<-sample(0:1,20,replace=TRUE) y2<-sample(LETTERS[1:5],20,replace=TRUE) df2<-data.frame(y1,y2) df2 y1 y2 1 0 B 2 1 E 3 0 B 4 1 A 5 1 D 6 0 A 7 0 E 8 1 D 9 0 D 10 0 D 11 0 E 12 0 C 13 1 A 14 1 D 15 0 B 16 0 E 17 1 C 18 0 C 19 1 D 20 1 C str(df2) 'data.frame': 20 obs. of 2 variables: $ y1: int 0 1 0 1 1 0 0 1 0 0 ... $ y2: chr "B" "E" "B" "A" ... Adding description of variables in df2 − comment(df2$y1)<-c("This is a binary variable") comment(df2$y2)<-c("This is a categorical variable") str(df2) 'data.frame': 20 obs. of 2 variables − $ y1: int 0 1 0 1 1 0 0 1 0 0 ... ..- attr(*, "comment")= chr "This is a binary variable" $ y2: chr "B" "E" "B" "A" ... ..- attr(*, "comment")= chr "This is a categorical variable"
[ { "code": null, "e": 1438, "s": 1062, "text": "To add a variable description in R, we can use comment function and if we want to have a look at the description then structure call of the data frame will be used. For example, if we have a data frame say df that contains a column x then we can describe x by using the command comment(df$x)<-c(\"The name of this variable is x\"). Now to have a look at it, we can use str(df)." }, { "code": null, "e": 1470, "s": 1438, "text": "Consider the below data frame −" }, { "code": null, "e": 1481, "s": 1470, "text": " Live Demo" }, { "code": null, "e": 1550, "s": 1481, "text": "x1<-rnorm(20,21,3.24)\nx2<-rnorm(20,5,2.1)\ndf1<-data.frame(x1,x2)\ndf1" }, { "code": null, "e": 2008, "s": 1550, "text": " x1 x2\n1 23.12252 5.085650\n2 19.81415 5.180194\n3 14.41423 2.756885\n4 21.34914 5.714200\n5 18.34662 3.814034\n6 21.37762 9.538720\n7 21.48240 4.838389\n8 22.58701 2.185943\n9 15.68257 5.084348\n10 20.86272 5.732107\n11 19.84529 3.430304\n12 26.23832 3.684373\n13 25.35179 5.001748\n14 19.83831 3.393473\n15 23.57819 5.057545\n16 15.69374 7.442210\n17 15.69028 6.722865\n18 18.94718 8.046787\n19 25.26722 2.776823\n20 23.32905 3.561213" }, { "code": null, "e": 2017, "s": 2008, "text": "str(df1)" }, { "code": null, "e": 2133, "s": 2017, "text": "'data.frame': 20 obs. of 2 variables:\n$ x1: num 23.1 19.8 14.4 21.3 18.3 ...\n$ x2: num 5.09 5.18 2.76 5.71 3.81 ..." }, { "code": null, "e": 2174, "s": 2133, "text": "Adding description of variables in df1 −" }, { "code": null, "e": 2311, "s": 2174, "text": "comment(df1$x1)<-c(\"This variable follows normal distribution\")\ncomment(df1$x2)<-c(\"This variable follows normal distribution\")\nstr(df1)" }, { "code": null, "e": 2350, "s": 2311, "text": "'data.frame': 20 obs. of 2 variables −" }, { "code": null, "e": 2572, "s": 2350, "text": "$ x1: num 23.1 19.8 14.4 21.3 18.3 ...\n..- attr(*, \"comment\")= chr \"This variable follows normal distribution\"\n$ x2: num 5.09 5.18 2.76 5.71 3.81 ...\n..- attr(*, \"comment\")= chr \"This variable follows normal distribution\"" }, { "code": null, "e": 2583, "s": 2572, "text": " Live Demo" }, { "code": null, "e": 2683, "s": 2583, "text": "y1<-sample(0:1,20,replace=TRUE)\ny2<-sample(LETTERS[1:5],20,replace=TRUE)\ndf2<-data.frame(y1,y2)\ndf2" }, { "code": null, "e": 2852, "s": 2683, "text": " y1 y2\n1 0 B\n2 1 E\n3 0 B\n4 1 A\n5 1 D\n6 0 A\n7 0 E\n8 1 D\n9 0 D\n10 0 D\n11 0 E\n12 0 C\n13 1 A\n14 1 D\n15 0 B\n16 0 E\n17 1 C\n18 0 C\n19 1 D\n20 1 C" }, { "code": null, "e": 2861, "s": 2852, "text": "str(df2)" }, { "code": null, "e": 2963, "s": 2861, "text": "'data.frame': 20 obs. of 2 variables:\n$ y1: int 0 1 0 1 1 0 0 1 0 0 ...\n$ y2: chr \"B\" \"E\" \"B\" \"A\" ..." }, { "code": null, "e": 3004, "s": 2963, "text": "Adding description of variables in df2 −" }, { "code": null, "e": 3114, "s": 3004, "text": "comment(df2$y1)<-c(\"This is a binary variable\")\ncomment(df2$y2)<-c(\"This is a categorical variable\")\nstr(df2)" }, { "code": null, "e": 3153, "s": 3114, "text": "'data.frame': 20 obs. of 2 variables −" }, { "code": null, "e": 3334, "s": 3153, "text": "$ y1: int 0 1 0 1 1 0 0 1 0 0 ...\n..- attr(*, \"comment\")= chr \"This is a binary variable\"\n$ y2: chr \"B\" \"E\" \"B\" \"A\" ...\n..- attr(*, \"comment\")= chr \"This is a categorical variable\"" } ]
WPF - Triggers
A trigger basically enables you to change property values or take actions based on the value of a property. So, it allows you to dynamically change the appearance and/or behavior of your control without having to create a new one. Triggers are used to change the value of any given property, when certain conditions are satisfied. Triggers are usually defined in a style or in the root of a document which are applied to that specific control. There are three types of triggers − Property Triggers Data Triggers Event Triggers In property triggers, when a change occurs in one property, it will bring either an immediate or an animated change in another property. For example, you can use a property trigger to change the appearance of a button when the mouse hovers over the button. The following example code shows how to change the foreground color of a button when mouse hovers over the button. <Window x:Class = "WPFPropertyTriggers.MainWindow" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" Title = "MainWindow" Height = "350" Width = "604"> <Window.Resources> <Style x:Key = "TriggerStyle" TargetType = "Button"> <Setter Property = "Foreground" Value = "Blue" /> <Style.Triggers> <Trigger Property = "IsMouseOver" Value = "True"> <Setter Property = "Foreground" Value = "Green" /> </Trigger> </Style.Triggers> </Style> </Window.Resources> <Grid> <Button Width = "100" Height = "70" Style = "{StaticResource TriggerStyle}" Content = "Trigger"/> </Grid> </Window> When you compile and execute the above code, it will produce the following window − When the mouse hovers over the button, its foreground color will change to green. A data trigger performs some actions when the bound data satisfies some conditions. Let’s have a look at the following XAML code in which a checkbox and a text block are created with some properties. When the checkbox is checked, it will change its foreground color to red. <Window x:Class = "WPFDataTrigger.MainWindow" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" Title = "Data Trigger" Height = "350" Width = "604"> <StackPanel HorizontalAlignment = "Center"> <CheckBox x:Name = "redColorCheckBox" Content = "Set red as foreground color" Margin = "20"/> <TextBlock Name = "txtblock" VerticalAlignment = "Center" Text = "Event Trigger" FontSize = "24" Margin = "20"> <TextBlock.Style> <Style> <Style.Triggers> <DataTrigger Binding = "{Binding ElementName = redColorCheckBox, Path = IsChecked}" Value = "true"> <Setter Property = "TextBlock.Foreground" Value = "Red"/> <Setter Property = "TextBlock.Cursor" Value = "Hand" /> </DataTrigger> </Style.Triggers> </Style> </TextBlock.Style> </TextBlock> </StackPanel> </Window> When the above code is compiled and executed, it will produce the following output − When you tick the checkbox, the text block will change its foreground color to red. An event trigger performs some actions when a specific event is fired. It is usually used to accomplish some animation on control such DoubleAnumatio, ColorAnimation, etc. In the following example, we will create a simple button. When the click event is fired, it will expand the button width and height. <Window x:Class = "WPFEventTrigger.MainWindow" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" Title = "MainWindow" Height = "350" Width = "604"> <Grid> <Button Content = "Click Me" Width = "60" Height = "30"> <Button.Triggers> <EventTrigger RoutedEvent = "Button.Click"> <EventTrigger.Actions> <BeginStoryboard> <Storyboard> <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty = "Width" Duration = "0:0:4"> <LinearDoubleKeyFrame Value = "60" KeyTime = "0:0:0"/> <LinearDoubleKeyFrame Value = "120" KeyTime = "0:0:1"/> <LinearDoubleKeyFrame Value = "200" KeyTime = "0:0:2"/> <LinearDoubleKeyFrame Value = "300" KeyTime = "0:0:3"/> </DoubleAnimationUsingKeyFrames> <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty = "Height" Duration = "0:0:4"> <LinearDoubleKeyFrame Value = "30" KeyTime = "0:0:0"/> <LinearDoubleKeyFrame Value = "40" KeyTime = "0:0:1"/> <LinearDoubleKeyFrame Value = "80" KeyTime = "0:0:2"/> <LinearDoubleKeyFrame Value = "150" KeyTime = "0:0:3"/> </DoubleAnimationUsingKeyFrames> </Storyboard> </BeginStoryboard> </EventTrigger.Actions> </EventTrigger> </Button.Triggers> </Button> </Grid> </Window> When you compile and execute the above code, it will produce the following window − Upon clicking the button, you will observe that it will start expanding in both dimensions. We recommend that you compile and execute the above examples and apply the triggers to other properties as well. 31 Lectures 2.5 hours Anadi Sharma 30 Lectures 2.5 hours Taurius Litvinavicius Print Add Notes Bookmark this page
[ { "code": null, "e": 2251, "s": 2020, "text": "A trigger basically enables you to change property values or take actions based on the value of a property. So, it allows you to dynamically change the appearance and/or behavior of your control without having to create a new one." }, { "code": null, "e": 2500, "s": 2251, "text": "Triggers are used to change the value of any given property, when certain conditions are satisfied. Triggers are usually defined in a style or in the root of a document which are applied to that specific control. There are three types of triggers −" }, { "code": null, "e": 2518, "s": 2500, "text": "Property Triggers" }, { "code": null, "e": 2532, "s": 2518, "text": "Data Triggers" }, { "code": null, "e": 2547, "s": 2532, "text": "Event Triggers" }, { "code": null, "e": 2804, "s": 2547, "text": "In property triggers, when a change occurs in one property, it will bring either an immediate or an animated change in another property. For example, you can use a property trigger to change the appearance of a button when the mouse hovers over the button." }, { "code": null, "e": 2919, "s": 2804, "text": "The following example code shows how to change the foreground color of a button when mouse hovers over the button." }, { "code": null, "e": 3705, "s": 2919, "text": "<Window x:Class = \"WPFPropertyTriggers.MainWindow\" \n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" \n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\" \n Title = \"MainWindow\" Height = \"350\" Width = \"604\"> \n\t\n <Window.Resources> \n <Style x:Key = \"TriggerStyle\" TargetType = \"Button\"> \n <Setter Property = \"Foreground\" Value = \"Blue\" /> \n <Style.Triggers> \n <Trigger Property = \"IsMouseOver\" Value = \"True\"> \n <Setter Property = \"Foreground\" Value = \"Green\" /> \n </Trigger> \n </Style.Triggers> \n </Style> \n </Window.Resources> \n\t\n <Grid> \n <Button Width = \"100\" Height = \"70\"\n Style = \"{StaticResource TriggerStyle}\" Content = \"Trigger\"/> \n </Grid> \n\t\n</Window> " }, { "code": null, "e": 3789, "s": 3705, "text": "When you compile and execute the above code, it will produce the following window −" }, { "code": null, "e": 3871, "s": 3789, "text": "When the mouse hovers over the button, its foreground color will change to green." }, { "code": null, "e": 4145, "s": 3871, "text": "A data trigger performs some actions when the bound data satisfies some conditions. Let’s have a look at the following XAML code in which a checkbox and a text block are created with some properties. When the checkbox is checked, it will change its foreground color to red." }, { "code": null, "e": 5228, "s": 4145, "text": "<Window x:Class = \"WPFDataTrigger.MainWindow\" \n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" \n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\" \n Title = \"Data Trigger\" Height = \"350\" Width = \"604\">\n\t\n <StackPanel HorizontalAlignment = \"Center\"> \n <CheckBox x:Name = \"redColorCheckBox\" \n Content = \"Set red as foreground color\" Margin = \"20\"/> \n\t\t\t\n <TextBlock Name = \"txtblock\" VerticalAlignment = \"Center\" \n Text = \"Event Trigger\" FontSize = \"24\" Margin = \"20\"> \n <TextBlock.Style> \n <Style> \n <Style.Triggers> \n <DataTrigger Binding = \"{Binding ElementName = redColorCheckBox, Path = IsChecked}\" \n Value = \"true\"> \n <Setter Property = \"TextBlock.Foreground\" Value = \"Red\"/> \n <Setter Property = \"TextBlock.Cursor\" Value = \"Hand\" /> \n </DataTrigger> \n </Style.Triggers> \n </Style> \n </TextBlock.Style> \n </TextBlock> \n\t\t\n </StackPanel> \n\t\n</Window>" }, { "code": null, "e": 5313, "s": 5228, "text": "When the above code is compiled and executed, it will produce the following output −" }, { "code": null, "e": 5397, "s": 5313, "text": "When you tick the checkbox, the text block will change its foreground color to red." }, { "code": null, "e": 5702, "s": 5397, "text": "An event trigger performs some actions when a specific event is fired. It is usually used to accomplish some animation on control such DoubleAnumatio, ColorAnimation, etc. In the following example, we will create a simple button. When the click event is fired, it will expand the button width and height." }, { "code": null, "e": 7518, "s": 5702, "text": "<Window x:Class = \"WPFEventTrigger.MainWindow\"\n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" \n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\" \n Title = \"MainWindow\" Height = \"350\" Width = \"604\"> \n\t\n <Grid> \n <Button Content = \"Click Me\" Width = \"60\" Height = \"30\">\n\t\t\n <Button.Triggers> \n <EventTrigger RoutedEvent = \"Button.Click\"> \n <EventTrigger.Actions> \n <BeginStoryboard> \n <Storyboard> \n\t\t\t\t\t\t\t\n <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty = \n \"Width\" Duration = \"0:0:4\"> \n <LinearDoubleKeyFrame Value = \"60\" KeyTime = \"0:0:0\"/> \n <LinearDoubleKeyFrame Value = \"120\" KeyTime = \"0:0:1\"/> \n <LinearDoubleKeyFrame Value = \"200\" KeyTime = \"0:0:2\"/> \n <LinearDoubleKeyFrame Value = \"300\" KeyTime = \"0:0:3\"/> \n </DoubleAnimationUsingKeyFrames>\n\t\t\t\t\t\t\t\t\n <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty = \"Height\" \n Duration = \"0:0:4\"> \n <LinearDoubleKeyFrame Value = \"30\" KeyTime = \"0:0:0\"/> \n <LinearDoubleKeyFrame Value = \"40\" KeyTime = \"0:0:1\"/> \n <LinearDoubleKeyFrame Value = \"80\" KeyTime = \"0:0:2\"/> \n <LinearDoubleKeyFrame Value = \"150\" KeyTime = \"0:0:3\"/> \n </DoubleAnimationUsingKeyFrames>\n\t\t\t\t\t\t\t\t\n </Storyboard> \n </BeginStoryboard> \n </EventTrigger.Actions> \n </EventTrigger> \n </Button.Triggers> \n\t\t\t\n </Button> \n </Grid> \n\t\n</Window>" }, { "code": null, "e": 7602, "s": 7518, "text": "When you compile and execute the above code, it will produce the following window −" }, { "code": null, "e": 7694, "s": 7602, "text": "Upon clicking the button, you will observe that it will start expanding in both dimensions." }, { "code": null, "e": 7807, "s": 7694, "text": "We recommend that you compile and execute the above examples and apply the triggers to other properties as well." }, { "code": null, "e": 7842, "s": 7807, "text": "\n 31 Lectures \n 2.5 hours \n" }, { "code": null, "e": 7856, "s": 7842, "text": " Anadi Sharma" }, { "code": null, "e": 7891, "s": 7856, "text": "\n 30 Lectures \n 2.5 hours \n" }, { "code": null, "e": 7914, "s": 7891, "text": " Taurius Litvinavicius" }, { "code": null, "e": 7921, "s": 7914, "text": " Print" }, { "code": null, "e": 7932, "s": 7921, "text": " Add Notes" } ]
numpy.hstack
Variants of numpy.stack function to stack so as to make a single array horizontally. import numpy as np a = np.array([[1,2],[3,4]]) print 'First array:' print a print '\n' b = np.array([[5,6],[7,8]]) print 'Second array:' print b print '\n' print 'Horizontal stacking:' c = np.hstack((a,b)) print c print '\n' It would produce the following output − First array: [[1 2] [3 4]] Second array: [[5 6] [7 8]] Horizontal stacking: [[1 2 5 6] [3 4 7 8]] 63 Lectures 6 hours Abhilash Nelson 19 Lectures 8 hours DATAhill Solutions Srinivas Reddy 12 Lectures 3 hours DATAhill Solutions Srinivas Reddy 10 Lectures 2.5 hours Akbar Khan 20 Lectures 2 hours Pruthviraja L 63 Lectures 6 hours Anmol Print Add Notes Bookmark this page
[ { "code": null, "e": 2328, "s": 2243, "text": "Variants of numpy.stack function to stack so as to make a single array horizontally." }, { "code": null, "e": 2570, "s": 2328, "text": "import numpy as np \na = np.array([[1,2],[3,4]]) \n\nprint 'First array:' \nprint a \nprint '\\n' \nb = np.array([[5,6],[7,8]]) \n\nprint 'Second array:' \nprint b \nprint '\\n' \n\nprint 'Horizontal stacking:' \nc = np.hstack((a,b)) \nprint c \nprint '\\n'" }, { "code": null, "e": 2610, "s": 2570, "text": "It would produce the following output −" }, { "code": null, "e": 2714, "s": 2610, "text": "First array:\n[[1 2]\n [3 4]]\n\nSecond array:\n[[5 6]\n [7 8]]\n\nHorizontal stacking:\n[[1 2 5 6]\n [3 4 7 8]]\n" }, { "code": null, "e": 2747, "s": 2714, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 2764, "s": 2747, "text": " Abhilash Nelson" }, { "code": null, "e": 2797, "s": 2764, "text": "\n 19 Lectures \n 8 hours \n" }, { "code": null, "e": 2832, "s": 2797, "text": " DATAhill Solutions Srinivas Reddy" }, { "code": null, "e": 2865, "s": 2832, "text": "\n 12 Lectures \n 3 hours \n" }, { "code": null, "e": 2900, "s": 2865, "text": " DATAhill Solutions Srinivas Reddy" }, { "code": null, "e": 2935, "s": 2900, "text": "\n 10 Lectures \n 2.5 hours \n" }, { "code": null, "e": 2947, "s": 2935, "text": " Akbar Khan" }, { "code": null, "e": 2980, "s": 2947, "text": "\n 20 Lectures \n 2 hours \n" }, { "code": null, "e": 2995, "s": 2980, "text": " Pruthviraja L" }, { "code": null, "e": 3028, "s": 2995, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 3035, "s": 3028, "text": " Anmol" }, { "code": null, "e": 3042, "s": 3035, "text": " Print" }, { "code": null, "e": 3053, "s": 3042, "text": " Add Notes" } ]
Write a C program that displays contents of a given file like 'more' utility in Linux - GeeksforGeeks
08 May, 2017 Write a C program that displays contents of given line page by page. Given number of lines to show as ‘n’ at a time and a file name, the program should first show n lines, then wait for user to hit a key before showing next n lines and so on. We strongly recommend to minimize the browser and try this yourself first. We can open the given file and print contents of files. While printing, we can keep track of number of newline characters. If the number of newline characters become n, we wait for the user to press a key before showing next n lines. Following is the requires C program. // C program to show contents of a file with breaks#include <stdio.h> // This function displays a given file with breaks of// given line numbers.void show(char *fname, int n){ // Open given file FILE *fp = fopen(fname, "r"); int curr_lines = 0, ch; // If not able to open file if (fp == NULL) { printf("File doesn't exist\n"); return; } // Read contents of file while ((ch = fgetc(fp)) != EOF) { // print current character putchar(ch); // If current character is a new line character, // then increment count of current lines if (ch == '\n') { curr_lines++; // If count of current lines reaches limit, then // wait for user to enter a key if (curr_lines == n) { curr_lines = 0; getchar(); } } } fclose(fp);} // Driver program to test above functionint main(){ char fname[] = "A.CPP"; int n = 25; show(fname, n); return 0;} This article is contributed by Ajay Jain. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. C-File Handling cpp-file-handling C Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments TCP Server-Client implementation in C Exception Handling in C++ Multithreading in C Arrow operator -> in C/C++ with Examples 'this' pointer in C++ How to split a string in C/C++, Python and Java? Smart Pointers in C++ and How to Use Them UDP Server-Client implementation in C How to dynamically allocate a 2D array in C? Unordered Sets in C++ Standard Template Library
[ { "code": null, "e": 23817, "s": 23789, "text": "\n08 May, 2017" }, { "code": null, "e": 24060, "s": 23817, "text": "Write a C program that displays contents of given line page by page. Given number of lines to show as ‘n’ at a time and a file name, the program should first show n lines, then wait for user to hit a key before showing next n lines and so on." }, { "code": null, "e": 24135, "s": 24060, "text": "We strongly recommend to minimize the browser and try this yourself first." }, { "code": null, "e": 24369, "s": 24135, "text": "We can open the given file and print contents of files. While printing, we can keep track of number of newline characters. If the number of newline characters become n, we wait for the user to press a key before showing next n lines." }, { "code": null, "e": 24406, "s": 24369, "text": "Following is the requires C program." }, { "code": "// C program to show contents of a file with breaks#include <stdio.h> // This function displays a given file with breaks of// given line numbers.void show(char *fname, int n){ // Open given file FILE *fp = fopen(fname, \"r\"); int curr_lines = 0, ch; // If not able to open file if (fp == NULL) { printf(\"File doesn't exist\\n\"); return; } // Read contents of file while ((ch = fgetc(fp)) != EOF) { // print current character putchar(ch); // If current character is a new line character, // then increment count of current lines if (ch == '\\n') { curr_lines++; // If count of current lines reaches limit, then // wait for user to enter a key if (curr_lines == n) { curr_lines = 0; getchar(); } } } fclose(fp);} // Driver program to test above functionint main(){ char fname[] = \"A.CPP\"; int n = 25; show(fname, n); return 0;}", "e": 25448, "s": 24406, "text": null }, { "code": null, "e": 25615, "s": 25448, "text": "This article is contributed by Ajay Jain. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 25631, "s": 25615, "text": "C-File Handling" }, { "code": null, "e": 25649, "s": 25631, "text": "cpp-file-handling" }, { "code": null, "e": 25660, "s": 25649, "text": "C Language" }, { "code": null, "e": 25758, "s": 25660, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25767, "s": 25758, "text": "Comments" }, { "code": null, "e": 25780, "s": 25767, "text": "Old Comments" }, { "code": null, "e": 25818, "s": 25780, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 25844, "s": 25818, "text": "Exception Handling in C++" }, { "code": null, "e": 25864, "s": 25844, "text": "Multithreading in C" }, { "code": null, "e": 25905, "s": 25864, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 25927, "s": 25905, "text": "'this' pointer in C++" }, { "code": null, "e": 25976, "s": 25927, "text": "How to split a string in C/C++, Python and Java?" }, { "code": null, "e": 26018, "s": 25976, "text": "Smart Pointers in C++ and How to Use Them" }, { "code": null, "e": 26056, "s": 26018, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 26101, "s": 26056, "text": "How to dynamically allocate a 2D array in C?" } ]
Building a Streamlit app to visualise Covid-19 data | by Sam Ho | Towards Data Science
Our World in Data (OWID) is an open-source, online research publication. They have a wide range of public data sets covering topics such as disease, climate change, social injustice and poverty. The goal of our work is to make the knowledge on the big problems accessible and understandable....Our World in Data is about Research and data to make progress against the world’s largest problems. So you won’t be surprised to find that OWID has an extensive collection of Covid-19 data sets hosted on their GitHub repository. Taking some of their Covid-19 data, I set out to build a Streamlit app that would allow users to visualise and analyse Covid-19 data. Of particular importance was the ability for users to be able to interact with the data allowing for bespoke analysis and answer questions such as: Is there a relationship between population density and total cases? Which countries are leading vaccination rollouts and who is lagging? What features are most strongly correlated with deaths? I wanted it to look easy on the eye so Plotly was my go-to charting library for this task. I specifically wanted to animate some of the visualisations and Plotly is one of a few libraries that can do this in a code efficient manner. The final Streamlit is deployed and you can find it at the link below but I wanted to walk through some of the key steps I took to build it and talk about some of the thinking that took place throughout its development. https://share.streamlit.io/kitsamho/covid-19-data/covid_streamlit_app.py There are many datasets on the OWID GitHub repository however they have aggregated many of the key data points into one combined structure. This makes life considerably easier as transformations are in less intensive. Let’s have a look at the CSV. import pandas as pddf = pd.read_csv('owid-covid-data.csv')print(df.shape)(101752, 60)print('Total unique continents:',len(df.continent.unique()))print('Total unique countries:',len(df.location.unique()))print('Date span:',df.date.min(),df.date.max())Total unique continents: 7Total unique countries: 231Date span: 2020-01-01 2021-07-11 Let’s inspect the head of the data frame.. We have 60 columns and just over 101,000 rows (correct as of July 2021) with each row representing a day in the year We have 231 countries spanning 6 continents Almost all variables are continuous whereas country and continent are categorical. There are a lot of null values (more on this in a bit). Given the nature of our analysis some of these variables are dependent and some are best described as independent, especially if we are looking through the lens of risk factors and their impact on the Covid-19 pandemic. Note — I’ve selected 24 variables that I feel are most useful to demo the dashboard, these are outlined below. If you want you can evolve this app and include more. dependent_var = [‘total_deaths’,’total_deaths_per_million’,’total_cases_per_million’,’icu_patients_per_million’,‘people_vaccinated_per_hundred’,’total_vaccinations’,'hosp_patients_per_million] independent_var = [‘gdp_per_capita’,’population’,’stringency_index’,’population’, ‘population_density’, ‘median_age’, ‘aged_65_older’,‘aged_70_older’, ‘gdp_per_capita’, ‘extreme_poverty’,‘cardiovasc_death_rate’, ‘diabetes_prevalence’, ‘female_smokers’,’male_smokers’, ‘handwashing_facilities’, ‘hospital_beds_per_thousand’,’life_expectancy’,'continent', 'location'] Most of these metrics are self explanatory. For a detailed breakdown of what they represent and how they are measured there is an extensive data dictionary here. Often when we are preparing data we encounter missing values. This can be because of errors in collection pipelines or it could be because there wasn’t any data to begin with. When we are dealing with data that fits a gaussian distribution a valid strategy is to replace nulls with the mean and in other instances the median possibly. For data that is cumulative over time a more appropriate technique would be to use interpolation where we estimate and impute values based on its surrounding values. Pandas has a method pd.interpolate() and the default replacement is linear. Inspection of the raw OWID data set revealed that missing values were commonplace. Here are some functions that solve this problem. Below is the main function that produces clean/formatted data that can be used in the app. Let’s have a look at the final DataFrame and see what it looks like for the UK. Our Covid-19 dependent variables (e.g. total cases, deaths, hospital admissions, vaccinations) are grouped by week however you can see there is variance in the data as time progresses Each independent feature (e.g GDP per capita, population density, smoking prevalence) is also grouped by week although the data doesn’t change as these things don’t move anywhere near as fast as Covid-19. Great, now we have the data in the right format for our needs. Next we need to start thinking about how to present this data in a meaningful and useful way on our app! This post assumes you have a working knowledge of how Streamlit works. If you don’t then please check this post out below for a primer towardsdatascience.com There were two useful ways of looking at this data: Cross sectionally — exploring the relationships between multiple independent variables and dependent variables at a given point in time Time Series — exploring relationships between multiple independent variables and dependent variables and how this changes over time I wanted to keep the app light in use and didn’t want to have multiple plots showing different data points so I took the decision to only use one scatter plot visualisation but allow for a high level of customisation from the user. This would encourage interactivity and hopefully a degree of discovery. I built two pages in the app, one for cross section visualisation and one for time series visualisation. Note — navigating Streamlit apps using pages is not a native feature on the Streamlit platform but there is a work around to this outlined by Praneel Nihar here: medium.com I love scatter plots. If a scatter plot is static and in two dimensions, we have the ability to show up to five variables in just the one figure. X axis Y axis Scatter point Scatter Size Scatter Colour And if we animate these plots we can add a sixth dimension of time to the visualisation too Finally if we can give the user the opportunity to change each one of these variables, then the scope of analysis can be widened even further. Widgets in Streamlit allow us to provide this feature. In addition to X, Y and scatter data points I included some other visualisation options: The option to mask by continent, i.e. only show countries from specific continents For X and Y plot a vertical / horizontal line denoting a measure of central tendency for a feature. This allows you to see which markers are above or below the average for any plotted metric The code block below outlines the steps needed to create the cross sectional scatter plot as above. And this code block below outlines the steps needed to create the cross sectional scatter plot that is animated. Hopefully this short walk through has given you some examples of how we can visualise data in a compelling way. By choosing the right tools to interact with the data and through using appropriate visualisations, exploratory analysis can be more efficient, more fun and more informative than using bar charts alone. By all means please take my Streamlit code and build on it — there is a lot of data here and even though I have written some comprehensive code to visualise the data I’m sure there’s plenty of other avenues that can be explored and built upon. Until next time! Sam To launch this app locally you should clone my forked OWID repo and in the command line run: $ streamlit run covid_streamlit_app.py Streamlit AppForked OWID repository with my appStreamlit app requirementsOriginal Our World In Data repo Streamlit App Forked OWID repository with my app Streamlit app requirements Original Our World In Data repo
[ { "code": null, "e": 367, "s": 172, "text": "Our World in Data (OWID) is an open-source, online research publication. They have a wide range of public data sets covering topics such as disease, climate change, social injustice and poverty." }, { "code": null, "e": 566, "s": 367, "text": "The goal of our work is to make the knowledge on the big problems accessible and understandable....Our World in Data is about Research and data to make progress against the world’s largest problems." }, { "code": null, "e": 695, "s": 566, "text": "So you won’t be surprised to find that OWID has an extensive collection of Covid-19 data sets hosted on their GitHub repository." }, { "code": null, "e": 977, "s": 695, "text": "Taking some of their Covid-19 data, I set out to build a Streamlit app that would allow users to visualise and analyse Covid-19 data. Of particular importance was the ability for users to be able to interact with the data allowing for bespoke analysis and answer questions such as:" }, { "code": null, "e": 1045, "s": 977, "text": "Is there a relationship between population density and total cases?" }, { "code": null, "e": 1114, "s": 1045, "text": "Which countries are leading vaccination rollouts and who is lagging?" }, { "code": null, "e": 1170, "s": 1114, "text": "What features are most strongly correlated with deaths?" }, { "code": null, "e": 1403, "s": 1170, "text": "I wanted it to look easy on the eye so Plotly was my go-to charting library for this task. I specifically wanted to animate some of the visualisations and Plotly is one of a few libraries that can do this in a code efficient manner." }, { "code": null, "e": 1623, "s": 1403, "text": "The final Streamlit is deployed and you can find it at the link below but I wanted to walk through some of the key steps I took to build it and talk about some of the thinking that took place throughout its development." }, { "code": null, "e": 1696, "s": 1623, "text": "https://share.streamlit.io/kitsamho/covid-19-data/covid_streamlit_app.py" }, { "code": null, "e": 1914, "s": 1696, "text": "There are many datasets on the OWID GitHub repository however they have aggregated many of the key data points into one combined structure. This makes life considerably easier as transformations are in less intensive." }, { "code": null, "e": 1944, "s": 1914, "text": "Let’s have a look at the CSV." }, { "code": null, "e": 2280, "s": 1944, "text": "import pandas as pddf = pd.read_csv('owid-covid-data.csv')print(df.shape)(101752, 60)print('Total unique continents:',len(df.continent.unique()))print('Total unique countries:',len(df.location.unique()))print('Date span:',df.date.min(),df.date.max())Total unique continents: 7Total unique countries: 231Date span: 2020-01-01 2021-07-11" }, { "code": null, "e": 2323, "s": 2280, "text": "Let’s inspect the head of the data frame.." }, { "code": null, "e": 2440, "s": 2323, "text": "We have 60 columns and just over 101,000 rows (correct as of July 2021) with each row representing a day in the year" }, { "code": null, "e": 2484, "s": 2440, "text": "We have 231 countries spanning 6 continents" }, { "code": null, "e": 2567, "s": 2484, "text": "Almost all variables are continuous whereas country and continent are categorical." }, { "code": null, "e": 2623, "s": 2567, "text": "There are a lot of null values (more on this in a bit)." }, { "code": null, "e": 2843, "s": 2623, "text": "Given the nature of our analysis some of these variables are dependent and some are best described as independent, especially if we are looking through the lens of risk factors and their impact on the Covid-19 pandemic." }, { "code": null, "e": 3008, "s": 2843, "text": "Note — I’ve selected 24 variables that I feel are most useful to demo the dashboard, these are outlined below. If you want you can evolve this app and include more." }, { "code": null, "e": 3201, "s": 3008, "text": "dependent_var = [‘total_deaths’,’total_deaths_per_million’,’total_cases_per_million’,’icu_patients_per_million’,‘people_vaccinated_per_hundred’,’total_vaccinations’,'hosp_patients_per_million]" }, { "code": null, "e": 3567, "s": 3201, "text": "independent_var = [‘gdp_per_capita’,’population’,’stringency_index’,’population’, ‘population_density’, ‘median_age’, ‘aged_65_older’,‘aged_70_older’, ‘gdp_per_capita’, ‘extreme_poverty’,‘cardiovasc_death_rate’, ‘diabetes_prevalence’, ‘female_smokers’,’male_smokers’, ‘handwashing_facilities’, ‘hospital_beds_per_thousand’,’life_expectancy’,'continent', 'location']" }, { "code": null, "e": 3729, "s": 3567, "text": "Most of these metrics are self explanatory. For a detailed breakdown of what they represent and how they are measured there is an extensive data dictionary here." }, { "code": null, "e": 4306, "s": 3729, "text": "Often when we are preparing data we encounter missing values. This can be because of errors in collection pipelines or it could be because there wasn’t any data to begin with. When we are dealing with data that fits a gaussian distribution a valid strategy is to replace nulls with the mean and in other instances the median possibly. For data that is cumulative over time a more appropriate technique would be to use interpolation where we estimate and impute values based on its surrounding values. Pandas has a method pd.interpolate() and the default replacement is linear." }, { "code": null, "e": 4438, "s": 4306, "text": "Inspection of the raw OWID data set revealed that missing values were commonplace. Here are some functions that solve this problem." }, { "code": null, "e": 4529, "s": 4438, "text": "Below is the main function that produces clean/formatted data that can be used in the app." }, { "code": null, "e": 4609, "s": 4529, "text": "Let’s have a look at the final DataFrame and see what it looks like for the UK." }, { "code": null, "e": 4793, "s": 4609, "text": "Our Covid-19 dependent variables (e.g. total cases, deaths, hospital admissions, vaccinations) are grouped by week however you can see there is variance in the data as time progresses" }, { "code": null, "e": 4998, "s": 4793, "text": "Each independent feature (e.g GDP per capita, population density, smoking prevalence) is also grouped by week although the data doesn’t change as these things don’t move anywhere near as fast as Covid-19." }, { "code": null, "e": 5166, "s": 4998, "text": "Great, now we have the data in the right format for our needs. Next we need to start thinking about how to present this data in a meaningful and useful way on our app!" }, { "code": null, "e": 5301, "s": 5166, "text": "This post assumes you have a working knowledge of how Streamlit works. If you don’t then please check this post out below for a primer" }, { "code": null, "e": 5324, "s": 5301, "text": "towardsdatascience.com" }, { "code": null, "e": 5376, "s": 5324, "text": "There were two useful ways of looking at this data:" }, { "code": null, "e": 5512, "s": 5376, "text": "Cross sectionally — exploring the relationships between multiple independent variables and dependent variables at a given point in time" }, { "code": null, "e": 5644, "s": 5512, "text": "Time Series — exploring relationships between multiple independent variables and dependent variables and how this changes over time" }, { "code": null, "e": 5948, "s": 5644, "text": "I wanted to keep the app light in use and didn’t want to have multiple plots showing different data points so I took the decision to only use one scatter plot visualisation but allow for a high level of customisation from the user. This would encourage interactivity and hopefully a degree of discovery." }, { "code": null, "e": 6053, "s": 5948, "text": "I built two pages in the app, one for cross section visualisation and one for time series visualisation." }, { "code": null, "e": 6215, "s": 6053, "text": "Note — navigating Streamlit apps using pages is not a native feature on the Streamlit platform but there is a work around to this outlined by Praneel Nihar here:" }, { "code": null, "e": 6226, "s": 6215, "text": "medium.com" }, { "code": null, "e": 6372, "s": 6226, "text": "I love scatter plots. If a scatter plot is static and in two dimensions, we have the ability to show up to five variables in just the one figure." }, { "code": null, "e": 6379, "s": 6372, "text": "X axis" }, { "code": null, "e": 6386, "s": 6379, "text": "Y axis" }, { "code": null, "e": 6400, "s": 6386, "text": "Scatter point" }, { "code": null, "e": 6413, "s": 6400, "text": "Scatter Size" }, { "code": null, "e": 6428, "s": 6413, "text": "Scatter Colour" }, { "code": null, "e": 6520, "s": 6428, "text": "And if we animate these plots we can add a sixth dimension of time to the visualisation too" }, { "code": null, "e": 6718, "s": 6520, "text": "Finally if we can give the user the opportunity to change each one of these variables, then the scope of analysis can be widened even further. Widgets in Streamlit allow us to provide this feature." }, { "code": null, "e": 6807, "s": 6718, "text": "In addition to X, Y and scatter data points I included some other visualisation options:" }, { "code": null, "e": 6890, "s": 6807, "text": "The option to mask by continent, i.e. only show countries from specific continents" }, { "code": null, "e": 7081, "s": 6890, "text": "For X and Y plot a vertical / horizontal line denoting a measure of central tendency for a feature. This allows you to see which markers are above or below the average for any plotted metric" }, { "code": null, "e": 7181, "s": 7081, "text": "The code block below outlines the steps needed to create the cross sectional scatter plot as above." }, { "code": null, "e": 7294, "s": 7181, "text": "And this code block below outlines the steps needed to create the cross sectional scatter plot that is animated." }, { "code": null, "e": 7609, "s": 7294, "text": "Hopefully this short walk through has given you some examples of how we can visualise data in a compelling way. By choosing the right tools to interact with the data and through using appropriate visualisations, exploratory analysis can be more efficient, more fun and more informative than using bar charts alone." }, { "code": null, "e": 7853, "s": 7609, "text": "By all means please take my Streamlit code and build on it — there is a lot of data here and even though I have written some comprehensive code to visualise the data I’m sure there’s plenty of other avenues that can be explored and built upon." }, { "code": null, "e": 7870, "s": 7853, "text": "Until next time!" }, { "code": null, "e": 7874, "s": 7870, "text": "Sam" }, { "code": null, "e": 7967, "s": 7874, "text": "To launch this app locally you should clone my forked OWID repo and in the command line run:" }, { "code": null, "e": 8006, "s": 7967, "text": "$ streamlit run covid_streamlit_app.py" }, { "code": null, "e": 8111, "s": 8006, "text": "Streamlit AppForked OWID repository with my appStreamlit app requirementsOriginal Our World In Data repo" }, { "code": null, "e": 8125, "s": 8111, "text": "Streamlit App" }, { "code": null, "e": 8160, "s": 8125, "text": "Forked OWID repository with my app" }, { "code": null, "e": 8187, "s": 8160, "text": "Streamlit app requirements" } ]
Python | sympy.integrate() method - GeeksforGeeks
12 Jun, 2019 With the help of sympy.integrate() method, we can find the integration of mathematical expressions in the form of variables by using sympy.integrate() method. Syntax : sympy.integrate(expression, reference variable)Return : Return integration of mathematical expression. Example #1 :In this example we can see that by using sympy.integrate() method, we can find the integration of mathematical expression with variables. Here we use symbols() method also to declare a variable as symbol. # import sympyfrom sympy import * x, y = symbols('x y')gfg_exp = sin(x)*exp(x) print("Before Integration : {}".format(gfg_exp)) # Use sympy.integrate() methodintr = integrate(gfg_exp, x) print("After Integration : {}".format(intr)) Output : Before Integration : exp(x)*sin(x) After Integration : exp(x)*sin(x)/2 – exp(x)*cos(x)/2 Example #2 : # import sympyfrom sympy import * x, y = symbols('x y')gfg_exp = sin(x)*tan(x) print("Before Integration : {}".format(gfg_exp)) # Use sympy.integrate() methodintr = integrate(gfg_exp, x) print("After Integration : {}".format(intr)) Output : Before Integration : sin(x)*tan(x) After Integration : -log(sin(x) – 1)/2 + log(sin(x) + 1)/2 – sin(x) SymPy 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": "\n12 Jun, 2019" }, { "code": null, "e": 24060, "s": 23901, "text": "With the help of sympy.integrate() method, we can find the integration of mathematical expressions in the form of variables by using sympy.integrate() method." }, { "code": null, "e": 24172, "s": 24060, "text": "Syntax : sympy.integrate(expression, reference variable)Return : Return integration of mathematical expression." }, { "code": null, "e": 24389, "s": 24172, "text": "Example #1 :In this example we can see that by using sympy.integrate() method, we can find the integration of mathematical expression with variables. Here we use symbols() method also to declare a variable as symbol." }, { "code": "# import sympyfrom sympy import * x, y = symbols('x y')gfg_exp = sin(x)*exp(x) print(\"Before Integration : {}\".format(gfg_exp)) # Use sympy.integrate() methodintr = integrate(gfg_exp, x) print(\"After Integration : {}\".format(intr))", "e": 24624, "s": 24389, "text": null }, { "code": null, "e": 24633, "s": 24624, "text": "Output :" }, { "code": null, "e": 24668, "s": 24633, "text": "Before Integration : exp(x)*sin(x)" }, { "code": null, "e": 24722, "s": 24668, "text": "After Integration : exp(x)*sin(x)/2 – exp(x)*cos(x)/2" }, { "code": null, "e": 24735, "s": 24722, "text": "Example #2 :" }, { "code": "# import sympyfrom sympy import * x, y = symbols('x y')gfg_exp = sin(x)*tan(x) print(\"Before Integration : {}\".format(gfg_exp)) # Use sympy.integrate() methodintr = integrate(gfg_exp, x) print(\"After Integration : {}\".format(intr))", "e": 24970, "s": 24735, "text": null }, { "code": null, "e": 24979, "s": 24970, "text": "Output :" }, { "code": null, "e": 25014, "s": 24979, "text": "Before Integration : sin(x)*tan(x)" }, { "code": null, "e": 25082, "s": 25014, "text": "After Integration : -log(sin(x) – 1)/2 + log(sin(x) + 1)/2 – sin(x)" }, { "code": null, "e": 25088, "s": 25082, "text": "SymPy" }, { "code": null, "e": 25095, "s": 25088, "text": "Python" }, { "code": null, "e": 25193, "s": 25095, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25202, "s": 25193, "text": "Comments" }, { "code": null, "e": 25215, "s": 25202, "text": "Old Comments" }, { "code": null, "e": 25247, "s": 25215, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 25303, "s": 25247, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 25345, "s": 25303, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 25387, "s": 25345, "text": "Check if element exists in list in Python" }, { "code": null, "e": 25423, "s": 25387, "text": "Python | Pandas dataframe.groupby()" }, { "code": null, "e": 25462, "s": 25423, "text": "Python | Get unique values from a list" }, { "code": null, "e": 25484, "s": 25462, "text": "Defaultdict in Python" }, { "code": null, "e": 25515, "s": 25484, "text": "Python | os.path.join() method" }, { "code": null, "e": 25542, "s": 25515, "text": "Python Classes and Objects" } ]
How to create a big font text using JavaScript?
To create a big font text, use the JavaScript big() method. This method causes a string to be displayed in a big font as if it were in a BIG tag. You can try to run the following code to create a big font text − Live Demo <html> <head> <title>JavaScript String big() Method</title> </head> <body> <script> var str = new String("Demo Text"); document.write("Following is bigger text: "+str.big()); </script> </body> </html>
[ { "code": null, "e": 1208, "s": 1062, "text": "To create a big font text, use the JavaScript big() method. This method causes a string to be displayed in a big font as if it were in a BIG tag." }, { "code": null, "e": 1274, "s": 1208, "text": "You can try to run the following code to create a big font text −" }, { "code": null, "e": 1284, "s": 1274, "text": "Live Demo" }, { "code": null, "e": 1534, "s": 1284, "text": "<html>\n <head>\n <title>JavaScript String big() Method</title>\n </head>\n\n <body>\n <script>\n var str = new String(\"Demo Text\");\n document.write(\"Following is bigger text: \"+str.big());\n </script>\n </body>\n</html>" } ]
\atop - Tex Command
\atop - Command to create fractions without horizontal fraction bar { sub-formula1 \atop sub-formula2 } \atop command creates a fraction like structure. a+1 \atop b a+1b a \atop b+2 ab+2 {a+1 \atop b+2}+c a+1b+2+c a+1 \atop b a+1b a+1 \atop b a \atop b+2 ab+2 a \atop b+2 {a+1 \atop b+2}+c a+1b+2+c {a+1 \atop b+2}+c 14 Lectures 52 mins Ashraf Said 11 Lectures 1 hours Ashraf Said 9 Lectures 1 hours Emenwa Global, Ejike IfeanyiChukwu 29 Lectures 2.5 hours Mohammad Nauman 14 Lectures 1 hours Daniel Stern 15 Lectures 47 mins Nishant Kumar Print Add Notes Bookmark this page
[ { "code": null, "e": 8054, "s": 7986, "text": "\\atop - Command to create fractions without horizontal fraction bar" }, { "code": null, "e": 8090, "s": 8054, "text": "{ sub-formula1 \\atop sub-formula2 }" }, { "code": null, "e": 8139, "s": 8090, "text": "\\atop command creates a fraction like structure." }, { "code": null, "e": 8219, "s": 8139, "text": "\na+1 \\atop b \n\na+1b\n\n\n a \\atop b+2 \n\nab+2\n\n\n {a+1 \\atop b+2}+c \n\na+1b+2+c\n\n\n" }, { "code": null, "e": 8241, "s": 8219, "text": "a+1 \\atop b \n\na+1b\n\n" }, { "code": null, "e": 8255, "s": 8241, "text": "a+1 \\atop b " }, { "code": null, "e": 8278, "s": 8255, "text": " a \\atop b+2 \n\nab+2\n\n" }, { "code": null, "e": 8293, "s": 8278, "text": " a \\atop b+2 " }, { "code": null, "e": 8326, "s": 8293, "text": " {a+1 \\atop b+2}+c \n\na+1b+2+c\n\n" }, { "code": null, "e": 8347, "s": 8326, "text": " {a+1 \\atop b+2}+c " }, { "code": null, "e": 8379, "s": 8347, "text": "\n 14 Lectures \n 52 mins\n" }, { "code": null, "e": 8392, "s": 8379, "text": " Ashraf Said" }, { "code": null, "e": 8425, "s": 8392, "text": "\n 11 Lectures \n 1 hours \n" }, { "code": null, "e": 8438, "s": 8425, "text": " Ashraf Said" }, { "code": null, "e": 8470, "s": 8438, "text": "\n 9 Lectures \n 1 hours \n" }, { "code": null, "e": 8506, "s": 8470, "text": " Emenwa Global, Ejike IfeanyiChukwu" }, { "code": null, "e": 8541, "s": 8506, "text": "\n 29 Lectures \n 2.5 hours \n" }, { "code": null, "e": 8558, "s": 8541, "text": " Mohammad Nauman" }, { "code": null, "e": 8591, "s": 8558, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 8605, "s": 8591, "text": " Daniel Stern" }, { "code": null, "e": 8637, "s": 8605, "text": "\n 15 Lectures \n 47 mins\n" }, { "code": null, "e": 8652, "s": 8637, "text": " Nishant Kumar" }, { "code": null, "e": 8659, "s": 8652, "text": " Print" }, { "code": null, "e": 8670, "s": 8659, "text": " Add Notes" } ]
Cleansing and transforming schema drifted CSV files into relational data in Azure Databricks | by Dhyanendra Singh Rathore | Towards Data Science
Data is the blood of a business. Data comes in varying shapes and sizes, making it a constant challenging task to find the means of processing and consumption, without which it holds no value whatsoever. This article looks at how to leverage Apache Spark’s parallel analytics capabilities to iteratively cleanse and transform schema drifted CSV files into queryable relational data to store in a data warehouse. We will work in a Spark environment and write code in PySpark to achieve our transformation goal. Caution: Microsoft Azure is a paid service, and following this article can cause financial liability to you or your organization. Please read our terms of use before proceeding with this article: https://dhyanintech.medium.com/disclaimer-disclosure-terms-of-use-fb3bfbd1e0e5 An active Microsoft Azure subscriptionAzure Data Lake Storage Gen2 account with CSV filesAzure Databricks Workspace (Premium Pricing Tier)Azure Synapse Analytics data warehouse An active Microsoft Azure subscription Azure Data Lake Storage Gen2 account with CSV files Azure Databricks Workspace (Premium Pricing Tier) Azure Synapse Analytics data warehouse If you don’t have prerequisites set up yet, refer to our previous articles to get started: medium.com medium.com Sign in to the Azure Portal, locate and open your Azure Databricks instance and click on ‘Launch Workspace.’ Our Databricks instance will open up in a new browser tab; wait for Azure AD SSO to sign you in automatically. Next, we need to create a cluster of nodes to leverage Apache Spark’s unparalleled parallel processing (pun intended) capabilities to process, cleanse, and transform our semi-structured data. spark.apache.org Select Clusters on the left menu to begin creating a new cluster. Start by selecting + Create Cluster and proceed as shown. Two essential things to pay attention to here are the Databricks runtime version and the minimum and the maximum number of worker nodes. Our cluster will scale automatically between these nodes to accommodate the load. Wait for the creation process to finish. Click on Start to start your cluster. It might take a few minutes for Azure to provision and set up your cluster resources. Keep an eye on the cluster status indicator to see the real-time status. The real magic of Databricks takes place in notebooks. Azure Databricks supports notebooks written in Python, Scala, SQL, and R. In our project, we will use Python and PySpark to code all the transformation and cleansing activities. Let’s get spinning by creating a Python notebook. A notebook is a web-based interface to a document that contains runnable code, narrative text, and visualizations. PySpark is a Python API for Apache Spark. Apache Spark is written in Scala. PySpark has been released to support the collaboration of Apache Spark and Python. Select the Workspace in the left menu and follow the steps as shown. Your notebook will open up after creation; take a minute to look around to familiarize yourself with the UI and various options available for us. The first few lines in a notebook should tell Databricks where our data is and how to access it. We will mount our storage account to the Databricks filesystem and access it as local storage. Please head over to our article for detailed steps on mounting and accessing ADLS Gen2 storage in Azure Databricks. We will keep it short. medium.com Our end goal is to load the data into a data warehouse to derive insights from the data and build reports to make decisions. Let’s set up the connectivity before proceeding. medium.com Our connections are all set; let’s get on with cleansing the CSV files we just mounted. We will briefly explain the purpose of statements and, in the end, present the entire code. First off, let’s read a file into PySpark and determine the schema. We will set some options to tell PySpark about the type and structure of the columns. # Read the csv files with first line as header, comma (,) as separator, and detect schema from the filecsvDf = spark.read.format("csv") \.option("inferSchema", "true") \.option("header", "true") \.option("sep", ",") \.load("dbfs:/mnt/csvFiles/01-22-2020.csv")csvDf.printSchema() This file has lesser columns than we expected from our GitHub Source and column names differ as well. We’re interested in highlighted columns for our final Power BI visualization. Let’s read a newer file and check the structure. This file’s structure is closer to our source’s description. The difference in schema doesn’t make things easy for us. If all our files have the same schema, we can load and cleanse all the files at once. Ours is a classic case of schema drift, and we must handle it appropriately; otherwise, our ELT (Extract, Load, and Transform) process will fail. We will design our transformation to account for this drift and make it unerring to schema changes. Schema drift is the case where a source often changes metadata. Fields, columns, and, types are subject to change, addition, or removal. We will start cleansing by renaming the columns to match our table's attributes in the database to have a one-to-one mapping between our table and the data. We will achieve this by converting all letters to lowercase and removing space, forwards slash (‘/’), and underscore (‘_’). # Function to flatten the column names by removing (' ', '/', '_') and converting them to lowercase lettersdef rename_columns(rename_df): for column in rename_df.columns: new_column = column.replace(' ','').replace('/','').replace('_','') rename_df = rename_df.withColumnRenamed(column, new_column.lower()) return rename_dfcsvDf = rename_columns(csvDf)csvDf.printSchema() Our column names look much better now. We will add a few new columns to deal with our missing column situation; active, longitude, latitude, and sourcefile. We will use the file name as the value for the sourcefile column. This column will be useful to set up the incremental load of our data into our database. First, we will rename lat and long column names to latitude and longitude if they exist in the data. Next, we will use lit()from PySpark to add missing active, latitude, and longitude columns with null values and sourcefile with the file name as the column value. # lit() function to create new columns in our dataframfrom pyspark.sql.functions import lit# Check dataframe and add/rename columns to fit our database table structureif 'lat' in csvDf.columns: csvDf = csvDf.withColumnRenamed('lat', 'latitude') if 'long' in csvDf.columns: csvDf = csvDf.withColumnRenamed('long', 'longitude') if 'active' not in csvDf.columns: csvDf = csvDf.withColumn('active', lit(None).cast("int")) if 'latitude' not in csvDf.columns: csvDf = csvDf.withColumn('latitude', lit(None).cast("decimal")) if 'longitude' not in csvDf.columns: csvDf = csvDf.withColumn('longitude', lit(None).cast("decimal"))# Add the source file name (without the extension) as an additional column to help us keep track of data sourcecsvDf = csvDf.withColumn("sourcefile", lit('01-22-2020.csv'.split('.')[0]))csvDf = csvDf.select("provincestate", "countryregion", "lastupdate", "confirmed", "deaths", "recovered", "active", "latitude", "longitude", "sourcefile")csvDf.printSchema() Let’s take a look at the data from the two files we viewed at the beginning of our cleansing activity using display(DATAFRAME) Both files now give us formatted data in a fixed desired structure and are ready to be inserted in our database. We have dealt with our drifted schema successfully. So far, we ran our code for two files manually; we should automate this to process files one after the other. We can use Databricks file system utilities to iterate through all the files. Further reading on Databricks file system utilities: docs.databricks.com # List all the files we have in our store to iterate through themfile_list = [file.name for file in dbutils.fs.ls("dbfs:{}".format(mountPoint))]for file in file_list: print(file) We only need to process the files that haven’t been loaded to our database yet (an incremental load). We can find out the name of the last file we loaded by querying the database and tweak our iterator code to ignore the files we have already loaded. # Find out the last file we loaded into the database# This will return null if there's no data in the tablelastLoadedFileQuery = "(SELECT MAX(sourcefile) as sourcefile FROM csvData.covidcsvdata) t"lastFileDf = spark.read.jdbc(url=jdbcUrl, table=lastLoadedFileQuery, properties=connectionProperties)lastFile = lastFileDf.collect()[0][0]# List all the files we have in our store to iterate through themfile_list = [file.name for file in dbutils.fs.ls("dbfs:{}".format(mountPoint))]# Find the index of the file from the listloadFrom = file_list.index('{}.csv'.format(lastFile)) + 1 if lastFile else 0# Trim the list keeping only the files that should be processedfile_list = file_list[loadFrom:]for file in file_list: print(file) Combining and restructuring all the code we’ve written so far will allow us to cleanse our schema drifted files with an incremental load to our database. Give it a try. You can find the entire notebook from GitHub at the end of the article for any troubleshooting purposes. We looked at our CSV files and realized that they have different schemas and need divergent processing methods before we can load them into our data warehouse. We used PySpark to make a creative solution to process our files incrementally and designed a solution to fit our needs. If you’re following our series on turning CSV data into Power BI visuals or are interested in learning how to add and execute Databricks notebook in your Data Factory pipeline, please head to our next article to continue the journey. medium.com Dhyanendra Singh Rathore is a Microsoft-certified Data, BI, and power platform professional. He is passionate about solving problems and currently gravitating towards serverless computing and AI platforms. He has a Master’s degree in Computer Networking Engineering. You can join him on Medium or connect with him on LinkedIn. Got any topic-related issues you wish to discuss? Shoot an email to dhyan.singh@everydaybi.com for a private consultation.
[ { "code": null, "e": 376, "s": 172, "text": "Data is the blood of a business. Data comes in varying shapes and sizes, making it a constant challenging task to find the means of processing and consumption, without which it holds no value whatsoever." }, { "code": null, "e": 682, "s": 376, "text": "This article looks at how to leverage Apache Spark’s parallel analytics capabilities to iteratively cleanse and transform schema drifted CSV files into queryable relational data to store in a data warehouse. We will work in a Spark environment and write code in PySpark to achieve our transformation goal." }, { "code": null, "e": 812, "s": 682, "text": "Caution: Microsoft Azure is a paid service, and following this article can cause financial liability to you or your organization." }, { "code": null, "e": 957, "s": 812, "text": "Please read our terms of use before proceeding with this article: https://dhyanintech.medium.com/disclaimer-disclosure-terms-of-use-fb3bfbd1e0e5" }, { "code": null, "e": 1134, "s": 957, "text": "An active Microsoft Azure subscriptionAzure Data Lake Storage Gen2 account with CSV filesAzure Databricks Workspace (Premium Pricing Tier)Azure Synapse Analytics data warehouse" }, { "code": null, "e": 1173, "s": 1134, "text": "An active Microsoft Azure subscription" }, { "code": null, "e": 1225, "s": 1173, "text": "Azure Data Lake Storage Gen2 account with CSV files" }, { "code": null, "e": 1275, "s": 1225, "text": "Azure Databricks Workspace (Premium Pricing Tier)" }, { "code": null, "e": 1314, "s": 1275, "text": "Azure Synapse Analytics data warehouse" }, { "code": null, "e": 1405, "s": 1314, "text": "If you don’t have prerequisites set up yet, refer to our previous articles to get started:" }, { "code": null, "e": 1416, "s": 1405, "text": "medium.com" }, { "code": null, "e": 1427, "s": 1416, "text": "medium.com" }, { "code": null, "e": 1647, "s": 1427, "text": "Sign in to the Azure Portal, locate and open your Azure Databricks instance and click on ‘Launch Workspace.’ Our Databricks instance will open up in a new browser tab; wait for Azure AD SSO to sign you in automatically." }, { "code": null, "e": 1839, "s": 1647, "text": "Next, we need to create a cluster of nodes to leverage Apache Spark’s unparalleled parallel processing (pun intended) capabilities to process, cleanse, and transform our semi-structured data." }, { "code": null, "e": 1856, "s": 1839, "text": "spark.apache.org" }, { "code": null, "e": 2240, "s": 1856, "text": "Select Clusters on the left menu to begin creating a new cluster. Start by selecting + Create Cluster and proceed as shown. Two essential things to pay attention to here are the Databricks runtime version and the minimum and the maximum number of worker nodes. Our cluster will scale automatically between these nodes to accommodate the load. Wait for the creation process to finish." }, { "code": null, "e": 2437, "s": 2240, "text": "Click on Start to start your cluster. It might take a few minutes for Azure to provision and set up your cluster resources. Keep an eye on the cluster status indicator to see the real-time status." }, { "code": null, "e": 2720, "s": 2437, "text": "The real magic of Databricks takes place in notebooks. Azure Databricks supports notebooks written in Python, Scala, SQL, and R. In our project, we will use Python and PySpark to code all the transformation and cleansing activities. Let’s get spinning by creating a Python notebook." }, { "code": null, "e": 2835, "s": 2720, "text": "A notebook is a web-based interface to a document that contains runnable code, narrative text, and visualizations." }, { "code": null, "e": 2994, "s": 2835, "text": "PySpark is a Python API for Apache Spark. Apache Spark is written in Scala. PySpark has been released to support the collaboration of Apache Spark and Python." }, { "code": null, "e": 3209, "s": 2994, "text": "Select the Workspace in the left menu and follow the steps as shown. Your notebook will open up after creation; take a minute to look around to familiarize yourself with the UI and various options available for us." }, { "code": null, "e": 3401, "s": 3209, "text": "The first few lines in a notebook should tell Databricks where our data is and how to access it. We will mount our storage account to the Databricks filesystem and access it as local storage." }, { "code": null, "e": 3540, "s": 3401, "text": "Please head over to our article for detailed steps on mounting and accessing ADLS Gen2 storage in Azure Databricks. We will keep it short." }, { "code": null, "e": 3551, "s": 3540, "text": "medium.com" }, { "code": null, "e": 3725, "s": 3551, "text": "Our end goal is to load the data into a data warehouse to derive insights from the data and build reports to make decisions. Let’s set up the connectivity before proceeding." }, { "code": null, "e": 3736, "s": 3725, "text": "medium.com" }, { "code": null, "e": 3916, "s": 3736, "text": "Our connections are all set; let’s get on with cleansing the CSV files we just mounted. We will briefly explain the purpose of statements and, in the end, present the entire code." }, { "code": null, "e": 4070, "s": 3916, "text": "First off, let’s read a file into PySpark and determine the schema. We will set some options to tell PySpark about the type and structure of the columns." }, { "code": null, "e": 4349, "s": 4070, "text": "# Read the csv files with first line as header, comma (,) as separator, and detect schema from the filecsvDf = spark.read.format(\"csv\") \\.option(\"inferSchema\", \"true\") \\.option(\"header\", \"true\") \\.option(\"sep\", \",\") \\.load(\"dbfs:/mnt/csvFiles/01-22-2020.csv\")csvDf.printSchema()" }, { "code": null, "e": 4529, "s": 4349, "text": "This file has lesser columns than we expected from our GitHub Source and column names differ as well. We’re interested in highlighted columns for our final Power BI visualization." }, { "code": null, "e": 4578, "s": 4529, "text": "Let’s read a newer file and check the structure." }, { "code": null, "e": 5029, "s": 4578, "text": "This file’s structure is closer to our source’s description. The difference in schema doesn’t make things easy for us. If all our files have the same schema, we can load and cleanse all the files at once. Ours is a classic case of schema drift, and we must handle it appropriately; otherwise, our ELT (Extract, Load, and Transform) process will fail. We will design our transformation to account for this drift and make it unerring to schema changes." }, { "code": null, "e": 5166, "s": 5029, "text": "Schema drift is the case where a source often changes metadata. Fields, columns, and, types are subject to change, addition, or removal." }, { "code": null, "e": 5447, "s": 5166, "text": "We will start cleansing by renaming the columns to match our table's attributes in the database to have a one-to-one mapping between our table and the data. We will achieve this by converting all letters to lowercase and removing space, forwards slash (‘/’), and underscore (‘_’)." }, { "code": null, "e": 5827, "s": 5447, "text": "# Function to flatten the column names by removing (' ', '/', '_') and converting them to lowercase lettersdef rename_columns(rename_df): for column in rename_df.columns: new_column = column.replace(' ','').replace('/','').replace('_','') rename_df = rename_df.withColumnRenamed(column, new_column.lower()) return rename_dfcsvDf = rename_columns(csvDf)csvDf.printSchema()" }, { "code": null, "e": 6139, "s": 5827, "text": "Our column names look much better now. We will add a few new columns to deal with our missing column situation; active, longitude, latitude, and sourcefile. We will use the file name as the value for the sourcefile column. This column will be useful to set up the incremental load of our data into our database." }, { "code": null, "e": 6403, "s": 6139, "text": "First, we will rename lat and long column names to latitude and longitude if they exist in the data. Next, we will use lit()from PySpark to add missing active, latitude, and longitude columns with null values and sourcefile with the file name as the column value." }, { "code": null, "e": 7393, "s": 6403, "text": "# lit() function to create new columns in our dataframfrom pyspark.sql.functions import lit# Check dataframe and add/rename columns to fit our database table structureif 'lat' in csvDf.columns: csvDf = csvDf.withColumnRenamed('lat', 'latitude') if 'long' in csvDf.columns: csvDf = csvDf.withColumnRenamed('long', 'longitude') if 'active' not in csvDf.columns: csvDf = csvDf.withColumn('active', lit(None).cast(\"int\")) if 'latitude' not in csvDf.columns: csvDf = csvDf.withColumn('latitude', lit(None).cast(\"decimal\")) if 'longitude' not in csvDf.columns: csvDf = csvDf.withColumn('longitude', lit(None).cast(\"decimal\"))# Add the source file name (without the extension) as an additional column to help us keep track of data sourcecsvDf = csvDf.withColumn(\"sourcefile\", lit('01-22-2020.csv'.split('.')[0]))csvDf = csvDf.select(\"provincestate\", \"countryregion\", \"lastupdate\", \"confirmed\", \"deaths\", \"recovered\", \"active\", \"latitude\", \"longitude\", \"sourcefile\")csvDf.printSchema()" }, { "code": null, "e": 7520, "s": 7393, "text": "Let’s take a look at the data from the two files we viewed at the beginning of our cleansing activity using display(DATAFRAME)" }, { "code": null, "e": 7685, "s": 7520, "text": "Both files now give us formatted data in a fixed desired structure and are ready to be inserted in our database. We have dealt with our drifted schema successfully." }, { "code": null, "e": 7873, "s": 7685, "text": "So far, we ran our code for two files manually; we should automate this to process files one after the other. We can use Databricks file system utilities to iterate through all the files." }, { "code": null, "e": 7926, "s": 7873, "text": "Further reading on Databricks file system utilities:" }, { "code": null, "e": 7946, "s": 7926, "text": "docs.databricks.com" }, { "code": null, "e": 8126, "s": 7946, "text": "# List all the files we have in our store to iterate through themfile_list = [file.name for file in dbutils.fs.ls(\"dbfs:{}\".format(mountPoint))]for file in file_list: print(file)" }, { "code": null, "e": 8377, "s": 8126, "text": "We only need to process the files that haven’t been loaded to our database yet (an incremental load). We can find out the name of the last file we loaded by querying the database and tweak our iterator code to ignore the files we have already loaded." }, { "code": null, "e": 9105, "s": 8377, "text": "# Find out the last file we loaded into the database# This will return null if there's no data in the tablelastLoadedFileQuery = \"(SELECT MAX(sourcefile) as sourcefile FROM csvData.covidcsvdata) t\"lastFileDf = spark.read.jdbc(url=jdbcUrl, table=lastLoadedFileQuery, properties=connectionProperties)lastFile = lastFileDf.collect()[0][0]# List all the files we have in our store to iterate through themfile_list = [file.name for file in dbutils.fs.ls(\"dbfs:{}\".format(mountPoint))]# Find the index of the file from the listloadFrom = file_list.index('{}.csv'.format(lastFile)) + 1 if lastFile else 0# Trim the list keeping only the files that should be processedfile_list = file_list[loadFrom:]for file in file_list: print(file)" }, { "code": null, "e": 9379, "s": 9105, "text": "Combining and restructuring all the code we’ve written so far will allow us to cleanse our schema drifted files with an incremental load to our database. Give it a try. You can find the entire notebook from GitHub at the end of the article for any troubleshooting purposes." }, { "code": null, "e": 9660, "s": 9379, "text": "We looked at our CSV files and realized that they have different schemas and need divergent processing methods before we can load them into our data warehouse. We used PySpark to make a creative solution to process our files incrementally and designed a solution to fit our needs." }, { "code": null, "e": 9894, "s": 9660, "text": "If you’re following our series on turning CSV data into Power BI visuals or are interested in learning how to add and execute Databricks notebook in your Data Factory pipeline, please head to our next article to continue the journey." }, { "code": null, "e": 9905, "s": 9894, "text": "medium.com" }, { "code": null, "e": 10172, "s": 9905, "text": "Dhyanendra Singh Rathore is a Microsoft-certified Data, BI, and power platform professional. He is passionate about solving problems and currently gravitating towards serverless computing and AI platforms. He has a Master’s degree in Computer Networking Engineering." }, { "code": null, "e": 10232, "s": 10172, "text": "You can join him on Medium or connect with him on LinkedIn." } ]
TimeZone getTimeZone() Method in Java with Examples - GeeksforGeeks
02 Jan, 2019 The getTimeZone() method of TimeZone class in Java is used to know the actual TimeZone for any passed TimeZone ID. Syntax: public static TimeZone getTimeZone(String the_ID) Parameters: The method takes one parameter the_ID of string datatype which refers to the ID of which the TimeZone is needed to be known. Return Value: The method either returns the specified TimeZone for the passed ID or the GMT zone if the specified ID cannot be understood by the program. Below programs illustrate the working of getTimeZone() Method of TimeZone:Example 1: // Java code to illustrate getTimeZone() method import java.util.*; public class TimeZoneDemo { public static void main(String args[]) { // Creating a TimeZone TimeZone the_time_zone = TimeZone.getDefault(); // Knowing the TimeZone System.out.println("The TimeZone is: " + the_time_zone .getTimeZone("GMT+5:30")); }} The TimeZone is: sun.util.calendar.ZoneInfo[id="GMT+05:30", offset=19800000, dstSavings=0, useDaylight=false, transitions=0, lastRule=null] Example 2: // Java code to illustrate getTimeZone() method import java.util.*; public class TimeZoneDemo { public static void main(String args[]) { // Creating a TimeZone TimeZone the_time_zone = TimeZone.getDefault(); // Knowing the TimeZone System.out.println("The TimeZone is: " + the_time_zone .getTimeZone("GMT-3:30")); }} The TimeZone is: sun.util.calendar.ZoneInfo[id="GMT-03:30", offset=-12600000, dstSavings=0, useDaylight=false, transitions=0, lastRule=null] Reference: https://docs.oracle.com/javase/7/docs/api/java/util/TimeZone.html#getTimeZone() Java - util package Java-Functions Java-TimeZone Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples How to iterate any Map in Java Initialize an ArrayList in Java Interfaces in Java ArrayList in Java Multidimensional Arrays in Java Stack Class in Java Singleton Class in Java Collections in Java
[ { "code": null, "e": 24163, "s": 24135, "text": "\n02 Jan, 2019" }, { "code": null, "e": 24278, "s": 24163, "text": "The getTimeZone() method of TimeZone class in Java is used to know the actual TimeZone for any passed TimeZone ID." }, { "code": null, "e": 24286, "s": 24278, "text": "Syntax:" }, { "code": null, "e": 24336, "s": 24286, "text": "public static TimeZone getTimeZone(String the_ID)" }, { "code": null, "e": 24473, "s": 24336, "text": "Parameters: The method takes one parameter the_ID of string datatype which refers to the ID of which the TimeZone is needed to be known." }, { "code": null, "e": 24627, "s": 24473, "text": "Return Value: The method either returns the specified TimeZone for the passed ID or the GMT zone if the specified ID cannot be understood by the program." }, { "code": null, "e": 24712, "s": 24627, "text": "Below programs illustrate the working of getTimeZone() Method of TimeZone:Example 1:" }, { "code": "// Java code to illustrate getTimeZone() method import java.util.*; public class TimeZoneDemo { public static void main(String args[]) { // Creating a TimeZone TimeZone the_time_zone = TimeZone.getDefault(); // Knowing the TimeZone System.out.println(\"The TimeZone is: \" + the_time_zone .getTimeZone(\"GMT+5:30\")); }}", "e": 25141, "s": 24712, "text": null }, { "code": null, "e": 25282, "s": 25141, "text": "The TimeZone is: sun.util.calendar.ZoneInfo[id=\"GMT+05:30\",\noffset=19800000, dstSavings=0, useDaylight=false, transitions=0, lastRule=null]\n" }, { "code": null, "e": 25293, "s": 25282, "text": "Example 2:" }, { "code": "// Java code to illustrate getTimeZone() method import java.util.*; public class TimeZoneDemo { public static void main(String args[]) { // Creating a TimeZone TimeZone the_time_zone = TimeZone.getDefault(); // Knowing the TimeZone System.out.println(\"The TimeZone is: \" + the_time_zone .getTimeZone(\"GMT-3:30\")); }}", "e": 25722, "s": 25293, "text": null }, { "code": null, "e": 25864, "s": 25722, "text": "The TimeZone is: sun.util.calendar.ZoneInfo[id=\"GMT-03:30\",\noffset=-12600000, dstSavings=0, useDaylight=false, transitions=0, lastRule=null]\n" }, { "code": null, "e": 25955, "s": 25864, "text": "Reference: https://docs.oracle.com/javase/7/docs/api/java/util/TimeZone.html#getTimeZone()" }, { "code": null, "e": 25975, "s": 25955, "text": "Java - util package" }, { "code": null, "e": 25990, "s": 25975, "text": "Java-Functions" }, { "code": null, "e": 26004, "s": 25990, "text": "Java-TimeZone" }, { "code": null, "e": 26009, "s": 26004, "text": "Java" }, { "code": null, "e": 26014, "s": 26009, "text": "Java" }, { "code": null, "e": 26112, "s": 26014, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26121, "s": 26112, "text": "Comments" }, { "code": null, "e": 26134, "s": 26121, "text": "Old Comments" }, { "code": null, "e": 26185, "s": 26134, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 26215, "s": 26185, "text": "HashMap in Java with Examples" }, { "code": null, "e": 26246, "s": 26215, "text": "How to iterate any Map in Java" }, { "code": null, "e": 26278, "s": 26246, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 26297, "s": 26278, "text": "Interfaces in Java" }, { "code": null, "e": 26315, "s": 26297, "text": "ArrayList in Java" }, { "code": null, "e": 26347, "s": 26315, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 26367, "s": 26347, "text": "Stack Class in Java" }, { "code": null, "e": 26391, "s": 26367, "text": "Singleton Class in Java" } ]
Find minimum sum of factors of number - GeeksforGeeks
31 Jan, 2022 Given a number, find minimum sum of its factors.Examples: Input : 12 Output : 7 Explanation: Following are different ways to factorize 12 and sum of factors in different ways. 12 = 12 * 1 = 12 + 1 = 13 12 = 2 * 6 = 2 + 6 = 8 12 = 3 * 4 = 3 + 4 = 7 12 = 2 * 2 * 3 = 2 + 2 + 3 = 7 Therefore minimum sum is 7 Input : 105 Output : 15 To minimize sum, we must factorize factors as long as possible. With this process, we prime factors. So to find minimum sum of product of number, we find sum of prime factors of product. C++ Java Python3 C# PHP Javascript // CPP program to find minimum// sum of product of number#include <bits/stdc++.h>using namespace std; // To find minimum sum of// product of numberint findMinSum(int num){ int sum = 0; // Find factors of number // and add to the sum for (int i = 2; i * i <= num; i++) { while (num % i == 0) { sum += i; num /= i; } } sum += num; // Return sum of numbers // having minimum product return sum;} // Driver program to test above functionint main(){ int num = 12; cout << findMinSum(num); return 0;} // Java program to find minimum// sum of product of number public class Main { // To find minimum sum of // product of number static int findMinSum(int num) { int sum = 0; // Find factors of number // and add to the sum for (int i = 2; i * i <= num; i++) { while (num % i == 0) { sum += i; num /= i; } } sum += num; // Return sum of numbers // having minimum product return sum; } // Driver program to test above function public static void main(String[] args) { int num = 12; System.out.println(findMinSum(num)); }} # Python program to find minimum# sum of product of number # To find minimum sum of# product of numberdef findMinSum(num): sum = 0 # Find factors of number # and add to the sum i = 2 while(i * i <= num): while(num % i == 0): sum += i num //= i i += 1 sum += num # Return sum of numbers # having minimum product return sum # Driver Codenum = 12print (findMinSum(num)) # This code is contributed by Sachin Bisht // C# program to find minimum// sum of product of numberusing System; public class GFG { // To find minimum sum of // product of number static int findMinSum(int num) { int sum = 0; // Find factors of number // and add to the sum for (int i = 2; i * i <= num; i++) { while (num % i == 0) { sum += i; num /= i; } } sum += num; // Return sum of numbers // having minimum product return sum; } // Driver Code public static void Main() { int num = 12; Console.Write(findMinSum(num)); } } // This Code is contributed by Nitin Mittal. <?php// PHP program to find minimum// sum of product of number // To find minimum sum of// product of numberfunction findMinSum($num){ $sum = 0; // Find factors of number // and add to the sum for ($i = 2; $i * $i <= $num; $i++) { while ($num % $i == 0) { $sum += $i; $num /= $i; } } $sum += $num; // Return sum of numbers // having minimum product return $sum;} // Driver Code$num = 12; echo(findMinSum($num)); // This code is contributed by Ajit.?> <script> // Javascript program to find minimum// sum of product of number // To find minimum sum of// product of numberfunction findMinSum(num){ let sum = 0; // Find factors of number // and add to the sum for (let i = 2; i * i <= num; i++) { while (num % i == 0) { sum += i; num /= i; } } sum += num; // Return sum of numbers // having minimum product return sum;} // Driver Codelet num = 12; document.write(findMinSum(num)); // This code is contributed by _saurabh_jaiswal. </script> Output: 7 This article is contributed by nuclode. 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. nitin mittal jit_t _saurabh_jaiswal amartyaghoshgfg number-theory prime-factor Mathematical number-theory Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Prime Numbers Print all possible combinations of r elements in a given array of size n Program for factorial of a number Operators in C / C++ Find minimum number of coins that make a given value The Knight's tour problem | Backtracking-1 Program to find sum of elements in a given array Program for Decimal to Binary Conversion
[ { "code": null, "e": 26139, "s": 26111, "text": "\n31 Jan, 2022" }, { "code": null, "e": 26199, "s": 26139, "text": "Given a number, find minimum sum of its factors.Examples: " }, { "code": null, "e": 26473, "s": 26199, "text": "Input : 12\nOutput : 7\nExplanation: \nFollowing are different ways to factorize 12 and\nsum of factors in different ways.\n12 = 12 * 1 = 12 + 1 = 13\n12 = 2 * 6 = 2 + 6 = 8\n12 = 3 * 4 = 3 + 4 = 7\n12 = 2 * 2 * 3 = 2 + 2 + 3 = 7\nTherefore minimum sum is 7\n\nInput : 105\nOutput : 15" }, { "code": null, "e": 26663, "s": 26475, "text": "To minimize sum, we must factorize factors as long as possible. With this process, we prime factors. So to find minimum sum of product of number, we find sum of prime factors of product. " }, { "code": null, "e": 26667, "s": 26663, "text": "C++" }, { "code": null, "e": 26672, "s": 26667, "text": "Java" }, { "code": null, "e": 26680, "s": 26672, "text": "Python3" }, { "code": null, "e": 26683, "s": 26680, "text": "C#" }, { "code": null, "e": 26687, "s": 26683, "text": "PHP" }, { "code": null, "e": 26698, "s": 26687, "text": "Javascript" }, { "code": "// CPP program to find minimum// sum of product of number#include <bits/stdc++.h>using namespace std; // To find minimum sum of// product of numberint findMinSum(int num){ int sum = 0; // Find factors of number // and add to the sum for (int i = 2; i * i <= num; i++) { while (num % i == 0) { sum += i; num /= i; } } sum += num; // Return sum of numbers // having minimum product return sum;} // Driver program to test above functionint main(){ int num = 12; cout << findMinSum(num); return 0;}", "e": 27269, "s": 26698, "text": null }, { "code": "// Java program to find minimum// sum of product of number public class Main { // To find minimum sum of // product of number static int findMinSum(int num) { int sum = 0; // Find factors of number // and add to the sum for (int i = 2; i * i <= num; i++) { while (num % i == 0) { sum += i; num /= i; } } sum += num; // Return sum of numbers // having minimum product return sum; } // Driver program to test above function public static void main(String[] args) { int num = 12; System.out.println(findMinSum(num)); }}", "e": 27946, "s": 27269, "text": null }, { "code": "# Python program to find minimum# sum of product of number # To find minimum sum of# product of numberdef findMinSum(num): sum = 0 # Find factors of number # and add to the sum i = 2 while(i * i <= num): while(num % i == 0): sum += i num //= i i += 1 sum += num # Return sum of numbers # having minimum product return sum # Driver Codenum = 12print (findMinSum(num)) # This code is contributed by Sachin Bisht", "e": 28430, "s": 27946, "text": null }, { "code": "// C# program to find minimum// sum of product of numberusing System; public class GFG { // To find minimum sum of // product of number static int findMinSum(int num) { int sum = 0; // Find factors of number // and add to the sum for (int i = 2; i * i <= num; i++) { while (num % i == 0) { sum += i; num /= i; } } sum += num; // Return sum of numbers // having minimum product return sum; } // Driver Code public static void Main() { int num = 12; Console.Write(findMinSum(num)); } } // This Code is contributed by Nitin Mittal.", "e": 29123, "s": 28430, "text": null }, { "code": "<?php// PHP program to find minimum// sum of product of number // To find minimum sum of// product of numberfunction findMinSum($num){ $sum = 0; // Find factors of number // and add to the sum for ($i = 2; $i * $i <= $num; $i++) { while ($num % $i == 0) { $sum += $i; $num /= $i; } } $sum += $num; // Return sum of numbers // having minimum product return $sum;} // Driver Code$num = 12; echo(findMinSum($num)); // This code is contributed by Ajit.?>", "e": 29649, "s": 29123, "text": null }, { "code": "<script> // Javascript program to find minimum// sum of product of number // To find minimum sum of// product of numberfunction findMinSum(num){ let sum = 0; // Find factors of number // and add to the sum for (let i = 2; i * i <= num; i++) { while (num % i == 0) { sum += i; num /= i; } } sum += num; // Return sum of numbers // having minimum product return sum;} // Driver Codelet num = 12; document.write(findMinSum(num)); // This code is contributed by _saurabh_jaiswal. </script>", "e": 30224, "s": 29649, "text": null }, { "code": null, "e": 30233, "s": 30224, "text": "Output: " }, { "code": null, "e": 30235, "s": 30233, "text": "7" }, { "code": null, "e": 30651, "s": 30235, "text": "This article is contributed by nuclode. 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": 30664, "s": 30651, "text": "nitin mittal" }, { "code": null, "e": 30670, "s": 30664, "text": "jit_t" }, { "code": null, "e": 30687, "s": 30670, "text": "_saurabh_jaiswal" }, { "code": null, "e": 30703, "s": 30687, "text": "amartyaghoshgfg" }, { "code": null, "e": 30717, "s": 30703, "text": "number-theory" }, { "code": null, "e": 30730, "s": 30717, "text": "prime-factor" }, { "code": null, "e": 30743, "s": 30730, "text": "Mathematical" }, { "code": null, "e": 30757, "s": 30743, "text": "number-theory" }, { "code": null, "e": 30770, "s": 30757, "text": "Mathematical" }, { "code": null, "e": 30868, "s": 30770, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30892, "s": 30868, "text": "Merge two sorted arrays" }, { "code": null, "e": 30935, "s": 30892, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 30949, "s": 30935, "text": "Prime Numbers" }, { "code": null, "e": 31022, "s": 30949, "text": "Print all possible combinations of r elements in a given array of size n" }, { "code": null, "e": 31056, "s": 31022, "text": "Program for factorial of a number" }, { "code": null, "e": 31077, "s": 31056, "text": "Operators in C / C++" }, { "code": null, "e": 31130, "s": 31077, "text": "Find minimum number of coins that make a given value" }, { "code": null, "e": 31173, "s": 31130, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 31222, "s": 31173, "text": "Program to find sum of elements in a given array" } ]
A Quick Way to Build Applications in Python | by Naser Tamimi | Towards Data Science
Building Python applications that have graphical user interfaces and are doing sophisticated tasks might look difficult. In a recently published article (see the link below), I mentioned how only 7 Python libraries are needed to start building applications. towardsdatascience.com This article will show you how to build a simple translation application in a few lines. I only use two Python libraries: requests and ipywidgets. I chose to write a translator application as an example to show you how it is easy to build applications in Python. This application gets an English text and shows its Spanish translation. Very easy and straightforward. To do so, we need two parts inside the application. The first part is a backend that does the translation, and the second part is a frontend or a graphical user interface (GUI) that interacts with the user (taking the input text and showing the output text). For the backend, I use Azure Translation API. If you are not familiar with the concept of API (Application Programming Interface), I try to explain it in an effortless way. An API is a way (i.e., protocol) to ask a service (for example, translation) from a service provider (usually a server). For example, you can use Google Maps API to get the driving distance between two locations. Imagine, if Google Maps API did not exist, then you should write your own code to calculate this driving distance based on roads databases. Simply, APIs prevent you from reinventing the wheel. Sometimes third party APIs are free, but most of the time, you must pay a little bit of cost (especially if you are using them frequently). For this article's purpose, we use Microsoft Azure Translator API, which is free for limited use. If you don’t have an Azure account, please read the next section; otherwise, you can skip it. If you don’t have an Azure account, you can sign up for a free one. Follow the instructions in the following link. It is easy and gives you free access to tens of awesome APIs and services. docs.microsoft.com After creating a free Azure account, you need to add Azure Translator API to your account. Again, it is free and easy. You need to follow the steps in the following link. docs.microsoft.com If you do everything correctly, you must have an API key (i.e., Authentication key). The key is simply a string of characters that lets you work with the Azure Translator API. You need the key to put it in your Python program (the next section). REMEMBER, never share your API keys with anyone (including your users). Now that you have your API key for Azure Translator (congratulations!), let’s see how we can talk to the API through Python. One of the most popular Python libraries to work with APIs is “requests.” You may install it using pip install requests or conda install -c anaconda requests The following Python function gets a text and sends a request to Azure Translator API. Before going further, I must tell you an important point (especially to beginners). The truth is: Each API has a set of rules for requesting a service. Working with Google Maps API is different from Azure Translator API. To work with an API, you must read the documentation. Let’s go back to our code ... In the code, you must put your API key (see API_KEY) and specify your API region (see API_REGION). requests.post sends a POST request to Azure Translator API. To send a request, you need to pass an URL address, parameters, headers, and a body. The URL address is a web address that Azure servers are constantly monitoring for any upcoming requests. As soon as the server sees your request, first, it checks your credentials in the header. If your credentials are valid, it looks at your parameters to understand what you are requesting. For example, in this case, I am requesting version 3.0 of the translator for translating from English (i.e. en) to Spanish (i.e. es). If the parameters are valid, then the API server takes the body (i.e., a JSON object in this example) and processes my requests. Finally, the requests.post send me a JSON object back that I named as response. You can check the function with a simple example. Add the following lines at the end of the code and run it. if __name__ == '__main__': print(azure_translate('Hello world.')) You must see an output like this. [{'translations': [{'text': 'Hola mundo.', 'to': 'es'}]}] This is a JSON (or Python dictionary) object in response to your request. If you look closely, you see the translation as well as some additional information such as the translated language (i.e., Spanish or es). Again, everything that is said here is based on the documentation, and you must be able to work with any API after reading the documentation. If you don’t read it, you never know how to communicate with an API and what parameters with what data structure should be passed. Now that you have your backend ready, it is time to build your frontend. As I mentioned previously (link), ipywidgets and Jupyter Notebooks are good combinations to build simple user interfaces for browsers. For my simple application, I only need a few elements in my user interface. Those elements are: A header to show the name of the application (a cosmetic feature).A text area widgets to input an English text.A button to request the translation after clicking.An empty area to print the Spanish translation. A header to show the name of the application (a cosmetic feature). A text area widgets to input an English text. A button to request the translation after clicking. An empty area to print the Spanish translation. Ipywidgets has a set of widgets to create different sorts of user interfaces and dashboards with them. For this application, I’ll use an HTML widget for the header, a Textarea widget for input text, a Button widget for requesting the translation, and an Output widget for printing out the results. Then I put them vertically aligned in a container using a VBox widget. The only trick is how to request a translation service when the user clicks on the translation button. It is simple to define this action upon the clicking event. To do so, I define a function and pass it to on_click method of the button. When a user clicks on the translation button, the specified function will run and send a request to Azure Translator API. Simple, right? The following codes show the front end part of the application. Now, it is time to put everything together in a Jupyter Notebook file. Put both parts in a Jupyter Notebook file and save it (e.g., Translator_API.ipynb). Since Ipywidgets work very well with Chrome, check if your default browser is Chrome. After setting your default browser to Chrome, open a terminal and run your Jupyter Notebook code via Voila. voila Translator_API.ipynb After a few seconds, you must see your application automatically opened in the browser. Give it a test like what I did here. Voila!!!!! you made your simple Translator application in a few steps. You can improve your GUI look by using ipyvuetify, a library full of modern-looking widgets. You can also share your MVP (minimum viable product) with other people using ngrok (read the following article for details). towardsdatascience.com Building applications in Python is easy and fast. You can use APIs to avoid reinventing the wheel and build your backend. You can also use simple libraries like ipywidgets or ipyvuetify to build a simple GUI for your application. In this article, I showed you how to build a simple translator application with a few lines of code. The same approach can be applied to more sophisticated MVP applications. Follow me on Medium and Twitter for the latest stories.
[ { "code": null, "e": 429, "s": 171, "text": "Building Python applications that have graphical user interfaces and are doing sophisticated tasks might look difficult. In a recently published article (see the link below), I mentioned how only 7 Python libraries are needed to start building applications." }, { "code": null, "e": 452, "s": 429, "text": "towardsdatascience.com" }, { "code": null, "e": 599, "s": 452, "text": "This article will show you how to build a simple translation application in a few lines. I only use two Python libraries: requests and ipywidgets." }, { "code": null, "e": 819, "s": 599, "text": "I chose to write a translator application as an example to show you how it is easy to build applications in Python. This application gets an English text and shows its Spanish translation. Very easy and straightforward." }, { "code": null, "e": 1078, "s": 819, "text": "To do so, we need two parts inside the application. The first part is a backend that does the translation, and the second part is a frontend or a graphical user interface (GUI) that interacts with the user (taking the input text and showing the output text)." }, { "code": null, "e": 1989, "s": 1078, "text": "For the backend, I use Azure Translation API. If you are not familiar with the concept of API (Application Programming Interface), I try to explain it in an effortless way. An API is a way (i.e., protocol) to ask a service (for example, translation) from a service provider (usually a server). For example, you can use Google Maps API to get the driving distance between two locations. Imagine, if Google Maps API did not exist, then you should write your own code to calculate this driving distance based on roads databases. Simply, APIs prevent you from reinventing the wheel. Sometimes third party APIs are free, but most of the time, you must pay a little bit of cost (especially if you are using them frequently). For this article's purpose, we use Microsoft Azure Translator API, which is free for limited use. If you don’t have an Azure account, please read the next section; otherwise, you can skip it." }, { "code": null, "e": 2179, "s": 1989, "text": "If you don’t have an Azure account, you can sign up for a free one. Follow the instructions in the following link. It is easy and gives you free access to tens of awesome APIs and services." }, { "code": null, "e": 2198, "s": 2179, "text": "docs.microsoft.com" }, { "code": null, "e": 2369, "s": 2198, "text": "After creating a free Azure account, you need to add Azure Translator API to your account. Again, it is free and easy. You need to follow the steps in the following link." }, { "code": null, "e": 2388, "s": 2369, "text": "docs.microsoft.com" }, { "code": null, "e": 2706, "s": 2388, "text": "If you do everything correctly, you must have an API key (i.e., Authentication key). The key is simply a string of characters that lets you work with the Azure Translator API. You need the key to put it in your Python program (the next section). REMEMBER, never share your API keys with anyone (including your users)." }, { "code": null, "e": 2831, "s": 2706, "text": "Now that you have your API key for Azure Translator (congratulations!), let’s see how we can talk to the API through Python." }, { "code": null, "e": 2930, "s": 2831, "text": "One of the most popular Python libraries to work with APIs is “requests.” You may install it using" }, { "code": null, "e": 2951, "s": 2930, "text": "pip install requests" }, { "code": null, "e": 2954, "s": 2951, "text": "or" }, { "code": null, "e": 2989, "s": 2954, "text": "conda install -c anaconda requests" }, { "code": null, "e": 3076, "s": 2989, "text": "The following Python function gets a text and sends a request to Azure Translator API." }, { "code": null, "e": 3174, "s": 3076, "text": "Before going further, I must tell you an important point (especially to beginners). The truth is:" }, { "code": null, "e": 3351, "s": 3174, "text": "Each API has a set of rules for requesting a service. Working with Google Maps API is different from Azure Translator API. To work with an API, you must read the documentation." }, { "code": null, "e": 3381, "s": 3351, "text": "Let’s go back to our code ..." }, { "code": null, "e": 4261, "s": 3381, "text": "In the code, you must put your API key (see API_KEY) and specify your API region (see API_REGION). requests.post sends a POST request to Azure Translator API. To send a request, you need to pass an URL address, parameters, headers, and a body. The URL address is a web address that Azure servers are constantly monitoring for any upcoming requests. As soon as the server sees your request, first, it checks your credentials in the header. If your credentials are valid, it looks at your parameters to understand what you are requesting. For example, in this case, I am requesting version 3.0 of the translator for translating from English (i.e. en) to Spanish (i.e. es). If the parameters are valid, then the API server takes the body (i.e., a JSON object in this example) and processes my requests. Finally, the requests.post send me a JSON object back that I named as response." }, { "code": null, "e": 4370, "s": 4261, "text": "You can check the function with a simple example. Add the following lines at the end of the code and run it." }, { "code": null, "e": 4439, "s": 4370, "text": "if __name__ == '__main__': print(azure_translate('Hello world.'))" }, { "code": null, "e": 4473, "s": 4439, "text": "You must see an output like this." }, { "code": null, "e": 4531, "s": 4473, "text": "[{'translations': [{'text': 'Hola mundo.', 'to': 'es'}]}]" }, { "code": null, "e": 4744, "s": 4531, "text": "This is a JSON (or Python dictionary) object in response to your request. If you look closely, you see the translation as well as some additional information such as the translated language (i.e., Spanish or es)." }, { "code": null, "e": 5017, "s": 4744, "text": "Again, everything that is said here is based on the documentation, and you must be able to work with any API after reading the documentation. If you don’t read it, you never know how to communicate with an API and what parameters with what data structure should be passed." }, { "code": null, "e": 5225, "s": 5017, "text": "Now that you have your backend ready, it is time to build your frontend. As I mentioned previously (link), ipywidgets and Jupyter Notebooks are good combinations to build simple user interfaces for browsers." }, { "code": null, "e": 5321, "s": 5225, "text": "For my simple application, I only need a few elements in my user interface. Those elements are:" }, { "code": null, "e": 5531, "s": 5321, "text": "A header to show the name of the application (a cosmetic feature).A text area widgets to input an English text.A button to request the translation after clicking.An empty area to print the Spanish translation." }, { "code": null, "e": 5598, "s": 5531, "text": "A header to show the name of the application (a cosmetic feature)." }, { "code": null, "e": 5644, "s": 5598, "text": "A text area widgets to input an English text." }, { "code": null, "e": 5696, "s": 5644, "text": "A button to request the translation after clicking." }, { "code": null, "e": 5744, "s": 5696, "text": "An empty area to print the Spanish translation." }, { "code": null, "e": 6113, "s": 5744, "text": "Ipywidgets has a set of widgets to create different sorts of user interfaces and dashboards with them. For this application, I’ll use an HTML widget for the header, a Textarea widget for input text, a Button widget for requesting the translation, and an Output widget for printing out the results. Then I put them vertically aligned in a container using a VBox widget." }, { "code": null, "e": 6489, "s": 6113, "text": "The only trick is how to request a translation service when the user clicks on the translation button. It is simple to define this action upon the clicking event. To do so, I define a function and pass it to on_click method of the button. When a user clicks on the translation button, the specified function will run and send a request to Azure Translator API. Simple, right?" }, { "code": null, "e": 6553, "s": 6489, "text": "The following codes show the front end part of the application." }, { "code": null, "e": 6708, "s": 6553, "text": "Now, it is time to put everything together in a Jupyter Notebook file. Put both parts in a Jupyter Notebook file and save it (e.g., Translator_API.ipynb)." }, { "code": null, "e": 6902, "s": 6708, "text": "Since Ipywidgets work very well with Chrome, check if your default browser is Chrome. After setting your default browser to Chrome, open a terminal and run your Jupyter Notebook code via Voila." }, { "code": null, "e": 6929, "s": 6902, "text": "voila Translator_API.ipynb" }, { "code": null, "e": 7054, "s": 6929, "text": "After a few seconds, you must see your application automatically opened in the browser. Give it a test like what I did here." }, { "code": null, "e": 7343, "s": 7054, "text": "Voila!!!!! you made your simple Translator application in a few steps. You can improve your GUI look by using ipyvuetify, a library full of modern-looking widgets. You can also share your MVP (minimum viable product) with other people using ngrok (read the following article for details)." }, { "code": null, "e": 7366, "s": 7343, "text": "towardsdatascience.com" }, { "code": null, "e": 7770, "s": 7366, "text": "Building applications in Python is easy and fast. You can use APIs to avoid reinventing the wheel and build your backend. You can also use simple libraries like ipywidgets or ipyvuetify to build a simple GUI for your application. In this article, I showed you how to build a simple translator application with a few lines of code. The same approach can be applied to more sophisticated MVP applications." } ]
WebSockets - Duplex Communication
Before diving to the need of Web sockets, it is necessary to have a look at the existing techniques, which are used for duplex communication between the server and the client. They are as follows − Polling Long Polling Streaming Postback and AJAX HTML5 Polling can be defined as a method, which performs periodic requests regardless of the data that exists in the transmission. The periodic requests are sent in a synchronous way. The client makes a periodic request in a specified time interval to the Server. The response of the server includes available data or some warning message in it. Long polling, as the name suggests, includes similar technique like polling. The client and the server keep the connection active until some data is fetched or timeout occurs. If the connection is lost due to some reasons, the client can start over and perform sequential request. Long polling is nothing but performance improvement over polling process, but constant requests may slow down the process. It is considered as the best option for real-time data transmission. The server keeps the connection open and active with the client until and unless the required data is being fetched. In this case, the connection is said to be open indefinitely. Streaming includes HTTP headers which increases the file size, increasing delay. This can be considered as a major drawback. AJAX is based on Javascript's XmlHttpRequest Object. It is an abbreviated form of Asynchronous Javascript and XML. XmlHttpRequest Object allows execution of the Javascript without reloading the complete web page. AJAX sends and receives only a portion of the web page. The code snippet of AJAX call with XmlHttpRequest Object is as follows − var xhttp; if (window.XMLHttpRequest) { xhttp = new XMLHttpRequest(); } else { // code for IE6, IE5 xhttp = new ActiveXObject("Microsoft.XMLHTTP"); } The major drawbacks of AJAX in comparison with Web Sockets are − They send HTTP headers, which makes total size larger. The communication is half-duplex. The web server consumes more resources. HTML5 is a robust framework for developing and designing web applications. The main pillars include Mark-up, CSS3 and Javascript APIs together. The following diagram shows HTML5 components − The code snippet given below describes the declaration of HTML5 and its doctype. <!DOCTYPE html> Internet was conceived to be a collection of Hypertext Mark-up Language (HTML) pages linking one another to form a conceptual web of information. During the course of time, static resources increased in number and richer items, such as images and began to be a part of the web fabric. Server technologies advanced which allowed dynamic server pages - pages whose content was generated based on a query. Soon, the requirement to have more dynamic web pages lead to the availability of Dynamic Hypertext Mark-up Language (DHTML). All thanks to JavaScript. Over the following years, we saw cross frame communication in an attempt to avoid page reloads followed by HTTP Polling within frames. However, none of these solutions offered a truly standardized cross browser solution to real-time bi-directional communication between a server and a client. This gave rise to the need of Web Sockets Protocol. It gave rise to full-duplex communication bringing desktop-rich functionality to all web browsers. Print Add Notes Bookmark this page
[ { "code": null, "e": 2317, "s": 2119, "text": "Before diving to the need of Web sockets, it is necessary to have a look at the existing techniques, which are used for duplex communication between the server and the client. They are as follows −" }, { "code": null, "e": 2325, "s": 2317, "text": "Polling" }, { "code": null, "e": 2338, "s": 2325, "text": "Long Polling" }, { "code": null, "e": 2348, "s": 2338, "text": "Streaming" }, { "code": null, "e": 2366, "s": 2348, "text": "Postback and AJAX" }, { "code": null, "e": 2372, "s": 2366, "text": "HTML5" }, { "code": null, "e": 2712, "s": 2372, "text": "Polling can be defined as a method, which performs periodic requests regardless of the data that exists in the transmission. The periodic requests are sent in a synchronous way. The client makes a periodic request in a specified time interval to the Server. The response of the server includes available data or some warning message in it." }, { "code": null, "e": 2993, "s": 2712, "text": "Long polling, as the name suggests, includes similar technique like polling. The client and the server keep the connection active until some data is fetched or timeout occurs. If the connection is lost due to some reasons, the client can start over and perform sequential request." }, { "code": null, "e": 3116, "s": 2993, "text": "Long polling is nothing but performance improvement over polling process, but constant requests may slow down the process." }, { "code": null, "e": 3489, "s": 3116, "text": "It is considered as the best option for real-time data transmission. The server keeps the connection open and active with the client until and unless the required data is being fetched. In this case, the connection is said to be open indefinitely. Streaming includes HTTP headers which increases the file size, increasing delay. This can be considered as a major drawback." }, { "code": null, "e": 3758, "s": 3489, "text": "AJAX is based on Javascript's XmlHttpRequest Object. It is an abbreviated form of Asynchronous Javascript and XML. XmlHttpRequest Object allows execution of the Javascript without reloading the complete web page. AJAX sends and receives only a portion of the web page." }, { "code": null, "e": 3831, "s": 3758, "text": "The code snippet of AJAX call with XmlHttpRequest Object is as follows −" }, { "code": null, "e": 3991, "s": 3831, "text": "var xhttp;\n\nif (window.XMLHttpRequest) {\n xhttp = new XMLHttpRequest();\n} else {\n // code for IE6, IE5\n xhttp = new ActiveXObject(\"Microsoft.XMLHTTP\");\n}" }, { "code": null, "e": 4056, "s": 3991, "text": "The major drawbacks of AJAX in comparison with Web Sockets are −" }, { "code": null, "e": 4111, "s": 4056, "text": "They send HTTP headers, which makes total size larger." }, { "code": null, "e": 4145, "s": 4111, "text": "The communication is half-duplex." }, { "code": null, "e": 4185, "s": 4145, "text": "The web server consumes more resources." }, { "code": null, "e": 4329, "s": 4185, "text": "HTML5 is a robust framework for developing and designing web applications. The main pillars include Mark-up, CSS3 and Javascript APIs together." }, { "code": null, "e": 4376, "s": 4329, "text": "The following diagram shows HTML5 components −" }, { "code": null, "e": 4457, "s": 4376, "text": "The code snippet given below describes the declaration of HTML5 and its doctype." }, { "code": null, "e": 4473, "s": 4457, "text": "<!DOCTYPE html>" }, { "code": null, "e": 4758, "s": 4473, "text": "Internet was conceived to be a collection of Hypertext Mark-up Language (HTML) pages linking one another to form a conceptual web of information. During the course of time, static resources increased in number and richer items, such as images and began to be a part of the web fabric." }, { "code": null, "e": 4876, "s": 4758, "text": "Server technologies advanced which allowed dynamic server pages - pages whose content was generated based on a query." }, { "code": null, "e": 5162, "s": 4876, "text": "Soon, the requirement to have more dynamic web pages lead to the availability of Dynamic Hypertext Mark-up Language (DHTML). All thanks to JavaScript. Over the following years, we saw cross frame communication in an attempt to avoid page reloads followed by HTTP Polling within frames." }, { "code": null, "e": 5320, "s": 5162, "text": "However, none of these solutions offered a truly standardized cross browser solution to real-time bi-directional communication between a server and a client." }, { "code": null, "e": 5471, "s": 5320, "text": "This gave rise to the need of Web Sockets Protocol. It gave rise to full-duplex communication bringing desktop-rich functionality to all web browsers." }, { "code": null, "e": 5478, "s": 5471, "text": " Print" }, { "code": null, "e": 5489, "s": 5478, "text": " Add Notes" } ]
HTML | DOM parentElement Property - GeeksforGeeks
26 Jul, 2019 The DOM parentElement property is used to returns the parent element of a particular child element. It is a read-only property. The parentElement and parentNode property are similar and the only difference is the parentElement property returns null if the parent node is not an element. Syntax: node.parentElement Return Value: It returns a string which represents the parent node of any child node or it returns a null if the specified node does not contain any parent node. Example 1: <!DOCTYPE html><html> <head> <title> HTML DOM parentElement Property </title> </head> <body> <h1 style = "color:green;"> GeeksForGeeks </h1> <h2>DOM parentElement Property</h2> <ol type = "1"> <li id = "GFG">Quick Sort</li> <li>Merge Sort</li> <li>Selection Sort</li> <li>Heap Sort</li> </ol> <button onclick="Geeks()"> Submit </button> <p id="sudo"></p> <!-- script to find parentElement --> <script> function Geeks() { var w = document.getElementById("GFG").parentElement.nodeName; document.getElementById("sudo").innerHTML = w; } </script> </body></html> Output:Before click on the button:After click on the button: Example 2: This example hide the parent element to click on the close icon. <!DOCTYPE html><html> <head> <title> HTML DOM parentElement Property </title> <!-- CSS property to create box--> <style> div { padding: 16px; width: 70%; background-color: green; color: white; border-radius:30px; } .GFG { float: right; font-size: 30px; font-weight: bold; cursor: pointer; } </style> </head> <body> <center> <h2>DOM parentElement Property</h2> <div> <span class = "GFG" onclick = "this.parentElement.style.display = 'none';"> × </span> <p style="font-size:30px;">GeeksforGeeks.</p> </div> </center> </body></html> output:Before click on the cross icon:After click on the cross icon:Supported Browsers: The browser supported by DOM parentElement property are listed below: Google Chrome 1.0 Internet Explorer Firefox 9.0 Opera Safari Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. HTML-DOM Picked HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? REST API (Introduction) How to Insert Form Data into Database using PHP ? Form validation using HTML and JavaScript Express.js express.Router() Function Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 23537, "s": 23509, "text": "\n26 Jul, 2019" }, { "code": null, "e": 23824, "s": 23537, "text": "The DOM parentElement property is used to returns the parent element of a particular child element. It is a read-only property. The parentElement and parentNode property are similar and the only difference is the parentElement property returns null if the parent node is not an element." }, { "code": null, "e": 23832, "s": 23824, "text": "Syntax:" }, { "code": null, "e": 23851, "s": 23832, "text": "node.parentElement" }, { "code": null, "e": 24013, "s": 23851, "text": "Return Value: It returns a string which represents the parent node of any child node or it returns a null if the specified node does not contain any parent node." }, { "code": null, "e": 24024, "s": 24013, "text": "Example 1:" }, { "code": "<!DOCTYPE html><html> <head> <title> HTML DOM parentElement Property </title> </head> <body> <h1 style = \"color:green;\"> GeeksForGeeks </h1> <h2>DOM parentElement Property</h2> <ol type = \"1\"> <li id = \"GFG\">Quick Sort</li> <li>Merge Sort</li> <li>Selection Sort</li> <li>Heap Sort</li> </ol> <button onclick=\"Geeks()\"> Submit </button> <p id=\"sudo\"></p> <!-- script to find parentElement --> <script> function Geeks() { var w = document.getElementById(\"GFG\").parentElement.nodeName; document.getElementById(\"sudo\").innerHTML = w; } </script> </body></html> ", "e": 24898, "s": 24024, "text": null }, { "code": null, "e": 24959, "s": 24898, "text": "Output:Before click on the button:After click on the button:" }, { "code": null, "e": 25035, "s": 24959, "text": "Example 2: This example hide the parent element to click on the close icon." }, { "code": "<!DOCTYPE html><html> <head> <title> HTML DOM parentElement Property </title> <!-- CSS property to create box--> <style> div { padding: 16px; width: 70%; background-color: green; color: white; border-radius:30px; } .GFG { float: right; font-size: 30px; font-weight: bold; cursor: pointer; } </style> </head> <body> <center> <h2>DOM parentElement Property</h2> <div> <span class = \"GFG\" onclick = \"this.parentElement.style.display = 'none';\"> × </span> <p style=\"font-size:30px;\">GeeksforGeeks.</p> </div> </center> </body></html> ", "e": 26028, "s": 25035, "text": null }, { "code": null, "e": 26186, "s": 26028, "text": "output:Before click on the cross icon:After click on the cross icon:Supported Browsers: The browser supported by DOM parentElement property are listed below:" }, { "code": null, "e": 26204, "s": 26186, "text": "Google Chrome 1.0" }, { "code": null, "e": 26222, "s": 26204, "text": "Internet Explorer" }, { "code": null, "e": 26234, "s": 26222, "text": "Firefox 9.0" }, { "code": null, "e": 26240, "s": 26234, "text": "Opera" }, { "code": null, "e": 26247, "s": 26240, "text": "Safari" }, { "code": null, "e": 26384, "s": 26247, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 26393, "s": 26384, "text": "HTML-DOM" }, { "code": null, "e": 26400, "s": 26393, "text": "Picked" }, { "code": null, "e": 26405, "s": 26400, "text": "HTML" }, { "code": null, "e": 26422, "s": 26405, "text": "Web Technologies" }, { "code": null, "e": 26427, "s": 26422, "text": "HTML" }, { "code": null, "e": 26525, "s": 26427, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26534, "s": 26525, "text": "Comments" }, { "code": null, "e": 26547, "s": 26534, "text": "Old Comments" }, { "code": null, "e": 26609, "s": 26547, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 26659, "s": 26609, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 26683, "s": 26659, "text": "REST API (Introduction)" }, { "code": null, "e": 26733, "s": 26683, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 26775, "s": 26733, "text": "Form validation using HTML and JavaScript" }, { "code": null, "e": 26812, "s": 26775, "text": "Express.js express.Router() Function" }, { "code": null, "e": 26845, "s": 26812, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 26907, "s": 26845, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 26950, "s": 26907, "text": "How to fetch data from an API in ReactJS ?" } ]
Making Menu options with Checkbutton in Tkinter?
The Menu Bar in Tkinter can be created by initializing Menu (parent) instances in the application. We can add checkbuttons in place of add_command to extend the feature of Menu Bar in any application. To add the menu items using the add_checkbutton(label, options) method, we first initialize a Menu Bar. Once the MenuBar is defined, we can give the value of menu items by using Checkbuttons. The CheckButtons can be used to add the list of Menu Items or options. Checkbuttons are nothing but the Boolean widget, which validates a particular value by making it True or False. To mark the status of checkbuttons in the menu items, we can use onvalue and offvalue. #Import the required Libraries from tkinter import * #Create an instance of Tkinter frame win = Tk() #Set the geometry of Tkinter Frame win.geometry("750x250") #Initialize a Menu Bar menubar = Menu(win) #Add Menu Items in the MenuBar menu_items = Menu(menubar) menu_items.add_checkbutton(label="C++", onvalue=1, offvalue=0) menu_items.add_checkbutton(label="Java", onvalue=1, offvalue=0) menu_items.add_checkbutton(label="Python", onvalue=1, offvalue=0) # Add the Viwable Menu to the MenuBar menubar.add_cascade(label='File', menu=menu_items) win.config(menu=menubar) win.mainloop() Run the above code to display a Menu Bar which is having the Menu Items of CheckButtons. When we select an item in the Menu, it will mark the item on/off.
[ { "code": null, "e": 1263, "s": 1062, "text": "The Menu Bar in Tkinter can be created by initializing Menu (parent) instances in the application. We can add checkbuttons in place of add_command to extend the feature of Menu Bar in any application." }, { "code": null, "e": 1725, "s": 1263, "text": "To add the menu items using the add_checkbutton(label, options) method, we first initialize a Menu Bar. Once the MenuBar is defined, we can give the value of menu items by using Checkbuttons. The CheckButtons can be used to add the list of Menu Items or options. Checkbuttons are nothing but the Boolean widget, which validates a particular value by making it True or False. To mark the status of checkbuttons in the menu items, we can use onvalue and offvalue." }, { "code": null, "e": 2312, "s": 1725, "text": "#Import the required Libraries\nfrom tkinter import *\n#Create an instance of Tkinter frame\nwin = Tk()\n#Set the geometry of Tkinter Frame\nwin.geometry(\"750x250\")\n\n#Initialize a Menu Bar\nmenubar = Menu(win)\n\n#Add Menu Items in the MenuBar\nmenu_items = Menu(menubar)\nmenu_items.add_checkbutton(label=\"C++\", onvalue=1, offvalue=0)\nmenu_items.add_checkbutton(label=\"Java\", onvalue=1, offvalue=0)\nmenu_items.add_checkbutton(label=\"Python\", onvalue=1, offvalue=0)\n\n# Add the Viwable Menu to the MenuBar\nmenubar.add_cascade(label='File', menu=menu_items)\nwin.config(menu=menubar)\n\nwin.mainloop()" }, { "code": null, "e": 2401, "s": 2312, "text": "Run the above code to display a Menu Bar which is having the Menu Items of CheckButtons." }, { "code": null, "e": 2467, "s": 2401, "text": "When we select an item in the Menu, it will mark the item on/off." } ]
MySQL procedure to call multiple procedures?
Let us first see the syntax, wherein we are calling multiple procedures from a stored procedure − DELIMITER // CREATE PROCEDURE yourProcedureName() BEGIN CALL yourStoredProcedureName1(); CALL yourStoredProcedureName2(); . . N END // DELIMITER // Let us implement the above syntax to call multiple stored procedures. Following is the query to create first stored procedure − mysql> DELIMITER // mysql> CREATE PROCEDURE hello_message() -> BEGIN -> SELECT 'HELLO WORLD !!'; -> END -> // Query OK, 0 rows affected (0.19 sec) The query to create second stored procedure is as follows − mysql> CREATE PROCEDURE hi_message() -> BEGIN -> SELECT 'HI !!!!'; -> END -> // Query OK, 0 rows affected (0.11 sec) mysql> DELIMITER ; Here is the query to create a new procedure to call multiple stored procedures − mysql> DELIMITER // mysql> CREATE PROCEDURE call_all_stored_procedure() -> BEGIN -> CALL hello_message(); -> CALL hi_message(); -> END -> // Query OK, 0 rows affected (0.26 sec) mysql> DELIMITER ; Now you can call the main stored procedure − mysql> call call_all_stored_procedure(); This will produce the following output − +----------------+ | HELLO WORLD !! | +----------------+ | HELLO WORLD !! | +----------------+ 1 row in set (0.06 sec) +---------+ | HI !!!! | +---------+ | HI !!!! | +---------+ 1 row in set (0.06 sec) Query OK, 0 rows affected (0.08 sec)
[ { "code": null, "e": 1160, "s": 1062, "text": "Let us first see the syntax, wherein we are calling multiple procedures from a stored procedure −" }, { "code": null, "e": 1323, "s": 1160, "text": "DELIMITER //\nCREATE PROCEDURE yourProcedureName()\nBEGIN\n CALL yourStoredProcedureName1();\n CALL yourStoredProcedureName2();\n .\n .\n N\nEND\n//\nDELIMITER //" }, { "code": null, "e": 1393, "s": 1323, "text": "Let us implement the above syntax to call multiple stored procedures." }, { "code": null, "e": 1451, "s": 1393, "text": "Following is the query to create first stored procedure −" }, { "code": null, "e": 1610, "s": 1451, "text": "mysql> DELIMITER //\nmysql> CREATE PROCEDURE hello_message()\n -> BEGIN\n -> SELECT 'HELLO WORLD !!';\n -> END\n -> //\nQuery OK, 0 rows affected (0.19 sec)" }, { "code": null, "e": 1670, "s": 1610, "text": "The query to create second stored procedure is as follows −" }, { "code": null, "e": 1819, "s": 1670, "text": "mysql> CREATE PROCEDURE hi_message()\n -> BEGIN\n -> SELECT 'HI !!!!';\n -> END\n -> //\nQuery OK, 0 rows affected (0.11 sec)\n\nmysql> DELIMITER ;" }, { "code": null, "e": 1900, "s": 1819, "text": "Here is the query to create a new procedure to call multiple stored procedures −" }, { "code": null, "e": 2113, "s": 1900, "text": "mysql> DELIMITER //\nmysql> CREATE PROCEDURE call_all_stored_procedure()\n -> BEGIN\n -> CALL hello_message();\n -> CALL hi_message();\n -> END\n -> //\nQuery OK, 0 rows affected (0.26 sec)\n\nmysql> DELIMITER ;" }, { "code": null, "e": 2158, "s": 2113, "text": "Now you can call the main stored procedure −" }, { "code": null, "e": 2199, "s": 2158, "text": "mysql> call call_all_stored_procedure();" }, { "code": null, "e": 2240, "s": 2199, "text": "This will produce the following output −" }, { "code": null, "e": 2481, "s": 2240, "text": "+----------------+\n| HELLO WORLD !! |\n+----------------+\n| HELLO WORLD !! |\n+----------------+\n1 row in set (0.06 sec)\n\n+---------+\n| HI !!!! |\n+---------+\n| HI !!!! |\n+---------+\n1 row in set (0.06 sec)\nQuery OK, 0 rows affected (0.08 sec)" } ]
Properties of Dictionary Keys in Python
Dictionary values have no restrictions. They can be any arbitrary Python object, either standard objects or user-defined objects. However, same is not true for the keys. There are two important points to remember about dictionary keys − More than one entry per key not allowed. Which means no duplicate key is allowed. When duplicate keys encountered during assignment, the last assignment wins. Following is a simple example − Live Demo #!/usr/bin/python dict = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'} print "dict['Name']: ", dict['Name'] When the above code is executed, it produces the following result − dict['Name']: Manni Keys must be immutable. Which means you can use strings, numbers or tuples as dictionary keys but something like ['key'] is not allowed. Following is a simple example − Live Demo #!/usr/bin/python dict = {['Name']: 'Zara', 'Age': 7} print "dict['Name']: ", dict['Name'] When the above code is executed, it produces the following result − Traceback (most recent call last): File "test.py", line 3, in <module> dict = {['Name']: 'Zara', 'Age': 7}; TypeError: unhashable type: 'list'
[ { "code": null, "e": 1232, "s": 1062, "text": "Dictionary values have no restrictions. They can be any arbitrary Python object, either standard objects or user-defined objects. However, same is not true for the keys." }, { "code": null, "e": 1299, "s": 1232, "text": "There are two important points to remember about dictionary keys −" }, { "code": null, "e": 1458, "s": 1299, "text": "More than one entry per key not allowed. Which means no duplicate key is allowed. When duplicate keys encountered during assignment, the last assignment wins." }, { "code": null, "e": 1490, "s": 1458, "text": "Following is a simple example −" }, { "code": null, "e": 1501, "s": 1490, "text": " Live Demo" }, { "code": null, "e": 1607, "s": 1501, "text": "#!/usr/bin/python\ndict = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'}\nprint \"dict['Name']: \", dict['Name']" }, { "code": null, "e": 1675, "s": 1607, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 1696, "s": 1675, "text": "dict['Name']: Manni\n" }, { "code": null, "e": 1833, "s": 1696, "text": "Keys must be immutable. Which means you can use strings, numbers or tuples as dictionary keys but something like ['key'] is not allowed." }, { "code": null, "e": 1865, "s": 1833, "text": "Following is a simple example −" }, { "code": null, "e": 1876, "s": 1865, "text": " Live Demo" }, { "code": null, "e": 1967, "s": 1876, "text": "#!/usr/bin/python\ndict = {['Name']: 'Zara', 'Age': 7}\nprint \"dict['Name']: \", dict['Name']" }, { "code": null, "e": 2035, "s": 1967, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 2178, "s": 2035, "text": "Traceback (most recent call last):\nFile \"test.py\", line 3, in <module>\ndict = {['Name']: 'Zara', 'Age': 7};\nTypeError: unhashable type: 'list'" } ]
max() and min() in Python
Finding maximum and minimum values from a given list of values is a very common need in data processing programs. Python has these two functions which handle both numbers and strings. We will see both the scenarios in the below examples. We take a list of numeric values which has integers and floats. The functions work appropriately to give both the max and the min values. Live Demo x=[10,15,25.5,3,2,9/5,40,70] print("Maximum number is :",max(x)) print("\nMinimum number is :",min(x)) Running the above code gives us the following result: Maximum number is : 70 Minimum number is : 1.8 The string values are compared lexicographically to get the correct result. Internally the ascii values of the characters are compared. Live Demo x=['Mon','Tue','Wed','Thu','Fri','Sat','Sun'] print("Maximum number is :",max(x)) print("\nMinimum number is :",min(x)) Running the above code gives us the following result: Maximum number is : Wed Minimum number is : Fri
[ { "code": null, "e": 1300, "s": 1062, "text": "Finding maximum and minimum values from a given list of values is a very common need in data processing programs. Python has these two functions which handle both numbers and strings. We will see both the scenarios in the below examples." }, { "code": null, "e": 1438, "s": 1300, "text": "We take a list of numeric values which has integers and floats. The functions work appropriately to give both the max and the min values." }, { "code": null, "e": 1449, "s": 1438, "text": " Live Demo" }, { "code": null, "e": 1552, "s": 1449, "text": "x=[10,15,25.5,3,2,9/5,40,70]\nprint(\"Maximum number is :\",max(x))\nprint(\"\\nMinimum number is :\",min(x))" }, { "code": null, "e": 1606, "s": 1552, "text": "Running the above code gives us the following result:" }, { "code": null, "e": 1653, "s": 1606, "text": "Maximum number is : 70\nMinimum number is : 1.8" }, { "code": null, "e": 1789, "s": 1653, "text": "The string values are compared lexicographically to get the correct result. Internally the ascii values of the characters are compared." }, { "code": null, "e": 1800, "s": 1789, "text": " Live Demo" }, { "code": null, "e": 1920, "s": 1800, "text": "x=['Mon','Tue','Wed','Thu','Fri','Sat','Sun']\nprint(\"Maximum number is :\",max(x))\nprint(\"\\nMinimum number is :\",min(x))" }, { "code": null, "e": 1974, "s": 1920, "text": "Running the above code gives us the following result:" }, { "code": null, "e": 2022, "s": 1974, "text": "Maximum number is : Wed\nMinimum number is : Fri" } ]
C program to design a hot air balloon using graphics - GeeksforGeeks
23 Apr, 2021 In this article, we will discuss how to design a Hot Air Balloon in the C using Graphics. Approach: Draw a circle using the circle() function. Draw a total of four lines using the line() function which will act as the rope that holds the container. Implement the container using the rectangle() function. Color the circle which will act as a balloon with red using the setfillstyle() & floodfill() functions. Color the container yellow & brown using the setfillstyle() & floodfill() functions. Color all the ropes white using the setfillstyle() & floodfill() functions. Set the background color blue using setfillstyle() & floodfill() functions. Below is the implementation of the above approach: C // C program to design a Hot Air Balloon// using graphics#include <conio.h>#include <graphics.h>#include <stdio.h> // Driver Codevoid main(){ int gd = DETECT, gm; // Initialize of gdriver with // DETECT macros initgraph(&gd, &gm, "C:\\" "turboc3\\bgi"); // Set the Background Color to blue setfillstyle(SOLID_FILL, BLUE); floodfill(100, 100, 15); // Set Circle Balloon Color // With Red setfillstyle(SOLID_FILL, RED); // Creating Balloon circle(550, 200, 100); floodfill(552, 202, 15); // Set The Rope Color // With White setfillstyle(SOLID_FILL, WHITE); // Right Side Right Rope line(650, 200, 630, 400); // Right Side Left Rope line(650, 200, 620, 400); // Connect the two right side ropes // for coloring purpose line(620, 400, 630, 400); floodfill(625, 398, 15); // Left side left rope line(450, 200, 470, 400); // Left side right rope line(450, 200, 480, 400); // Connect the two left side ropes // for coloring purpose line(470, 400, 480, 400); floodfill(475, 398, 15); // Set Container One Part // With Brown setfillstyle(SOLID_FILL, BROWN); rectangle(450, 400, 650, 500); floodfill(452, 402, 15); // Set Container Another // Part With Yellow setfillstyle(XHATCH_FILL, YELLOW); // Dividing Container For // Decorating Purpose line(450, 430, 650, 430); floodfill(452, 498, 15); // Hold the screen getch(); // Close the initialized gdriver closegraph();} Output: c-graphics computer-graphics C Language C Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments TCP Server-Client implementation in C Exception Handling in C++ Multithreading in C 'this' pointer in C++ Arrow operator -> in C/C++ with Examples Strings in C Arrow operator -> in C/C++ with Examples C Program to read contents of Whole File UDP Server-Client implementation in C Header files in C/C++ and its uses
[ { "code": null, "e": 23817, "s": 23789, "text": "\n23 Apr, 2021" }, { "code": null, "e": 23907, "s": 23817, "text": "In this article, we will discuss how to design a Hot Air Balloon in the C using Graphics." }, { "code": null, "e": 23917, "s": 23907, "text": "Approach:" }, { "code": null, "e": 23960, "s": 23917, "text": "Draw a circle using the circle() function." }, { "code": null, "e": 24066, "s": 23960, "text": "Draw a total of four lines using the line() function which will act as the rope that holds the container." }, { "code": null, "e": 24122, "s": 24066, "text": "Implement the container using the rectangle() function." }, { "code": null, "e": 24226, "s": 24122, "text": "Color the circle which will act as a balloon with red using the setfillstyle() & floodfill() functions." }, { "code": null, "e": 24311, "s": 24226, "text": "Color the container yellow & brown using the setfillstyle() & floodfill() functions." }, { "code": null, "e": 24387, "s": 24311, "text": "Color all the ropes white using the setfillstyle() & floodfill() functions." }, { "code": null, "e": 24463, "s": 24387, "text": "Set the background color blue using setfillstyle() & floodfill() functions." }, { "code": null, "e": 24514, "s": 24463, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 24516, "s": 24514, "text": "C" }, { "code": "// C program to design a Hot Air Balloon// using graphics#include <conio.h>#include <graphics.h>#include <stdio.h> // Driver Codevoid main(){ int gd = DETECT, gm; // Initialize of gdriver with // DETECT macros initgraph(&gd, &gm, \"C:\\\\\" \"turboc3\\\\bgi\"); // Set the Background Color to blue setfillstyle(SOLID_FILL, BLUE); floodfill(100, 100, 15); // Set Circle Balloon Color // With Red setfillstyle(SOLID_FILL, RED); // Creating Balloon circle(550, 200, 100); floodfill(552, 202, 15); // Set The Rope Color // With White setfillstyle(SOLID_FILL, WHITE); // Right Side Right Rope line(650, 200, 630, 400); // Right Side Left Rope line(650, 200, 620, 400); // Connect the two right side ropes // for coloring purpose line(620, 400, 630, 400); floodfill(625, 398, 15); // Left side left rope line(450, 200, 470, 400); // Left side right rope line(450, 200, 480, 400); // Connect the two left side ropes // for coloring purpose line(470, 400, 480, 400); floodfill(475, 398, 15); // Set Container One Part // With Brown setfillstyle(SOLID_FILL, BROWN); rectangle(450, 400, 650, 500); floodfill(452, 402, 15); // Set Container Another // Part With Yellow setfillstyle(XHATCH_FILL, YELLOW); // Dividing Container For // Decorating Purpose line(450, 430, 650, 430); floodfill(452, 498, 15); // Hold the screen getch(); // Close the initialized gdriver closegraph();}", "e": 26078, "s": 24516, "text": null }, { "code": null, "e": 26086, "s": 26078, "text": "Output:" }, { "code": null, "e": 26097, "s": 26086, "text": "c-graphics" }, { "code": null, "e": 26115, "s": 26097, "text": "computer-graphics" }, { "code": null, "e": 26126, "s": 26115, "text": "C Language" }, { "code": null, "e": 26137, "s": 26126, "text": "C Programs" }, { "code": null, "e": 26235, "s": 26137, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26244, "s": 26235, "text": "Comments" }, { "code": null, "e": 26257, "s": 26244, "text": "Old Comments" }, { "code": null, "e": 26295, "s": 26257, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 26321, "s": 26295, "text": "Exception Handling in C++" }, { "code": null, "e": 26341, "s": 26321, "text": "Multithreading in C" }, { "code": null, "e": 26363, "s": 26341, "text": "'this' pointer in C++" }, { "code": null, "e": 26404, "s": 26363, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 26417, "s": 26404, "text": "Strings in C" }, { "code": null, "e": 26458, "s": 26417, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 26499, "s": 26458, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 26537, "s": 26499, "text": "UDP Server-Client implementation in C" } ]
How can I make one Python file run another?
There are multiple ways to make one Python file run another. 1. Use it like a module. import the file you want to run and run its functions. For example, say you want to import fileB.py into fileA.py, assuming the files are in the same directory, inside fileA you'd write import fileB Now in fileA, you can call any function inside fileB like: fileB.my_func() 2. You can use the exec command. execfile('file.py') executes the file.py file in the interpreter. 3. You can spawn a new process using the os.system command. os.system('python my_file.py')
[ { "code": null, "e": 1123, "s": 1062, "text": "There are multiple ways to make one Python file run another." }, { "code": null, "e": 1334, "s": 1123, "text": "1. Use it like a module. import the file you want to run and run its functions. For example, say you want to import fileB.py into fileA.py, assuming the files are in the same directory, inside fileA you'd write" }, { "code": null, "e": 1347, "s": 1334, "text": "import fileB" }, { "code": null, "e": 1406, "s": 1347, "text": "Now in fileA, you can call any function inside fileB like:" }, { "code": null, "e": 1422, "s": 1406, "text": "fileB.my_func()" }, { "code": null, "e": 1456, "s": 1422, "text": "2. You can use the exec command. " }, { "code": null, "e": 1476, "s": 1456, "text": "execfile('file.py')" }, { "code": null, "e": 1523, "s": 1476, "text": " executes the file.py file in the interpreter." }, { "code": null, "e": 1583, "s": 1523, "text": "3. You can spawn a new process using the os.system command." }, { "code": null, "e": 1614, "s": 1583, "text": "os.system('python my_file.py')" } ]
JSF - First Application
To create a simple JSF application, we'll use maven-archetype-webapp plugin. In the following example, we'll create a maven-based web application project in C:\JSF folder. Let's open command console, go the C:\ > JSF directory and execute the following mvn command. C:\JSF>mvn archetype:create -DgroupId = com.tutorialspoint.test -DartifactId = helloworld -DarchetypeArtifactId = maven-archetype-webapp Maven will start processing and will create the complete java web application project structure. [INFO] Scanning for projects... [INFO] Searching repository for plugin with prefix: 'archetype'. [INFO] ------------------------------------------------------------- [INFO] Building Maven Default Project [INFO] task-segment: [archetype:create] (aggregator-style) [INFO] ------------------------------------------------------------- [INFO] [archetype:create {execution: default-cli}] [INFO] Defaulting package to group ID: com.tutorialspoint.test [INFO] artifact org.apache.maven.archetypes:maven-archetype-webapp: checking for updates from central [INFO] ------------------------------------------------------------- [INFO] Using following parameters for creating project from Old (1.x) Archetype: maven-archetype-webapp:RELEASE [INFO] ------------------------------------------------------------- [INFO] Parameter: groupId, Value: com.tutorialspoint.test [INFO] Parameter: packageName, Value: com.tutorialspoint.test [INFO] Parameter: package, Value: com.tutorialspoint.test [INFO] Parameter: artifactId, Value: helloworld [INFO] Parameter: basedir, Value: C:\JSF [INFO] Parameter: version, Value: 1.0-SNAPSHOT [INFO] project created from Old (1.x) Archetype in dir: C:\JSF\helloworld [INFO] ------------------------------------------------------------- [INFO] BUILD SUCCESSFUL [INFO] ------------------------------------------------------------- [INFO] Total time: 7 seconds [INFO] Finished at: Mon Nov 05 16:05:04 IST 2012 [INFO] Final Memory: 12M/84M [INFO] ------------------------------------------------------------- Now go to C:/JSF directory. You'll see a Java web application project created, named helloworld (as specified in artifactId). Maven uses a standard directory layout as shown in the following screenshot. Using the above example, we can understand the following key concepts. helloworld Contains src folder and pom.xml src/main/wepapp Contains WEB-INF folder and index.jsp page src/main/resources It contains images/properties files (In the above example, we need to create this structure manually) Add the following JSF dependencies. <dependencies> <dependency> <groupId>com.sun.faces</groupId> <artifactId>jsf-api</artifactId> <version>2.1.7</version> </dependency> <dependency> <groupId>com.sun.faces</groupId> <artifactId>jsf-impl</artifactId> <version>2.1.7</version> </dependency> </dependencies> <project xmlns = "http://maven.apache.org/POM/4.0.0" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.tutorialspoint.test</groupId> <artifactId>helloworld</artifactId> <packaging>war</packaging> <version>1.0-SNAPSHOT</version> <name>helloworld Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>com.sun.faces</groupId> <artifactId>jsf-api</artifactId> <version>2.1.7</version> </dependency> <dependency> <groupId>com.sun.faces</groupId> <artifactId>jsf-impl</artifactId> <version>2.1.7</version> </dependency> </dependencies> <build> <finalName>helloworld</finalName> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.3.1</version> <configuration> <source>1.6</source> <target>1.6</target> </configuration> </plugin> </plugins> </build> </project> Let's open the command console. Go the C:\ > JSF > helloworld directory and execute the following mvn command. C:\JSF\helloworld>mvn eclipse:eclipse -Dwtpversion = 2.0 Maven will start processing, create the eclipse ready project, and will add wtp capability. Downloading: http://repo.maven.apache.org/org/apache/maven/plugins/ maven-compiler-plugin/2.3.1/maven-compiler-plugin-2.3.1.pom 5K downloaded (maven-compiler-plugin-2.3.1.pom) Downloading: http://repo.maven.apache.org/org/apache/maven/plugins/ maven-compiler-plugin/2.3.1/maven-compiler-plugin-2.3.1.jar 29K downloaded (maven-compiler-plugin-2.3.1.jar) [INFO] Searching repository for plugin with prefix: 'eclipse'. [INFO] ------------------------------------------------------------ [INFO] Building helloworld Maven Webapp [INFO] task-segment: [eclipse:eclipse] [INFO] ------------------------------------------------------------ [INFO] Preparing eclipse:eclipse [INFO] No goals needed for project - skipping [INFO] [eclipse:eclipse {execution: default-cli}] [INFO] Adding support for WTP version 2.0. [INFO] Using Eclipse Workspace: null [INFO] Adding default classpath container: org.eclipse.jdt. launching.JRE_CONTAINER Downloading: http://repo.maven.apache.org/ com/sun/faces/jsf-api/2.1.7/jsf-api-2.1.7.pom 12K downloaded (jsf-api-2.1.7.pom) Downloading: http://repo.maven.apache.org/ com/sun/faces/jsf-impl/2.1.7/jsf-impl-2.1.7.pom 10K downloaded (jsf-impl-2.1.7.pom) Downloading: http://repo.maven.apache.org/ com/sun/faces/jsf-api/2.1.7/jsf-api-2.1.7.jar 619K downloaded (jsf-api-2.1.7.jar) Downloading: http://repo.maven.apache.org/ com/sun/faces/jsf-impl/2.1.7/jsf-impl-2.1.7.jar 1916K downloaded (jsf-impl-2.1.7.jar) [INFO] Wrote settings to C:\JSF\helloworld\.settings\ org.eclipse.jdt.core.prefs [INFO] Wrote Eclipse project for "helloworld" to C:\JSF\helloworld. [INFO] [INFO] ----------------------------------------------------------- [INFO] BUILD SUCCESSFUL [INFO] ----------------------------------------------------------- [INFO] Total time: 6 minutes 7 seconds [INFO] Finished at: Mon Nov 05 16:16:25 IST 2012 [INFO] Final Memory: 10M/89M [INFO] ----------------------------------------------------------- Following are the steps − Import project in eclipse using Import wizard. Import project in eclipse using Import wizard. Go to File → Import... → Existing project into workspace. Go to File → Import... → Existing project into workspace. Select root directory to helloworld. Select root directory to helloworld. Keep Copy projects into workspace to be checked. Keep Copy projects into workspace to be checked. Click Finish button. Click Finish button. Eclipse will import and copy the project in its workspace C:\ → Projects → Data → WorkSpace. Eclipse will import and copy the project in its workspace C:\ → Projects → Data → WorkSpace. Locate web.xml in webapp → WEB-INF folder and update it as shown below. <?xml version = "1.0" encoding = "UTF-8"?> <web-app xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns = "http://java.sun.com/xml/ns/javaee" xmlns:web = "http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation = "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id = "WebApp_ID" version="2.5"> <welcome-file-list> <welcome-file>faces/home.xhtml</welcome-file> </welcome-file-list> <!-- FacesServlet is main servlet responsible to handle all request. It acts as central controller. This servlet initializes the JSF components before the JSP is displayed. --> <servlet> <servlet-name>Faces Servlet</servlet-name> <servlet-class>javax.faces.webapp.FacesServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern>/faces/*</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern>*.jsf</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern>*.faces</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern>*.xhtml</url-pattern> </servlet-mapping> </web-app> Create a package structure under src → main → java as com → tutorialspoint → test. Create HelloWorld.java class in this package. Update the code of HelloWorld.java as shown below. package com.tutorialspoint.test; import javax.faces.bean.ManagedBean; @ManagedBean(name = "helloWorld", eager = true) public class HelloWorld { public HelloWorld() { System.out.println("HelloWorld started!"); } public String getMessage() { return "Hello World!"; } } Create a page home.xhtml under webapp folder. Update the code of home.xhtml as shown below. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>JSF Tutorial!</title> </head> <body> #{helloWorld.getMessage()} </body> </html> Following are the steps. Select helloworld project in eclipse Select helloworld project in eclipse Use Run As wizard Use Run As wizard Select Run As → Maven package Select Run As → Maven package Maven will start building the project and will create helloworld.war under C:\ → Projects → Data → WorkSpace → helloworld → target folder. Maven will start building the project and will create helloworld.war under C:\ → Projects → Data → WorkSpace → helloworld → target folder. [INFO] Scanning for projects... [INFO] ----------------------------------------------------- [INFO] Building helloworld Maven Webapp [INFO] [INFO] Id: com.tutorialspoint.test:helloworld:war:1.0-SNAPSHOT [INFO] task-segment: [package] [INFO] ----------------------------------------------------- [INFO] [resources:resources] [INFO] Using default encoding to copy filtered resources. [INFO] [compiler:compile] [INFO] Nothing to compile - all classes are up to date [INFO] [resources:testResources] [INFO] Using default encoding to copy filtered resources. [INFO] [compiler:testCompile] [INFO] No sources to compile [INFO] [surefire:test] [INFO] Surefire report directory: C:\Projects\Data\WorkSpace\helloworld\target\surefire-reports ------------------------------------------------------- T E S T S ------------------------------------------------------- There are no tests to run. Results : Tests run: 0, Failures: 0, Errors: 0, Skipped: 0 [INFO] [war:war] [INFO] Packaging webapp [INFO] Assembling webapp[helloworld] in [C:\Projects\Data\WorkSpace\helloworld\target\helloworld] [INFO] Processing war project [INFO] Webapp assembled in[150 msecs] [INFO] Building war: C:\Projects\Data\WorkSpace\helloworld\target\helloworld.war [INFO] ------------------------------------------------ [INFO] BUILD SUCCESSFUL [INFO] ------------------------------------------------ [INFO] Total time: 3 seconds [INFO] Finished at: Mon Nov 05 16:34:46 IST 2012 [INFO] Final Memory: 2M/15M [INFO] ------------------------------------------------ Following are the steps. Stop the tomcat server. Stop the tomcat server. Copy the helloworld.war file to tomcat installation directory → webapps folder. Copy the helloworld.war file to tomcat installation directory → webapps folder. Start the tomcat server. Start the tomcat server. Look inside webapps directory, there should be a folder helloworld got created. Look inside webapps directory, there should be a folder helloworld got created. Now helloworld.war is successfully deployed in Tomcat Webserver root. Now helloworld.war is successfully deployed in Tomcat Webserver root. Enter a url in web browser: http://localhost:8080/helloworld/home.jsf to launch the application. Server name (localhost) and port (8080) may vary as per your tomcat configuration. 37 Lectures 3.5 hours Chaand Sheikh Print Add Notes Bookmark this page
[ { "code": null, "e": 2124, "s": 1952, "text": "To create a simple JSF application, we'll use maven-archetype-webapp plugin. In the following example, we'll create a maven-based web application project in C:\\JSF folder." }, { "code": null, "e": 2218, "s": 2124, "text": "Let's open command console, go the C:\\ > JSF directory and execute the following mvn command." }, { "code": null, "e": 2363, "s": 2218, "text": "C:\\JSF>mvn archetype:create \n-DgroupId = com.tutorialspoint.test \n-DartifactId = helloworld \n-DarchetypeArtifactId = maven-archetype-webapp \n" }, { "code": null, "e": 2460, "s": 2363, "text": "Maven will start processing and will create the complete java web application project structure." }, { "code": null, "e": 4019, "s": 2460, "text": "[INFO] Scanning for projects... \n[INFO] Searching repository for plugin with prefix: 'archetype'. \n[INFO] ------------------------------------------------------------- \n[INFO] Building Maven Default Project \n[INFO] task-segment: [archetype:create] (aggregator-style) \n[INFO] ------------------------------------------------------------- \n[INFO] [archetype:create {execution: default-cli}] \n[INFO] Defaulting package to group ID: com.tutorialspoint.test \n[INFO] artifact org.apache.maven.archetypes:maven-archetype-webapp: \nchecking for updates from central \n[INFO] ------------------------------------------------------------- \n[INFO] Using following parameters for creating project \nfrom Old (1.x) Archetype: maven-archetype-webapp:RELEASE \n[INFO] ------------------------------------------------------------- \n[INFO] Parameter: groupId, Value: com.tutorialspoint.test \n[INFO] Parameter: packageName, Value: com.tutorialspoint.test \n[INFO] Parameter: package, Value: com.tutorialspoint.test \n[INFO] Parameter: artifactId, Value: helloworld \n[INFO] Parameter: basedir, Value: C:\\JSF \n[INFO] Parameter: version, Value: 1.0-SNAPSHOT \n[INFO] project created from Old (1.x) Archetype in dir: \nC:\\JSF\\helloworld \n[INFO] ------------------------------------------------------------- \n[INFO] BUILD SUCCESSFUL \n[INFO] ------------------------------------------------------------- \n[INFO] Total time: 7 seconds \n[INFO] Finished at: Mon Nov 05 16:05:04 IST 2012 \n[INFO] Final Memory: 12M/84M \n[INFO] ------------------------------------------------------------- \n" }, { "code": null, "e": 4222, "s": 4019, "text": "Now go to C:/JSF directory. You'll see a Java web application project created, named helloworld (as specified in artifactId). Maven uses a standard directory layout as shown in the following screenshot." }, { "code": null, "e": 4293, "s": 4222, "text": "Using the above example, we can understand the following key concepts." }, { "code": null, "e": 4304, "s": 4293, "text": "helloworld" }, { "code": null, "e": 4336, "s": 4304, "text": "Contains src folder and pom.xml" }, { "code": null, "e": 4352, "s": 4336, "text": "src/main/wepapp" }, { "code": null, "e": 4395, "s": 4352, "text": "Contains WEB-INF folder and index.jsp page" }, { "code": null, "e": 4414, "s": 4395, "text": "src/main/resources" }, { "code": null, "e": 4516, "s": 4414, "text": "It contains images/properties files (In the above example, we need to create this structure manually)" }, { "code": null, "e": 4552, "s": 4516, "text": "Add the following JSF dependencies." }, { "code": null, "e": 4874, "s": 4552, "text": "<dependencies>\n <dependency>\n <groupId>com.sun.faces</groupId>\n <artifactId>jsf-api</artifactId>\n <version>2.1.7</version>\n </dependency>\n\t\n <dependency>\n <groupId>com.sun.faces</groupId>\n <artifactId>jsf-impl</artifactId>\n <version>2.1.7</version>\n </dependency>\n\t\n</dependencies> " }, { "code": null, "e": 6337, "s": 4874, "text": "<project xmlns = \"http://maven.apache.org/POM/4.0.0\" \n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://maven.apache.org/POM/4.0.0\n http://maven.apache.org/maven-v4_0_0.xsd\">\n\t\n <modelVersion>4.0.0</modelVersion>\n <groupId>com.tutorialspoint.test</groupId>\n <artifactId>helloworld</artifactId>\n <packaging>war</packaging>\n <version>1.0-SNAPSHOT</version>\n <name>helloworld Maven Webapp</name>\n <url>http://maven.apache.org</url>\n\t\n <dependencies>\n <dependency>\n <groupId>junit</groupId>\n <artifactId>junit</artifactId>\n <version>3.8.1</version>\n <scope>test</scope>\n </dependency>\n\t\t\n <dependency>\n <groupId>com.sun.faces</groupId>\n <artifactId>jsf-api</artifactId>\n <version>2.1.7</version>\n </dependency>\n\t\t\n <dependency>\n <groupId>com.sun.faces</groupId>\n <artifactId>jsf-impl</artifactId>\n <version>2.1.7</version>\n </dependency>\n\t\t\n </dependencies>\n\t\n <build>\n <finalName>helloworld</finalName>\n <plugins>\n <plugin>\n <groupId>org.apache.maven.plugins</groupId>\n <artifactId>maven-compiler-plugin</artifactId>\n <version>2.3.1</version>\n\t\t\t\t\n <configuration>\n <source>1.6</source>\n <target>1.6</target>\n </configuration>\n </plugin>\n </plugins>\n \n </build>\t\t\n</project>" }, { "code": null, "e": 6448, "s": 6337, "text": "Let's open the command console. Go the C:\\ > JSF > helloworld directory and execute the following mvn command." }, { "code": null, "e": 6506, "s": 6448, "text": "C:\\JSF\\helloworld>mvn eclipse:eclipse -Dwtpversion = 2.0\n" }, { "code": null, "e": 6598, "s": 6506, "text": "Maven will start processing, create the eclipse ready project, and will add wtp capability." }, { "code": null, "e": 8535, "s": 6598, "text": "Downloading: http://repo.maven.apache.org/org/apache/maven/plugins/\nmaven-compiler-plugin/2.3.1/maven-compiler-plugin-2.3.1.pom\n5K downloaded (maven-compiler-plugin-2.3.1.pom)\nDownloading: http://repo.maven.apache.org/org/apache/maven/plugins/\nmaven-compiler-plugin/2.3.1/maven-compiler-plugin-2.3.1.jar\n29K downloaded (maven-compiler-plugin-2.3.1.jar)\n[INFO] Searching repository for plugin with prefix: 'eclipse'.\n[INFO] ------------------------------------------------------------\n[INFO] Building helloworld Maven Webapp\n[INFO] task-segment: [eclipse:eclipse]\n[INFO] ------------------------------------------------------------\n[INFO] Preparing eclipse:eclipse\n[INFO] No goals needed for project - skipping\n[INFO] [eclipse:eclipse {execution: default-cli}]\n[INFO] Adding support for WTP version 2.0.\n[INFO] Using Eclipse Workspace: null\n[INFO] Adding default classpath container: org.eclipse.jdt.\nlaunching.JRE_CONTAINER\nDownloading: http://repo.maven.apache.org/\ncom/sun/faces/jsf-api/2.1.7/jsf-api-2.1.7.pom\n12K downloaded (jsf-api-2.1.7.pom)\nDownloading: http://repo.maven.apache.org/\ncom/sun/faces/jsf-impl/2.1.7/jsf-impl-2.1.7.pom\n10K downloaded (jsf-impl-2.1.7.pom)\nDownloading: http://repo.maven.apache.org/\ncom/sun/faces/jsf-api/2.1.7/jsf-api-2.1.7.jar\n619K downloaded (jsf-api-2.1.7.jar)\nDownloading: http://repo.maven.apache.org/\ncom/sun/faces/jsf-impl/2.1.7/jsf-impl-2.1.7.jar\n1916K downloaded (jsf-impl-2.1.7.jar)\n[INFO] Wrote settings to C:\\JSF\\helloworld\\.settings\\\norg.eclipse.jdt.core.prefs\n[INFO] Wrote Eclipse project for \"helloworld\" to C:\\JSF\\helloworld.\n[INFO]\n[INFO] -----------------------------------------------------------\n[INFO] BUILD SUCCESSFUL\n[INFO] -----------------------------------------------------------\n[INFO] Total time: 6 minutes 7 seconds\n[INFO] Finished at: Mon Nov 05 16:16:25 IST 2012\n[INFO] Final Memory: 10M/89M\n[INFO] -----------------------------------------------------------\n" }, { "code": null, "e": 8561, "s": 8535, "text": "Following are the steps −" }, { "code": null, "e": 8608, "s": 8561, "text": "Import project in eclipse using Import wizard." }, { "code": null, "e": 8655, "s": 8608, "text": "Import project in eclipse using Import wizard." }, { "code": null, "e": 8713, "s": 8655, "text": "Go to File → Import... → Existing project into workspace." }, { "code": null, "e": 8771, "s": 8713, "text": "Go to File → Import... → Existing project into workspace." }, { "code": null, "e": 8808, "s": 8771, "text": "Select root directory to helloworld." }, { "code": null, "e": 8845, "s": 8808, "text": "Select root directory to helloworld." }, { "code": null, "e": 8894, "s": 8845, "text": "Keep Copy projects into workspace to be checked." }, { "code": null, "e": 8943, "s": 8894, "text": "Keep Copy projects into workspace to be checked." }, { "code": null, "e": 8964, "s": 8943, "text": "Click Finish button." }, { "code": null, "e": 8985, "s": 8964, "text": "Click Finish button." }, { "code": null, "e": 9078, "s": 8985, "text": "Eclipse will import and copy the project in its workspace C:\\ → Projects → Data → WorkSpace." }, { "code": null, "e": 9171, "s": 9078, "text": "Eclipse will import and copy the project in its workspace C:\\ → Projects → Data → WorkSpace." }, { "code": null, "e": 9243, "s": 9171, "text": "Locate web.xml in webapp → WEB-INF folder and update it as shown below." }, { "code": null, "e": 10663, "s": 9243, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<web-app xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xmlns = \"http://java.sun.com/xml/ns/javaee\" \n xmlns:web = \"http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd\"\n xsi:schemaLocation = \"http://java.sun.com/xml/ns/javaee \n http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd\"\n id = \"WebApp_ID\" version=\"2.5\">\n\t\n <welcome-file-list>\n <welcome-file>faces/home.xhtml</welcome-file>\n </welcome-file-list>\n\t\n <!-- \n FacesServlet is main servlet responsible to handle all request. \n It acts as central controller.\n This servlet initializes the JSF components before the JSP is displayed.\n -->\n\t\n <servlet>\n <servlet-name>Faces Servlet</servlet-name>\n <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>\n <load-on-startup>1</load-on-startup>\n </servlet>\n\t\n <servlet-mapping>\n <servlet-name>Faces Servlet</servlet-name>\n <url-pattern>/faces/*</url-pattern>\n </servlet-mapping>\n\t\n <servlet-mapping>\n <servlet-name>Faces Servlet</servlet-name>\n <url-pattern>*.jsf</url-pattern>\n </servlet-mapping>\n\t\n <servlet-mapping>\n <servlet-name>Faces Servlet</servlet-name>\n <url-pattern>*.faces</url-pattern>\n </servlet-mapping>\n\t\n <servlet-mapping>\n <servlet-name>Faces Servlet</servlet-name>\n <url-pattern>*.xhtml</url-pattern>\n </servlet-mapping>\n\t\n</web-app>" }, { "code": null, "e": 10843, "s": 10663, "text": "Create a package structure under src → main → java as com → tutorialspoint → test. Create HelloWorld.java class in this package. Update the code of HelloWorld.java as shown below." }, { "code": null, "e": 11142, "s": 10843, "text": "package com.tutorialspoint.test;\n\nimport javax.faces.bean.ManagedBean;\n\n@ManagedBean(name = \"helloWorld\", eager = true)\npublic class HelloWorld {\n \n public HelloWorld() {\n System.out.println(\"HelloWorld started!\");\n }\n\t\n public String getMessage() {\n return \"Hello World!\";\n }\n}" }, { "code": null, "e": 11234, "s": 11142, "text": "Create a page home.xhtml under webapp folder. Update the code of home.xhtml as shown below." }, { "code": null, "e": 11525, "s": 11234, "text": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n\n<html xmlns = \"http://www.w3.org/1999/xhtml\">\n <head>\n <title>JSF Tutorial!</title>\n </head>\n\n <body>\n #{helloWorld.getMessage()}\n </body>\n</html>" }, { "code": null, "e": 11550, "s": 11525, "text": "Following are the steps." }, { "code": null, "e": 11587, "s": 11550, "text": "Select helloworld project in eclipse" }, { "code": null, "e": 11624, "s": 11587, "text": "Select helloworld project in eclipse" }, { "code": null, "e": 11642, "s": 11624, "text": "Use Run As wizard" }, { "code": null, "e": 11660, "s": 11642, "text": "Use Run As wizard" }, { "code": null, "e": 11690, "s": 11660, "text": "Select Run As → Maven package" }, { "code": null, "e": 11720, "s": 11690, "text": "Select Run As → Maven package" }, { "code": null, "e": 11859, "s": 11720, "text": "Maven will start building the project and will create helloworld.war under C:\\ → Projects → Data → WorkSpace → helloworld → target folder." }, { "code": null, "e": 11998, "s": 11859, "text": "Maven will start building the project and will create helloworld.war under C:\\ → Projects → Data → WorkSpace → helloworld → target folder." }, { "code": null, "e": 13533, "s": 11998, "text": "[INFO] Scanning for projects...\n[INFO] -----------------------------------------------------\n[INFO] Building helloworld Maven Webapp\n[INFO] \n[INFO] Id: com.tutorialspoint.test:helloworld:war:1.0-SNAPSHOT\n[INFO] task-segment: [package]\n[INFO] -----------------------------------------------------\n[INFO] [resources:resources]\n[INFO] Using default encoding to copy filtered resources.\n[INFO] [compiler:compile]\n[INFO] Nothing to compile - all classes are up to date\n[INFO] [resources:testResources]\n[INFO] Using default encoding to copy filtered resources.\n[INFO] [compiler:testCompile]\n[INFO] No sources to compile\n[INFO] [surefire:test]\n[INFO] Surefire report directory: \nC:\\Projects\\Data\\WorkSpace\\helloworld\\target\\surefire-reports\n\n-------------------------------------------------------\n T E S T S\n-------------------------------------------------------\nThere are no tests to run.\n\nResults :\n\nTests run: 0, Failures: 0, Errors: 0, Skipped: 0\n\n[INFO] [war:war]\n[INFO] Packaging webapp\n[INFO] Assembling webapp[helloworld] in\n[C:\\Projects\\Data\\WorkSpace\\helloworld\\target\\helloworld]\n[INFO] Processing war project\n[INFO] Webapp assembled in[150 msecs]\n[INFO] Building war: \nC:\\Projects\\Data\\WorkSpace\\helloworld\\target\\helloworld.war\n[INFO] ------------------------------------------------\n[INFO] BUILD SUCCESSFUL\n[INFO] ------------------------------------------------\n[INFO] Total time: 3 seconds\n[INFO] Finished at: Mon Nov 05 16:34:46 IST 2012\n[INFO] Final Memory: 2M/15M\n[INFO] ------------------------------------------------\n" }, { "code": null, "e": 13558, "s": 13533, "text": "Following are the steps." }, { "code": null, "e": 13582, "s": 13558, "text": "Stop the tomcat server." }, { "code": null, "e": 13606, "s": 13582, "text": "Stop the tomcat server." }, { "code": null, "e": 13686, "s": 13606, "text": "Copy the helloworld.war file to tomcat installation directory → webapps folder." }, { "code": null, "e": 13766, "s": 13686, "text": "Copy the helloworld.war file to tomcat installation directory → webapps folder." }, { "code": null, "e": 13791, "s": 13766, "text": "Start the tomcat server." }, { "code": null, "e": 13816, "s": 13791, "text": "Start the tomcat server." }, { "code": null, "e": 13896, "s": 13816, "text": "Look inside webapps directory, there should be a folder helloworld got created." }, { "code": null, "e": 13976, "s": 13896, "text": "Look inside webapps directory, there should be a folder helloworld got created." }, { "code": null, "e": 14046, "s": 13976, "text": "Now helloworld.war is successfully deployed in Tomcat Webserver root." }, { "code": null, "e": 14116, "s": 14046, "text": "Now helloworld.war is successfully deployed in Tomcat Webserver root." }, { "code": null, "e": 14213, "s": 14116, "text": "Enter a url in web browser: http://localhost:8080/helloworld/home.jsf to launch the application." }, { "code": null, "e": 14296, "s": 14213, "text": "Server name (localhost) and port (8080) may vary as per your tomcat configuration." }, { "code": null, "e": 14331, "s": 14296, "text": "\n 37 Lectures \n 3.5 hours \n" }, { "code": null, "e": 14346, "s": 14331, "text": " Chaand Sheikh" }, { "code": null, "e": 14353, "s": 14346, "text": " Print" }, { "code": null, "e": 14364, "s": 14353, "text": " Add Notes" } ]
MySQL Stored Procedure calling with INT and VARCHAR values
To call a stored procedure, you can use CALL command. Following is the syntax − CALL yourStoredProcedureName(parameter if any); Let us first create a sample procedure. Following is the query to create a stored procedure. Here, we have set two values, one is an INT and another VARCHAR − mysql> DELIMITER // mysql> CREATE PROCEDURE CALL_PROC(Id int,Name varchar(40)) BEGIN SELECT CONCAT('You have entered the Id which is=',Id); SELECT CONCAT('You have entered the Name which is=',Name); END // Query OK, 0 rows affected (0.21 sec) mysql> DELIMITER ; Following is the query to call a stored procedure in MySQL − mysql> CALL CALL_PROC(1001,'Chris'); This will produce the following output − +------------------------------------------------+ | CONCAT('You have entered the Id which is=',Id) | +------------------------------------------------+ | You have entered the Id which is=1001 | +------------------------------------------------+ 1 row in set (0.00 sec) +----------------------------------------------------+ | CONCAT('You have entered the Name which is=',Name) | +----------------------------------------------------+ | You have entered the Name which is=Chris | +----------------------------------------------------+ 1 row in set (0.02 sec) Query OK, 0 rows affected, 1 warning (0.04 sec)
[ { "code": null, "e": 1142, "s": 1062, "text": "To call a stored procedure, you can use CALL command. Following is the syntax −" }, { "code": null, "e": 1190, "s": 1142, "text": "CALL yourStoredProcedureName(parameter if any);" }, { "code": null, "e": 1349, "s": 1190, "text": "Let us first create a sample procedure. Following is the query to create a stored procedure. Here, we have set two values, one is an INT and another VARCHAR −" }, { "code": null, "e": 1623, "s": 1349, "text": "mysql> DELIMITER //\nmysql> CREATE PROCEDURE CALL_PROC(Id int,Name varchar(40))\n BEGIN\n SELECT CONCAT('You have entered the Id which is=',Id);\n SELECT CONCAT('You have entered the Name which is=',Name);\n END\n//\nQuery OK, 0 rows affected (0.21 sec)\nmysql> DELIMITER ;" }, { "code": null, "e": 1684, "s": 1623, "text": "Following is the query to call a stored procedure in MySQL −" }, { "code": null, "e": 1721, "s": 1684, "text": "mysql> CALL CALL_PROC(1001,'Chris');" }, { "code": null, "e": 1762, "s": 1721, "text": "This will produce the following output −" }, { "code": null, "e": 2388, "s": 1762, "text": "+------------------------------------------------+\n| CONCAT('You have entered the Id which is=',Id) |\n+------------------------------------------------+\n| You have entered the Id which is=1001 |\n+------------------------------------------------+\n1 row in set (0.00 sec)\n+----------------------------------------------------+\n| CONCAT('You have entered the Name which is=',Name) |\n+----------------------------------------------------+\n| You have entered the Name which is=Chris |\n+----------------------------------------------------+\n1 row in set (0.02 sec)\nQuery OK, 0 rows affected, 1 warning (0.04 sec)" } ]
Breadth First Search without using Queue - GeeksforGeeks
05 May, 2022 Breadth-first search is a graph traversal algorithm which traverse a graph or tree level by level. In this article, BFS for a Graph is implemented using Adjacency list without using a Queue.Examples: Input: Output: BFS traversal = 2, 0, 3, 1 Explanation: In the following graph, we start traversal from vertex 2. When we come to vertex 0, we look for all adjacent vertices of it. 2 is also an adjacent vertex of 0. If we don’t mark visited vertices, then 2 will be processed again and it will become a non-terminating process. Therefore, a Breadth-First Traversal of the following graph is 2, 0, 3, 1. Approach: This problem can be solved using simple breadth-first traversal from a given source. The implementation uses adjacency list representation of graphs. Here: STL Vector container is used to store lists of adjacent nodes and queue of nodes needed for BFS traversal. A DP array is used to store the distance of the nodes from the source. Every time we move from a node to another node, the distance increases by 1. If the distance to reach the nodes becomes smaller than the previous distance, we update the value stored in the DP[node]. Below is the implementation of the above approach: CPP Python3 // C++ implementation to demonstrate// the above mentioned approach #include <bits/stdc++.h>using namespace std; // Function to find the distance// from the source to other nodesvoid BFS(int curr, int N, vector<bool>& vis, vector<int>& dp, vector<int>& v, vector<vector<int> >& adj){ while (curr <= N) { // Current node int node = v[curr - 1]; cout << node << ", "; for (int i = 0; i < adj[node].size(); i++) { // Adjacent node int next = adj[node][i]; if ((!vis[next]) && (dp[next] < dp[node] + 1)) { // Stores the adjacent node v.push_back(next); // Increases the distance dp[next] = dp[node] + 1; // Mark it as visited vis[next] = true; } } curr += 1; }} // Function to print the distance// from source to other nodesvoid bfsTraversal( vector<vector<int> >& adj, int N, int source){ // Initially mark all nodes as false vector<bool> vis(N + 1, false); // Initialize distance array with 0 vector<int> dp(N + 1, 0), v; v.push_back(source); // Initially mark the starting // source as 0 and visited as true dp = 0; vis = true; // Call the BFS function BFS(1, N, vis, dp, v, adj);} // Driver codeint main(){ // No. of nodes in graph int N = 4; // Creating adjacency list // for representing graph vector<vector<int> > adj(N + 1); adj[0].push_back(1); adj[0].push_back(2); adj[1].push_back(2); adj[2].push_back(0); adj[2].push_back(3); adj[3].push_back(3); // Following is BFS Traversal // starting from vertex 2 bfsTraversal(adj, N, 2); return 0;} # C++ implementation to demonstrate# the above mentioned approachfrom queue import Queue # Function to find the distance# from the source to other nodesdef BFS(curr, N, vis, dp, v, adj): while (curr <= N) : # Current node node = v[curr - 1] print(node,end= ", ") for i in range(len(adj[node])) : # Adjacent node next = adj[node][i] if ((not vis[next]) and (dp[next] < dp[node] + 1)) : # Stores the adjacent node v.append(next) # Increases the distance dp[next] = dp[node] + 1 # Mark it as visited vis[next] = True curr += 1 # Function to print the distance# from source to other nodesdef bfsTraversal(adj, N, source): # Initially mark all nodes as false vis=[False]*(N + 1) # Initialize distance array with 0 dp=[0]*(N + 1); v=[] v.append(source) # Initially mark the starting # source as 0 and visited as true dp = 0 vis = True # Call the BFS function BFS(1, N, vis, dp, v, adj) # Driver codeif __name__ == '__main__': # No. of nodes in graph N = 4 # Creating adjacency list # for representing graph adj=[[] for _ in range(N+1)] adj[0].append(1) adj[0].append(2) adj[1].append(2) adj[2].append(0) adj[2].append(3) adj[3].append(3) # Following is BFS Traversal # starting from vertex 2 bfsTraversal(adj, N, 2) 2, 0, 3, 1, Time Complexity: O(V + E), where V is the number of vertices and E is the number of edges.Auxiliary Space: O(V) pankajsharmagfg amartyaghoshgfg adnanirshad158 harendrakumar123 BFS cpp-vector Algorithms Competitive Programming Graph Tree Graph Tree BFS Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. SDE SHEET - A Complete Guide for SDE Preparation DSA Sheet by Love Babbar How to Start Learning DSA? Introduction to Algorithms Difference between NP hard and NP complete problem Competitive Programming - A Complete Guide Practice for cracking any coding interview Arrow operator -> in C/C++ with Examples Prefix Sum Array - Implementation and Applications in Competitive Programming Top 10 Algorithms and Data Structures for Competitive Programming
[ { "code": null, "e": 26379, "s": 26351, "text": "\n05 May, 2022" }, { "code": null, "e": 26580, "s": 26379, "text": "Breadth-first search is a graph traversal algorithm which traverse a graph or tree level by level. In this article, BFS for a Graph is implemented using Adjacency list without using a Queue.Examples: " }, { "code": null, "e": 26588, "s": 26580, "text": "Input: " }, { "code": null, "e": 26985, "s": 26588, "text": "Output: BFS traversal = 2, 0, 3, 1 Explanation: In the following graph, we start traversal from vertex 2. When we come to vertex 0, we look for all adjacent vertices of it. 2 is also an adjacent vertex of 0. If we don’t mark visited vertices, then 2 will be processed again and it will become a non-terminating process. Therefore, a Breadth-First Traversal of the following graph is 2, 0, 3, 1. " }, { "code": null, "e": 27153, "s": 26985, "text": "Approach: This problem can be solved using simple breadth-first traversal from a given source. The implementation uses adjacency list representation of graphs. Here: " }, { "code": null, "e": 27262, "s": 27153, "text": "STL Vector container is used to store lists of adjacent nodes and queue of nodes needed for BFS traversal. " }, { "code": null, "e": 27533, "s": 27262, "text": "A DP array is used to store the distance of the nodes from the source. Every time we move from a node to another node, the distance increases by 1. If the distance to reach the nodes becomes smaller than the previous distance, we update the value stored in the DP[node]." }, { "code": null, "e": 27584, "s": 27533, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 27588, "s": 27584, "text": "CPP" }, { "code": null, "e": 27596, "s": 27588, "text": "Python3" }, { "code": "// C++ implementation to demonstrate// the above mentioned approach #include <bits/stdc++.h>using namespace std; // Function to find the distance// from the source to other nodesvoid BFS(int curr, int N, vector<bool>& vis, vector<int>& dp, vector<int>& v, vector<vector<int> >& adj){ while (curr <= N) { // Current node int node = v[curr - 1]; cout << node << \", \"; for (int i = 0; i < adj[node].size(); i++) { // Adjacent node int next = adj[node][i]; if ((!vis[next]) && (dp[next] < dp[node] + 1)) { // Stores the adjacent node v.push_back(next); // Increases the distance dp[next] = dp[node] + 1; // Mark it as visited vis[next] = true; } } curr += 1; }} // Function to print the distance// from source to other nodesvoid bfsTraversal( vector<vector<int> >& adj, int N, int source){ // Initially mark all nodes as false vector<bool> vis(N + 1, false); // Initialize distance array with 0 vector<int> dp(N + 1, 0), v; v.push_back(source); // Initially mark the starting // source as 0 and visited as true dp = 0; vis = true; // Call the BFS function BFS(1, N, vis, dp, v, adj);} // Driver codeint main(){ // No. of nodes in graph int N = 4; // Creating adjacency list // for representing graph vector<vector<int> > adj(N + 1); adj[0].push_back(1); adj[0].push_back(2); adj[1].push_back(2); adj[2].push_back(0); adj[2].push_back(3); adj[3].push_back(3); // Following is BFS Traversal // starting from vertex 2 bfsTraversal(adj, N, 2); return 0;}", "e": 29355, "s": 27596, "text": null }, { "code": "# C++ implementation to demonstrate# the above mentioned approachfrom queue import Queue # Function to find the distance# from the source to other nodesdef BFS(curr, N, vis, dp, v, adj): while (curr <= N) : # Current node node = v[curr - 1] print(node,end= \", \") for i in range(len(adj[node])) : # Adjacent node next = adj[node][i] if ((not vis[next]) and (dp[next] < dp[node] + 1)) : # Stores the adjacent node v.append(next) # Increases the distance dp[next] = dp[node] + 1 # Mark it as visited vis[next] = True curr += 1 # Function to print the distance# from source to other nodesdef bfsTraversal(adj, N, source): # Initially mark all nodes as false vis=[False]*(N + 1) # Initialize distance array with 0 dp=[0]*(N + 1); v=[] v.append(source) # Initially mark the starting # source as 0 and visited as true dp = 0 vis = True # Call the BFS function BFS(1, N, vis, dp, v, adj) # Driver codeif __name__ == '__main__': # No. of nodes in graph N = 4 # Creating adjacency list # for representing graph adj=[[] for _ in range(N+1)] adj[0].append(1) adj[0].append(2) adj[1].append(2) adj[2].append(0) adj[2].append(3) adj[3].append(3) # Following is BFS Traversal # starting from vertex 2 bfsTraversal(adj, N, 2)", "e": 30858, "s": 29355, "text": null }, { "code": null, "e": 30871, "s": 30858, "text": "2, 0, 3, 1, " }, { "code": null, "e": 30983, "s": 30871, "text": "Time Complexity: O(V + E), where V is the number of vertices and E is the number of edges.Auxiliary Space: O(V)" }, { "code": null, "e": 30999, "s": 30983, "text": "pankajsharmagfg" }, { "code": null, "e": 31015, "s": 30999, "text": "amartyaghoshgfg" }, { "code": null, "e": 31030, "s": 31015, "text": "adnanirshad158" }, { "code": null, "e": 31047, "s": 31030, "text": "harendrakumar123" }, { "code": null, "e": 31051, "s": 31047, "text": "BFS" }, { "code": null, "e": 31062, "s": 31051, "text": "cpp-vector" }, { "code": null, "e": 31073, "s": 31062, "text": "Algorithms" }, { "code": null, "e": 31097, "s": 31073, "text": "Competitive Programming" }, { "code": null, "e": 31103, "s": 31097, "text": "Graph" }, { "code": null, "e": 31108, "s": 31103, "text": "Tree" }, { "code": null, "e": 31114, "s": 31108, "text": "Graph" }, { "code": null, "e": 31119, "s": 31114, "text": "Tree" }, { "code": null, "e": 31123, "s": 31119, "text": "BFS" }, { "code": null, "e": 31134, "s": 31123, "text": "Algorithms" }, { "code": null, "e": 31232, "s": 31134, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31281, "s": 31232, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 31306, "s": 31281, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 31333, "s": 31306, "text": "How to Start Learning DSA?" }, { "code": null, "e": 31360, "s": 31333, "text": "Introduction to Algorithms" }, { "code": null, "e": 31411, "s": 31360, "text": "Difference between NP hard and NP complete problem" }, { "code": null, "e": 31454, "s": 31411, "text": "Competitive Programming - A Complete Guide" }, { "code": null, "e": 31497, "s": 31454, "text": "Practice for cracking any coding interview" }, { "code": null, "e": 31538, "s": 31497, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 31616, "s": 31538, "text": "Prefix Sum Array - Implementation and Applications in Competitive Programming" } ]
How to select element with specific class and title attribute using jQuery?
If your element is having a class and title attribute, still you can select it with jQuery. You can try to run the following code to learn how to select element with specific class and 'title' attribute using jQuery. Live Demo <html> <head> <title>The Selector Example</title> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script> $(document).ready(function() { $(".big[title='one']").css("background-color", "yellow"); }); </script> </head> <body> <div class = "big" title="one"> <p>This is first division of the DOM.</p> </div> <div class = "medium"> <p>This is second division of the DOM.</p> </div> </body> </html>
[ { "code": null, "e": 1279, "s": 1062, "text": "If your element is having a class and title attribute, still you can select it with jQuery. You can try to run the following code to learn how to select element with specific class and 'title' attribute using jQuery." }, { "code": null, "e": 1289, "s": 1279, "text": "Live Demo" }, { "code": null, "e": 1860, "s": 1289, "text": "<html>\n\n <head>\n <title>The Selector Example</title>\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\"></script>\n \n <script>\n $(document).ready(function() {\n\n $(\".big[title='one']\").css(\"background-color\", \"yellow\");\n });\n </script>\n \n </head>\n \n <body>\n\n <div class = \"big\" title=\"one\">\n <p>This is first division of the DOM.</p>\n </div>\n <div class = \"medium\">\n <p>This is second division of the DOM.</p>\n </div>\n\n </body>\n \n</html>" } ]
Angular PrimeNG Sidebar Component - GeeksforGeeks
07 Oct, 2021 Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will know how to use the Sidebar component in Angular PrimeNG. We will also learn about the properties, events & styling along with their syntaxes that will be used in the code. Sidebar component: It is used to make an element that overlays at the edges of the screen. Properties: visible: It specifies the visibility of the dialog. It is of the boolean data type, the default value is false. position: It specifies the position of the sidebar, valid values are “left”, “right”, “bottom” and “top”. It is of string data type & the default value is left. fullScreen: It is used to add a close icon to the header to hide the dialog. It is of boolean data type & the default value is false. appendTo: It is the target element to attach the dialog, valid values are “body” or a local ng-template variable of another element. It accepts any type of data & the default value is null. style: It is used to set the inline style of the component. It is of string data type & the default value is null. styleClass: It is used to set the style class of the component. It is of string data type & the default value is null. blockScroll: It is used to specify whether to block scrolling of the document when the sidebar is active. It is of boolean data type & the default value is false. baseZIndex: It is used to set the base zIndex value to use in layering. It is of number data type & the default value is 0. autoZIndex: It is used to specify whether to automatically manage the layering. It is of the boolean data type, the default value is true. modal: It is used to specify whether an overlay mask is displayed behind the sidebar. It is of the boolean data type, the default value is true. dismissible: It is used to specify whether to dismiss the sidebar on click of the mask. It is of the boolean data type, the default value is true. showCloseIcon: It is used to specify whether to display the close icon. It is of the boolean datatype, the default value is true. transitionOptions: It is used to set the transition options of the animation. It is of string data type & the default value is 150ms cubic-bezier(0, 0, 0.2, 1). ariaCloseLabel: It is used to set the aria-label of the close icon. It is of string data type & the default value is close. closeOnEscape: It is used to specify if pressing the escape key should hide the sidebar. It is of the boolean data type, the default value is true. Events: onShow: It is a callback that is fired when a dialog is shown. onHide: It is a callback that is fired when a dialog is hidden. Styling: p-sidebar: It is the container element p-sidebar-left: It is the container element of the left sidebar. p-sidebar-right: It is the container element of the right sidebar. p-sidebar-top: It is the container element of the top sidebar. p-sidebar-bottom: It is the container element of the bottom sidebar. p-sidebar-full: It is the container element of a full-screen sidebar. p-sidebar-active: It is the container element when the sidebar is visible. p-sidebar-close: It is the close anchor element. p-sidebar-sm: It is a small-sized sidebar. p-sidebar-md: It is the medium-sized sidebar. p-sidebar-lg: It is a large-sized sidebar. p-sidebar-mask: It is the modal layer of the sidebar. Creating Angular application & module installation: Step 1: Create an Angular application using the following command. ng new appname Step 2: After creating your project folder i.e. appname, move to it using the following command. cd appname Step 3: Install PrimeNG in your given directory. npm install primeng --save npm install primeicons --save Project Structure: It will look like the following: Example 1: This is the basic example that illustrates how to use the Sidebar component. app.component.html <p-sidebar [(visible)]="gfg" [baseZIndex]="10000"> <h1 style="font-weight: normal">GeeksforGeeks</h1> <p>Angular PrimeNG Sidebar Component</p> <p-button type="button" (click)="gfg = false" label="OK" styleClass="p-button-info"> </p-button> <p-button type="button" (click)="gfg = false" label="Cancel" styleClass="p-button-danger"> </p-button></p-sidebar><p-button (click)="gfg = true" label="Click Here!"></p-button> app.component.ts import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: ['./app.component.scss']})export class AppComponent {} app.module.ts import { NgModule } from "@angular/core";import { BrowserModule } from "@angular/platform-browser";import { BrowserAnimationsModule } from "@angular/platform-browser/animations"; import { AppComponent } from "./app.component";import { ButtonModule } from "primeng/button";import { SidebarModule } from "primeng/sidebar"; @NgModule({ imports: [ BrowserModule, BrowserAnimationsModule, SidebarModule, ButtonModule, ], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {} Output: Example 2: In this example, we will know how to use the position property in the Sidebar component. app.component.html <p-sidebar [(visible)]="gfg" [baseZIndex]="10000" position="right"> <h1 style="font-weight: normal">GeeksforGeeks</h1> <p>Angular PrimeNG Sidebar Component</p> <p-button type="button" (click)="gfg = false" label="OK" styleClass="p-button-info"> </p-button> <p-button type="button" (click)="gfg = false" label="Cancel" styleClass="p-button-danger"> </p-button></p-sidebar><p-button (click)="gfg = true" label="Click Here!"></p-button> app.component.ts import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: ['./app.component.scss']})export class AppComponent {} app.module.ts import { NgModule } from "@angular/core";import { BrowserModule } from "@angular/platform-browser";import { BrowserAnimationsModule } from "@angular/platform-browser/animations"; import { AppComponent } from "./app.component";import { ButtonModule } from "primeng/button";import { SidebarModule } from "primeng/sidebar"; @NgModule({ imports: [ BrowserModule, BrowserAnimationsModule, SidebarModule, ButtonModule, ], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {} Output: Reference: https://primefaces.org/primeng/showcase/#/sidebar Angular-PrimeNG AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Angular PrimeNG Dropdown Component Angular PrimeNG Calendar Component Angular 10 (blur) Event Angular PrimeNG Messages Component How to make a Bootstrap Modal Popup in Angular 9/8 ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 26354, "s": 26326, "text": "\n07 Oct, 2021" }, { "code": null, "e": 26753, "s": 26354, "text": "Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will know how to use the Sidebar component in Angular PrimeNG. We will also learn about the properties, events & styling along with their syntaxes that will be used in the code. " }, { "code": null, "e": 26844, "s": 26753, "text": "Sidebar component: It is used to make an element that overlays at the edges of the screen." }, { "code": null, "e": 26856, "s": 26844, "text": "Properties:" }, { "code": null, "e": 26968, "s": 26856, "text": "visible: It specifies the visibility of the dialog. It is of the boolean data type, the default value is false." }, { "code": null, "e": 27129, "s": 26968, "text": "position: It specifies the position of the sidebar, valid values are “left”, “right”, “bottom” and “top”. It is of string data type & the default value is left." }, { "code": null, "e": 27263, "s": 27129, "text": "fullScreen: It is used to add a close icon to the header to hide the dialog. It is of boolean data type & the default value is false." }, { "code": null, "e": 27453, "s": 27263, "text": "appendTo: It is the target element to attach the dialog, valid values are “body” or a local ng-template variable of another element. It accepts any type of data & the default value is null." }, { "code": null, "e": 27568, "s": 27453, "text": "style: It is used to set the inline style of the component. It is of string data type & the default value is null." }, { "code": null, "e": 27687, "s": 27568, "text": "styleClass: It is used to set the style class of the component. It is of string data type & the default value is null." }, { "code": null, "e": 27850, "s": 27687, "text": "blockScroll: It is used to specify whether to block scrolling of the document when the sidebar is active. It is of boolean data type & the default value is false." }, { "code": null, "e": 27974, "s": 27850, "text": "baseZIndex: It is used to set the base zIndex value to use in layering. It is of number data type & the default value is 0." }, { "code": null, "e": 28113, "s": 27974, "text": "autoZIndex: It is used to specify whether to automatically manage the layering. It is of the boolean data type, the default value is true." }, { "code": null, "e": 28258, "s": 28113, "text": "modal: It is used to specify whether an overlay mask is displayed behind the sidebar. It is of the boolean data type, the default value is true." }, { "code": null, "e": 28405, "s": 28258, "text": "dismissible: It is used to specify whether to dismiss the sidebar on click of the mask. It is of the boolean data type, the default value is true." }, { "code": null, "e": 28535, "s": 28405, "text": "showCloseIcon: It is used to specify whether to display the close icon. It is of the boolean datatype, the default value is true." }, { "code": null, "e": 28696, "s": 28535, "text": "transitionOptions: It is used to set the transition options of the animation. It is of string data type & the default value is 150ms cubic-bezier(0, 0, 0.2, 1)." }, { "code": null, "e": 28820, "s": 28696, "text": "ariaCloseLabel: It is used to set the aria-label of the close icon. It is of string data type & the default value is close." }, { "code": null, "e": 28968, "s": 28820, "text": "closeOnEscape: It is used to specify if pressing the escape key should hide the sidebar. It is of the boolean data type, the default value is true." }, { "code": null, "e": 28976, "s": 28968, "text": "Events:" }, { "code": null, "e": 29039, "s": 28976, "text": "onShow: It is a callback that is fired when a dialog is shown." }, { "code": null, "e": 29103, "s": 29039, "text": "onHide: It is a callback that is fired when a dialog is hidden." }, { "code": null, "e": 29114, "s": 29105, "text": "Styling:" }, { "code": null, "e": 29153, "s": 29114, "text": "p-sidebar: It is the container element" }, { "code": null, "e": 29218, "s": 29153, "text": "p-sidebar-left: It is the container element of the left sidebar." }, { "code": null, "e": 29285, "s": 29218, "text": "p-sidebar-right: It is the container element of the right sidebar." }, { "code": null, "e": 29348, "s": 29285, "text": "p-sidebar-top: It is the container element of the top sidebar." }, { "code": null, "e": 29417, "s": 29348, "text": "p-sidebar-bottom: It is the container element of the bottom sidebar." }, { "code": null, "e": 29487, "s": 29417, "text": "p-sidebar-full: It is the container element of a full-screen sidebar." }, { "code": null, "e": 29562, "s": 29487, "text": "p-sidebar-active: It is the container element when the sidebar is visible." }, { "code": null, "e": 29611, "s": 29562, "text": "p-sidebar-close: It is the close anchor element." }, { "code": null, "e": 29654, "s": 29611, "text": "p-sidebar-sm: It is a small-sized sidebar." }, { "code": null, "e": 29700, "s": 29654, "text": "p-sidebar-md: It is the medium-sized sidebar." }, { "code": null, "e": 29743, "s": 29700, "text": "p-sidebar-lg: It is a large-sized sidebar." }, { "code": null, "e": 29797, "s": 29743, "text": "p-sidebar-mask: It is the modal layer of the sidebar." }, { "code": null, "e": 29849, "s": 29797, "text": "Creating Angular application & module installation:" }, { "code": null, "e": 29916, "s": 29849, "text": "Step 1: Create an Angular application using the following command." }, { "code": null, "e": 29931, "s": 29916, "text": "ng new appname" }, { "code": null, "e": 30028, "s": 29931, "text": "Step 2: After creating your project folder i.e. appname, move to it using the following command." }, { "code": null, "e": 30039, "s": 30028, "text": "cd appname" }, { "code": null, "e": 30088, "s": 30039, "text": "Step 3: Install PrimeNG in your given directory." }, { "code": null, "e": 30145, "s": 30088, "text": "npm install primeng --save\nnpm install primeicons --save" }, { "code": null, "e": 30197, "s": 30145, "text": "Project Structure: It will look like the following:" }, { "code": null, "e": 30286, "s": 30197, "text": "Example 1: This is the basic example that illustrates how to use the Sidebar component. " }, { "code": null, "e": 30305, "s": 30286, "text": "app.component.html" }, { "code": "<p-sidebar [(visible)]=\"gfg\" [baseZIndex]=\"10000\"> <h1 style=\"font-weight: normal\">GeeksforGeeks</h1> <p>Angular PrimeNG Sidebar Component</p> <p-button type=\"button\" (click)=\"gfg = false\" label=\"OK\" styleClass=\"p-button-info\"> </p-button> <p-button type=\"button\" (click)=\"gfg = false\" label=\"Cancel\" styleClass=\"p-button-danger\"> </p-button></p-sidebar><p-button (click)=\"gfg = true\" label=\"Click Here!\"></p-button>", "e": 30765, "s": 30305, "text": null }, { "code": null, "e": 30782, "s": 30765, "text": "app.component.ts" }, { "code": "import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: ['./app.component.scss']})export class AppComponent {}", "e": 30965, "s": 30782, "text": null }, { "code": null, "e": 30981, "s": 30967, "text": "app.module.ts" }, { "code": "import { NgModule } from \"@angular/core\";import { BrowserModule } from \"@angular/platform-browser\";import { BrowserAnimationsModule } from \"@angular/platform-browser/animations\"; import { AppComponent } from \"./app.component\";import { ButtonModule } from \"primeng/button\";import { SidebarModule } from \"primeng/sidebar\"; @NgModule({ imports: [ BrowserModule, BrowserAnimationsModule, SidebarModule, ButtonModule, ], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {}", "e": 31503, "s": 30981, "text": null }, { "code": null, "e": 31511, "s": 31503, "text": "Output:" }, { "code": null, "e": 31612, "s": 31511, "text": "Example 2: In this example, we will know how to use the position property in the Sidebar component. " }, { "code": null, "e": 31631, "s": 31612, "text": "app.component.html" }, { "code": "<p-sidebar [(visible)]=\"gfg\" [baseZIndex]=\"10000\" position=\"right\"> <h1 style=\"font-weight: normal\">GeeksforGeeks</h1> <p>Angular PrimeNG Sidebar Component</p> <p-button type=\"button\" (click)=\"gfg = false\" label=\"OK\" styleClass=\"p-button-info\"> </p-button> <p-button type=\"button\" (click)=\"gfg = false\" label=\"Cancel\" styleClass=\"p-button-danger\"> </p-button></p-sidebar><p-button (click)=\"gfg = true\" label=\"Click Here!\"></p-button>", "e": 32121, "s": 31631, "text": null }, { "code": null, "e": 32138, "s": 32121, "text": "app.component.ts" }, { "code": "import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: ['./app.component.scss']})export class AppComponent {}", "e": 32321, "s": 32138, "text": null }, { "code": null, "e": 32335, "s": 32321, "text": "app.module.ts" }, { "code": "import { NgModule } from \"@angular/core\";import { BrowserModule } from \"@angular/platform-browser\";import { BrowserAnimationsModule } from \"@angular/platform-browser/animations\"; import { AppComponent } from \"./app.component\";import { ButtonModule } from \"primeng/button\";import { SidebarModule } from \"primeng/sidebar\"; @NgModule({ imports: [ BrowserModule, BrowserAnimationsModule, SidebarModule, ButtonModule, ], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {}", "e": 32857, "s": 32335, "text": null }, { "code": null, "e": 32865, "s": 32857, "text": "Output:" }, { "code": null, "e": 32926, "s": 32865, "text": "Reference: https://primefaces.org/primeng/showcase/#/sidebar" }, { "code": null, "e": 32942, "s": 32926, "text": "Angular-PrimeNG" }, { "code": null, "e": 32952, "s": 32942, "text": "AngularJS" }, { "code": null, "e": 32969, "s": 32952, "text": "Web Technologies" }, { "code": null, "e": 33067, "s": 32969, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33102, "s": 33067, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 33137, "s": 33102, "text": "Angular PrimeNG Calendar Component" }, { "code": null, "e": 33161, "s": 33137, "text": "Angular 10 (blur) Event" }, { "code": null, "e": 33196, "s": 33161, "text": "Angular PrimeNG Messages Component" }, { "code": null, "e": 33249, "s": 33196, "text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?" }, { "code": null, "e": 33289, "s": 33249, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 33322, "s": 33289, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 33367, "s": 33322, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 33410, "s": 33367, "text": "How to fetch data from an API in ReactJS ?" } ]
Mathematics | Random Variables - GeeksforGeeks
19 Jul, 2020 Random variable is basically a function which maps from the set of sample space to set of real numbers. The purpose is to get an idea about result of a particular situation where we are given probabilities of different outcomes. See below example for more clarity. Example : Suppose that two coins (unbiased) are tossed X = number of heads. [X is a random variable or function] Here, the sample space S = {HH, HT, TH, TT}. The output of the function will be : X(HH) = 2 X(HT) = 1 X(TH) = 1 X(TT) = 0 Formal definition :X: S -> RX = random variable (It is usually denoted using capital letter)S = set of sample spaceR = set of real numbers Suppose a random variable X takes m different values i.e. sample space X = {x1, x2, x3.........xm} with probabilities P(X=xi) = pi; where 1 ≤ i ≤ m. The probabilities must satisfy the following conditions : 0 <= pi <= 1; where 1 <= i <= mp1 + p2 + p3 + ....... + pm = 1 Or we can say 0 ≤ pi ≤ 1 and ∑pi = 1. 0 <= pi <= 1; where 1 <= i <= m p1 + p2 + p3 + ....... + pm = 1 Or we can say 0 ≤ pi ≤ 1 and ∑pi = 1. Hence possible values for random variable X are 0, 1, 2.X = {0, 1, 2} where m = 3P(X=0) = probability that number of heads is 0 = P(TT) = 1/2*1/2 = 1⁄4.P(X=1) = probability that number of heads is 1 = P(HT | TH) = 1/2*1/2 + 1/2*1/2 = 1⁄2.P(X=2) = probability that number of heads is 2 = P(HH) = 1/2*1/2 = 1⁄4. Here, you can observe that1) 0 ≤ p1, p2, p3 ≤ 12) p1 + p2 + p3 = 1/4 + 2/4 + 1/4 = 1 Example :Suppose a dice is thrown X = outcome of the dice. Here, the sample space S = {1, 2, 3, 4, 5, 6}. The output of the function will be: P(X=1) = 1/6P(X=2) = 1/6P(X=3) = 1/6P(X=4) = 1/6P(X=5) = 1/6P(X=6) = 1/6 P(X=1) = 1/6 P(X=2) = 1/6 P(X=3) = 1/6 P(X=4) = 1/6 P(X=5) = 1/6 P(X=6) = 1/6 See if there is any random variable then there must be some distribution associated with it. Discrete Random Variable: A random variable X is said to be discrete if it takes on finite number of values. The probability function associated with it is said to be PMF = Probability mass function.P(xi) = Probability that X = xi = PMF of X = pi. 0 ≤ pi ≤ 1.∑pi = 1 where sum is taken over all possible values of x. 0 ≤ pi ≤ 1. ∑pi = 1 where sum is taken over all possible values of x. The examples given above are discrete random variables. Example:- Let S = {0, 1, 2} Find the value of P (X=0):Sol:- We know that sum of all probabilities is equals to 1.==> p1 + p2 + p3 = 1==> p1 + 0.3 + 0.5 = 1==> p1 = 0.2 Continuous Random Variable: A random variable X is said to be continuous if it takes on infinite number of values. The probability function associated with it is said to be PDF = Probability density functionPDF: If X is continuous random variable.P (x < X < x + dx) = f(x)*dx. 0 ≤ f(x) ≤ 1; for all x∫ f(x) dx = 1 over all values of x 0 ≤ f(x) ≤ 1; for all x ∫ f(x) dx = 1 over all values of x Then P (X) is said to be PDF of the distribution. Example:- Compute the value of P (1 < X < 2). Such that f(x) = k*x^3; 0 ≤ x ≤ 3 = 0; otherwise f(x) is a density function Solution:- If a function f is said to be density function, then sum of all probabilities is equals to 1. Since it is a continuous random variable Integral value is 1 overall sample space s.==> K*[x^4]/4 = 1 [Note that [x^4]/4 is integral of x^3]==> K*[3^4 – 0^4]/4 = 1==> K = 4/81The value of P (1 < X < 2) = k*[X^4]/4 = 4/81 * [16-1]/4 = 15/81. Next Topic :Linearity of Expectation The Article is contributed by Anil Saikrishna DevarasettyPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above Engineering Mathematics GATE CS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Inequalities in LaTeX Activation Functions Arrow Symbols in LaTeX Newton's Divided Difference Interpolation Formula Set Notations in LaTeX Layers of OSI Model ACID Properties in DBMS TCP/IP Model Types of Operating Systems Normal Forms in DBMS
[ { "code": null, "e": 31387, "s": 31359, "text": "\n19 Jul, 2020" }, { "code": null, "e": 31652, "s": 31387, "text": "Random variable is basically a function which maps from the set of sample space to set of real numbers. The purpose is to get an idea about result of a particular situation where we are given probabilities of different outcomes. See below example for more clarity." }, { "code": null, "e": 31662, "s": 31652, "text": "Example :" }, { "code": null, "e": 31950, "s": 31662, "text": "Suppose that two coins (unbiased) are tossed \n\nX = number of heads. [X is a random variable \n or function]\n\nHere, the sample space S = {HH, HT, TH, TT}. \n\nThe output of the function will be :\n X(HH) = 2\n X(HT) = 1\n X(TH) = 1\n X(TT) = 0\n" }, { "code": null, "e": 32089, "s": 31950, "text": "Formal definition :X: S -> RX = random variable (It is usually denoted using capital letter)S = set of sample spaceR = set of real numbers" }, { "code": null, "e": 32296, "s": 32089, "text": "Suppose a random variable X takes m different values i.e. sample space X = {x1, x2, x3.........xm} with probabilities P(X=xi) = pi; where 1 ≤ i ≤ m. The probabilities must satisfy the following conditions :" }, { "code": null, "e": 32397, "s": 32296, "text": "0 <= pi <= 1; where 1 <= i <= mp1 + p2 + p3 + ....... + pm = 1 Or we can say 0 ≤ pi ≤ 1 and ∑pi = 1." }, { "code": null, "e": 32429, "s": 32397, "text": "0 <= pi <= 1; where 1 <= i <= m" }, { "code": null, "e": 32499, "s": 32429, "text": "p1 + p2 + p3 + ....... + pm = 1 Or we can say 0 ≤ pi ≤ 1 and ∑pi = 1." }, { "code": null, "e": 32809, "s": 32499, "text": "Hence possible values for random variable X are 0, 1, 2.X = {0, 1, 2} where m = 3P(X=0) = probability that number of heads is 0 = P(TT) = 1/2*1/2 = 1⁄4.P(X=1) = probability that number of heads is 1 = P(HT | TH) = 1/2*1/2 + 1/2*1/2 = 1⁄2.P(X=2) = probability that number of heads is 2 = P(HH) = 1/2*1/2 = 1⁄4." }, { "code": null, "e": 32894, "s": 32809, "text": "Here, you can observe that1) 0 ≤ p1, p2, p3 ≤ 12) p1 + p2 + p3 = 1/4 + 2/4 + 1/4 = 1" }, { "code": null, "e": 33036, "s": 32894, "text": "Example :Suppose a dice is thrown X = outcome of the dice. Here, the sample space S = {1, 2, 3, 4, 5, 6}. The output of the function will be:" }, { "code": null, "e": 33109, "s": 33036, "text": "P(X=1) = 1/6P(X=2) = 1/6P(X=3) = 1/6P(X=4) = 1/6P(X=5) = 1/6P(X=6) = 1/6" }, { "code": null, "e": 33122, "s": 33109, "text": "P(X=1) = 1/6" }, { "code": null, "e": 33135, "s": 33122, "text": "P(X=2) = 1/6" }, { "code": null, "e": 33148, "s": 33135, "text": "P(X=3) = 1/6" }, { "code": null, "e": 33161, "s": 33148, "text": "P(X=4) = 1/6" }, { "code": null, "e": 33174, "s": 33161, "text": "P(X=5) = 1/6" }, { "code": null, "e": 33187, "s": 33174, "text": "P(X=6) = 1/6" }, { "code": null, "e": 33280, "s": 33187, "text": "See if there is any random variable then there must be some distribution associated with it." }, { "code": null, "e": 33306, "s": 33280, "text": "Discrete Random Variable:" }, { "code": null, "e": 33528, "s": 33306, "text": "A random variable X is said to be discrete if it takes on finite number of values. The probability function associated with it is said to be PMF = Probability mass function.P(xi) = Probability that X = xi = PMF of X = pi." }, { "code": null, "e": 33597, "s": 33528, "text": "0 ≤ pi ≤ 1.∑pi = 1 where sum is taken over all possible values of x." }, { "code": null, "e": 33609, "s": 33597, "text": "0 ≤ pi ≤ 1." }, { "code": null, "e": 33667, "s": 33609, "text": "∑pi = 1 where sum is taken over all possible values of x." }, { "code": null, "e": 33723, "s": 33667, "text": "The examples given above are discrete random variables." }, { "code": null, "e": 33751, "s": 33723, "text": "Example:- Let S = {0, 1, 2}" }, { "code": null, "e": 33891, "s": 33751, "text": "Find the value of P (X=0):Sol:- We know that sum of all probabilities is equals to 1.==> p1 + p2 + p3 = 1==> p1 + 0.3 + 0.5 = 1==> p1 = 0.2" }, { "code": null, "e": 33921, "s": 33893, "text": "Continuous Random Variable:" }, { "code": null, "e": 34170, "s": 33921, "text": "A random variable X is said to be continuous if it takes on infinite number of values. The probability function associated with it is said to be PDF = Probability density functionPDF: If X is continuous random variable.P (x < X < x + dx) = f(x)*dx." }, { "code": null, "e": 34228, "s": 34170, "text": "0 ≤ f(x) ≤ 1; for all x∫ f(x) dx = 1 over all values of x" }, { "code": null, "e": 34252, "s": 34228, "text": "0 ≤ f(x) ≤ 1; for all x" }, { "code": null, "e": 34287, "s": 34252, "text": "∫ f(x) dx = 1 over all values of x" }, { "code": null, "e": 34337, "s": 34287, "text": "Then P (X) is said to be PDF of the distribution." }, { "code": null, "e": 34383, "s": 34337, "text": "Example:- Compute the value of P (1 < X < 2)." }, { "code": null, "e": 34476, "s": 34383, "text": "Such that f(x) = k*x^3; 0 ≤ x ≤ 3\n = 0; otherwise\nf(x) is a density function\n" }, { "code": null, "e": 34822, "s": 34476, "text": "Solution:- If a function f is said to be density function, then sum of all probabilities is equals to 1. Since it is a continuous random variable Integral value is 1 overall sample space s.==> K*[x^4]/4 = 1 [Note that [x^4]/4 is integral of x^3]==> K*[3^4 – 0^4]/4 = 1==> K = 4/81The value of P (1 < X < 2) = k*[X^4]/4 = 4/81 * [16-1]/4 = 15/81." }, { "code": null, "e": 34859, "s": 34822, "text": "Next Topic :Linearity of Expectation" }, { "code": null, "e": 35040, "s": 34859, "text": "The Article is contributed by Anil Saikrishna DevarasettyPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 35064, "s": 35040, "text": "Engineering Mathematics" }, { "code": null, "e": 35072, "s": 35064, "text": "GATE CS" }, { "code": null, "e": 35170, "s": 35072, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35192, "s": 35170, "text": "Inequalities in LaTeX" }, { "code": null, "e": 35213, "s": 35192, "text": "Activation Functions" }, { "code": null, "e": 35236, "s": 35213, "text": "Arrow Symbols in LaTeX" }, { "code": null, "e": 35286, "s": 35236, "text": "Newton's Divided Difference Interpolation Formula" }, { "code": null, "e": 35309, "s": 35286, "text": "Set Notations in LaTeX" }, { "code": null, "e": 35329, "s": 35309, "text": "Layers of OSI Model" }, { "code": null, "e": 35353, "s": 35329, "text": "ACID Properties in DBMS" }, { "code": null, "e": 35366, "s": 35353, "text": "TCP/IP Model" }, { "code": null, "e": 35393, "s": 35366, "text": "Types of Operating Systems" } ]
Lua - Data Types
Lua is a dynamically typed language, so the variables don't have types, only the values have types. Values can be stored in variables, passed as parameters and returned as results. In Lua, though we don't have variable data types, but we have types for the values. The list of data types for values are given below. nil Used to differentiate the value from having some data or no(nil) data. boolean Includes true and false as values. Generally used for condition checking. number Represents real(double precision floating point) numbers. string Represents array of characters. function Represents a method that is written in C or Lua. userdata Represents arbitrary C data. thread Represents independent threads of execution and it is used to implement coroutines. table Represent ordinary arrays, symbol tables, sets, records, graphs, trees, etc., and implements associative arrays. It can hold any value (except nil). In Lua, there is a function called ‘type’ that enables us to know the type of the variable. Some examples are given in the following code. print(type("What is my type")) --> string t = 10 print(type(5.8*t)) --> number print(type(true)) --> boolean print(type(print)) --> function print(type(nil)) --> nil print(type(type(ABC))) --> string When you build and execute the above program, it produces the following result on Linux − string number boolean function nil string By default, all the variables will point to nil until they are assigned a value or initialized. In Lua, zero and empty strings are considered to be true in case of condition checks. Hence, you have to be careful when using Boolean operations. We will know more using these types in the next chapters. 12 Lectures 2 hours Manish Gupta 80 Lectures 3 hours Sanjeev Mittal 54 Lectures 3.5 hours Mehmet GOKTEPE Print Add Notes Bookmark this page
[ { "code": null, "e": 2284, "s": 2103, "text": "Lua is a dynamically typed language, so the variables don't have types, only the values have types. Values can be stored in variables, passed as parameters and returned as results." }, { "code": null, "e": 2419, "s": 2284, "text": "In Lua, though we don't have variable data types, but we have types for the values. The list of data types for values are given below." }, { "code": null, "e": 2423, "s": 2419, "text": "nil" }, { "code": null, "e": 2494, "s": 2423, "text": "Used to differentiate the value from having some data or no(nil) data." }, { "code": null, "e": 2502, "s": 2494, "text": "boolean" }, { "code": null, "e": 2576, "s": 2502, "text": "Includes true and false as values. Generally used for condition checking." }, { "code": null, "e": 2583, "s": 2576, "text": "number" }, { "code": null, "e": 2641, "s": 2583, "text": "Represents real(double precision floating point) numbers." }, { "code": null, "e": 2648, "s": 2641, "text": "string" }, { "code": null, "e": 2680, "s": 2648, "text": "Represents array of characters." }, { "code": null, "e": 2689, "s": 2680, "text": "function" }, { "code": null, "e": 2738, "s": 2689, "text": "Represents a method that is written in C or Lua." }, { "code": null, "e": 2747, "s": 2738, "text": "userdata" }, { "code": null, "e": 2776, "s": 2747, "text": "Represents arbitrary C data." }, { "code": null, "e": 2783, "s": 2776, "text": "thread" }, { "code": null, "e": 2867, "s": 2783, "text": "Represents independent threads of execution and it is used to implement coroutines." }, { "code": null, "e": 2873, "s": 2867, "text": "table" }, { "code": null, "e": 3022, "s": 2873, "text": "Represent ordinary arrays, symbol tables, sets, records, graphs, trees, etc., and implements associative arrays. It can hold any value (except nil)." }, { "code": null, "e": 3161, "s": 3022, "text": "In Lua, there is a function called ‘type’ that enables us to know the type of the variable. Some examples are given in the following code." }, { "code": null, "e": 3433, "s": 3161, "text": "print(type(\"What is my type\")) --> string\nt = 10\n\nprint(type(5.8*t)) --> number\nprint(type(true)) --> boolean\nprint(type(print)) --> function\nprint(type(nil)) --> nil\nprint(type(type(ABC))) --> string" }, { "code": null, "e": 3523, "s": 3433, "text": "When you build and execute the above program, it produces the following result on Linux −" }, { "code": null, "e": 3566, "s": 3523, "text": "string\nnumber\nboolean\nfunction\nnil\nstring\n" }, { "code": null, "e": 3867, "s": 3566, "text": "By default, all the variables will point to nil until they are assigned a value or initialized. In Lua, zero and empty strings are considered to be true in case of condition checks. Hence, you have to be careful when using Boolean operations. We will know more using these types in the next chapters." }, { "code": null, "e": 3900, "s": 3867, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 3914, "s": 3900, "text": " Manish Gupta" }, { "code": null, "e": 3947, "s": 3914, "text": "\n 80 Lectures \n 3 hours \n" }, { "code": null, "e": 3963, "s": 3947, "text": " Sanjeev Mittal" }, { "code": null, "e": 3998, "s": 3963, "text": "\n 54 Lectures \n 3.5 hours \n" }, { "code": null, "e": 4014, "s": 3998, "text": " Mehmet GOKTEPE" }, { "code": null, "e": 4021, "s": 4014, "text": " Print" }, { "code": null, "e": 4032, "s": 4021, "text": " Add Notes" } ]
How To Place Legend Outside the Plot with Seaborn in Python? - GeeksforGeeks
16 Nov, 2020 Seaborn is a Python data visualization library based on matplotlib. It provides a high-level interface for drawing attractive and informative statistical graphics. Basically, it helps us stylize our basic plot made using matplotlib. Moreover, it also provides us different plotting techniques to ease our Exploratory Data Analysis(EDA). With these plots, it also becomes important to provide legends for a particular plot. In this following article, we are going to see how can we place our Legend on our plot, and later in this article, we will also see how can we place the legend outside the plot using Seaborn. We will start by importing our necessary libraries. Python3 import seaborn as sns import matplotlib.pyplot as plt We will be using Seaborn for not only plotting the data but also importing our dataset. Here we will be using the Gamma dataset by seaborn. Python3 # set our graph style to whitegridsns.set(style="whitegrid") # load the gammas datasetds = sns.load_dataset("gammas") # use seaborn's lineplot to plot our timeplot# and BOLD signal columnssns.lineplot(data=ds, x="timepoint", y="BOLD signal", hue = "ROI") plt.show() Output: We can see that this plots a beautiful line plot graph with the legends. We can see that the legend box is on the plot. This might be an issue in many plots, so we need to keep our legend box outside the plot. We can do this by using matplotlib’s legend function and providing its necessary parameters. Python3 plt.legend(bbox_to_anchor=(1, 1), loc=2) Output: We can also tune our parameters according to our necessities. Python3 plt.legend(bbox_to_anchor=(1.02, 1), loc=2) Output: Hence, this technique can be used in many scenarios where the legend box comes on the graph which may be otherwise useful for our EDA. Python-Seaborn Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | os.path.join() method Python | Get unique values from a list Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25555, "s": 25527, "text": "\n16 Nov, 2020" }, { "code": null, "e": 25978, "s": 25555, "text": "Seaborn is a Python data visualization library based on matplotlib. It provides a high-level interface for drawing attractive and informative statistical graphics. Basically, it helps us stylize our basic plot made using matplotlib. Moreover, it also provides us different plotting techniques to ease our Exploratory Data Analysis(EDA). With these plots, it also becomes important to provide legends for a particular plot." }, { "code": null, "e": 26171, "s": 25978, "text": "In this following article, we are going to see how can we place our Legend on our plot, and later in this article, we will also see how can we place the legend outside the plot using Seaborn. " }, { "code": null, "e": 26224, "s": 26171, "text": "We will start by importing our necessary libraries. " }, { "code": null, "e": 26232, "s": 26224, "text": "Python3" }, { "code": "import seaborn as sns import matplotlib.pyplot as plt", "e": 26286, "s": 26232, "text": null }, { "code": null, "e": 26427, "s": 26286, "text": "We will be using Seaborn for not only plotting the data but also importing our dataset. Here we will be using the Gamma dataset by seaborn. " }, { "code": null, "e": 26435, "s": 26427, "text": "Python3" }, { "code": "# set our graph style to whitegridsns.set(style=\"whitegrid\") # load the gammas datasetds = sns.load_dataset(\"gammas\") # use seaborn's lineplot to plot our timeplot# and BOLD signal columnssns.lineplot(data=ds, x=\"timepoint\", y=\"BOLD signal\", hue = \"ROI\") plt.show()", "e": 26707, "s": 26435, "text": null }, { "code": null, "e": 26715, "s": 26707, "text": "Output:" }, { "code": null, "e": 26926, "s": 26715, "text": "We can see that this plots a beautiful line plot graph with the legends. We can see that the legend box is on the plot. This might be an issue in many plots, so we need to keep our legend box outside the plot. " }, { "code": null, "e": 27019, "s": 26926, "text": "We can do this by using matplotlib’s legend function and providing its necessary parameters." }, { "code": null, "e": 27027, "s": 27019, "text": "Python3" }, { "code": "plt.legend(bbox_to_anchor=(1, 1), loc=2)", "e": 27068, "s": 27027, "text": null }, { "code": null, "e": 27076, "s": 27068, "text": "Output:" }, { "code": null, "e": 27139, "s": 27076, "text": "We can also tune our parameters according to our necessities. " }, { "code": null, "e": 27147, "s": 27139, "text": "Python3" }, { "code": "plt.legend(bbox_to_anchor=(1.02, 1), loc=2)", "e": 27191, "s": 27147, "text": null }, { "code": null, "e": 27199, "s": 27191, "text": "Output:" }, { "code": null, "e": 27335, "s": 27199, "text": "Hence, this technique can be used in many scenarios where the legend box comes on the graph which may be otherwise useful for our EDA. " }, { "code": null, "e": 27350, "s": 27335, "text": "Python-Seaborn" }, { "code": null, "e": 27357, "s": 27350, "text": "Python" }, { "code": null, "e": 27455, "s": 27357, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27487, "s": 27455, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27529, "s": 27487, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27571, "s": 27529, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27627, "s": 27571, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27654, "s": 27627, "text": "Python Classes and Objects" }, { "code": null, "e": 27685, "s": 27654, "text": "Python | os.path.join() method" }, { "code": null, "e": 27724, "s": 27685, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27753, "s": 27724, "text": "Create a directory in Python" }, { "code": null, "e": 27775, "s": 27753, "text": "Defaultdict in Python" } ]
How to Detect Keypress using JavaScript ? - GeeksforGeeks
31 Aug, 2020 In this article, keyboard detection is performed using HTML and CSS.HTML stands for “Hypertext Markup Language”. HTML language helps the developer to create and design the web page elements like links, sections, paragraphs, headings, and blockquotes for web applications. CSS stands for “Cascading Style Sheet”. Cascading style sheets are used to design web page layouts. The styles are defined to give styles to tables, sizes, and texts. JavaScript is a scripting programming language used on the client and server-side which makes the web pages talk and communicate with each other.All of the above technologies are used to implement keypress detection.Program editor applications like Atom or Sublime Text can be used to compile the programs. Example:Create an index.html file for the following code. <html><head> <link rel="stylesheet" type="text/css" href="main.css"> <script type="text/javascript" src="main.js"> </script></head><body> <div id="demo"></div></body></html> For the HTML above code, we need to include main.css and main.js CSS code: The following code is written in the main.css file. body{ font-family: monospace, arial; font-size: 38px; text-align: center;} JavaScript code: The following code is written in the main.js file. window.onload = function(){ var demo = document.getElementById('demo'); var value = 0; var space_bar = 32; var right_arrow = 39; window.onkeydown= function(gfg){ if(gfg.keyCode === space_bar){ value++; demo.innerHTML = value; }; if(gfg.keyCode === right_arrow) { alert("Welcome to GeeksForGeeks!"); }; };}; Here, var space_bar = 32 and var right_arrow = 39 are actually the key codes that corresponds to the specific key. Whenever the space bar or the right arrow is clicked, the HTML will detect the type of click and respond by the number of times clicked or by a message. Output: A number gets displayed when the space bar is once clicked. A number gets displayed when the space bar is once clicked. When the right arrow is clicked, the page responds with a message. When the right arrow is clicked, the page responds with a message. My Personal Notes arrow_drop_upSave CSS-Misc HTML-Misc JavaScript-Misc CSS HTML JavaScript Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? How to apply style to parent if it has child with CSS? Types of CSS (Cascading Style Sheet) How to position a div at the bottom of its container using CSS? How to set space between the flexbox ? How to update Node.js and NPM to next version ? How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property How to set input type date in dd-mm-yyyy format using HTML ? REST API (Introduction)
[ { "code": null, "e": 25947, "s": 25919, "text": "\n31 Aug, 2020" }, { "code": null, "e": 26219, "s": 25947, "text": "In this article, keyboard detection is performed using HTML and CSS.HTML stands for “Hypertext Markup Language”. HTML language helps the developer to create and design the web page elements like links, sections, paragraphs, headings, and blockquotes for web applications." }, { "code": null, "e": 26386, "s": 26219, "text": "CSS stands for “Cascading Style Sheet”. Cascading style sheets are used to design web page layouts. The styles are defined to give styles to tables, sizes, and texts." }, { "code": null, "e": 26693, "s": 26386, "text": "JavaScript is a scripting programming language used on the client and server-side which makes the web pages talk and communicate with each other.All of the above technologies are used to implement keypress detection.Program editor applications like Atom or Sublime Text can be used to compile the programs." }, { "code": null, "e": 26751, "s": 26693, "text": "Example:Create an index.html file for the following code." }, { "code": "<html><head> <link rel=\"stylesheet\" type=\"text/css\" href=\"main.css\"> <script type=\"text/javascript\" src=\"main.js\"> </script></head><body> <div id=\"demo\"></div></body></html>", "e": 26945, "s": 26751, "text": null }, { "code": null, "e": 27010, "s": 26945, "text": "For the HTML above code, we need to include main.css and main.js" }, { "code": null, "e": 27072, "s": 27010, "text": "CSS code: The following code is written in the main.css file." }, { "code": "body{ font-family: monospace, arial; font-size: 38px; text-align: center;}", "e": 27156, "s": 27072, "text": null }, { "code": null, "e": 27224, "s": 27156, "text": "JavaScript code: The following code is written in the main.js file." }, { "code": "window.onload = function(){ var demo = document.getElementById('demo'); var value = 0; var space_bar = 32; var right_arrow = 39; window.onkeydown= function(gfg){ if(gfg.keyCode === space_bar){ value++; demo.innerHTML = value; }; if(gfg.keyCode === right_arrow) { alert(\"Welcome to GeeksForGeeks!\"); }; };}; ", "e": 27620, "s": 27224, "text": null }, { "code": null, "e": 27626, "s": 27620, "text": "Here," }, { "code": null, "e": 27646, "s": 27626, "text": "var space_bar = 32 " }, { "code": null, "e": 27650, "s": 27646, "text": "and" }, { "code": null, "e": 27672, "s": 27650, "text": "var right_arrow = 39 " }, { "code": null, "e": 27890, "s": 27672, "text": "are actually the key codes that corresponds to the specific key. Whenever the space bar or the right arrow is clicked, the HTML will detect the type of click and respond by the number of times clicked or by a message." }, { "code": null, "e": 27898, "s": 27890, "text": "Output:" }, { "code": null, "e": 27958, "s": 27898, "text": "A number gets displayed when the space bar is once clicked." }, { "code": null, "e": 28018, "s": 27958, "text": "A number gets displayed when the space bar is once clicked." }, { "code": null, "e": 28085, "s": 28018, "text": "When the right arrow is clicked, the page responds with a message." }, { "code": null, "e": 28152, "s": 28085, "text": "When the right arrow is clicked, the page responds with a message." }, { "code": null, "e": 28188, "s": 28152, "text": "My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 28197, "s": 28188, "text": "CSS-Misc" }, { "code": null, "e": 28207, "s": 28197, "text": "HTML-Misc" }, { "code": null, "e": 28223, "s": 28207, "text": "JavaScript-Misc" }, { "code": null, "e": 28227, "s": 28223, "text": "CSS" }, { "code": null, "e": 28232, "s": 28227, "text": "HTML" }, { "code": null, "e": 28243, "s": 28232, "text": "JavaScript" }, { "code": null, "e": 28260, "s": 28243, "text": "Web Technologies" }, { "code": null, "e": 28265, "s": 28260, "text": "HTML" }, { "code": null, "e": 28363, "s": 28265, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28411, "s": 28363, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 28466, "s": 28411, "text": "How to apply style to parent if it has child with CSS?" }, { "code": null, "e": 28503, "s": 28466, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 28567, "s": 28503, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 28606, "s": 28567, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 28654, "s": 28606, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 28714, "s": 28654, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 28767, "s": 28714, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 28828, "s": 28767, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" } ]
Bootstrap-5 Badges - GeeksforGeeks
05 May, 2022 Bootstrap 5 is the latest major release by Bootstrap where they have revamped the UI and made various changes. Badges are used for creating labels. Badges scale to match the size of the immediate parent element by using relative font sizing. Syntax: <div class="badge bg-type"> Contents... <div> Types: Following are the eight types of backgrounds available in Bootstrap 5. bg-primary bg-secondary bg-success bg-danger bg-warning bg-info bg-light bg-dark Example 1: This example demonstrates the working of the first four types of Badges in Bootstrap 5. HTML <!DOCTYPE html><html><head> <!-- Load Bootstrap --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css" integrity="sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I" crossorigin="anonymous"></head><body> <div style="text-align: center;width: 600px;"> <h1 style="color: green;"> GeeksforGeeks </h1> </div> <div id="canvas" style="width: 600px; height: 200px;margin:20px;"> <h4> Hello World <span class="badge bg-primary"> GeeksforGeeks </span> </h4> <h4> Hello World <span class="badge bg-secondary"> GeeksforGeeks </span> </h4> <h4> Hello World <span class="badge bg-success"> GeeksforGeeks </span> </h4> <h4> Hello World <span class="badge bg-danger"> GeeksforGeeks </span> </h4> </div></body></html> Output: Example 2: This example demonstrates the working of last four types of Badges in Bootstrap 5. HTML <!DOCTYPE html><html><head> <!-- Load Bootstrap --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css" integrity="sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I" crossorigin="anonymous"></head><body> <div style="text-align: center;width: 600px;"> <h1 style="color: green;"> GeeksforGeeks </h1> </div> <div id="canvas" style="width: 600px; height: 200px;margin:20px;"> <h4> Hello World <span class="badge bg-warning"> GeeksforGeeks </span> </h4> <h4> Hello World <span class="badge bg-info"> GeeksforGeeks </span> </h4> <h4> Hello World <span class="badge bg-light text-dark"> GeeksforGeeks </span> </h4> <h4> Hello World <span class="badge bg-dark"> GeeksforGeeks </span> </h4> </div></body></html> Output: Example 3: This example shows the working of notifications badges in Bootstrap 5. HTML <!DOCTYPE html><html><head> <!-- Load Bootstrap --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css" integrity="sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I" crossorigin="anonymous"></head><body style="text-align:center;"> <div class="container mt-3"> <h1 style="color:green;"> GeeksforGeeks </h1> <button type="button" class="btn btn-primary"> Notifications <span class="badge bg-secondary"> 10 </span> </button> </div></body></html> Output: Example 4: This example shows the working of Pill Badges in Bootstrap 5. HTML <!DOCTYPE html><html><head> <!-- Load Bootstrap --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css" integrity="sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I" crossorigin="anonymous"></head><body style="text-align:center;"> <div class="container mt-3"> <h1 style="color:green;"> GeeksforGeeks </h1> <span class="badge rounded-pill bg-primary"> Primary </span> <span class="badge rounded-pill bg-secondary"> Secondary </span> <span class="badge rounded-pill bg-success"> Success </span> <span class="badge rounded-pill bg-danger"> Danger </span> <span class="badge rounded-pill bg-warning text-dark"> Warning </span> <span class="badge rounded-pill bg-info"> Info </span> <span class="badge rounded-pill bg-light text-dark"> Light </span> <span class="badge rounded-pill bg-dark"> Dark </span> </div></body></html> Output: Supported Browser: Google Chrome Internet Explorer Firefox Opera Safari ysachin2314 sahilintern Bootstrap Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Form validation using jQuery How to change navigation bar color in Bootstrap ? How to pass data into a bootstrap modal? How to align navbar items to the right in Bootstrap 4 ? How to set Bootstrap Timepicker using datetimepicker library ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 28538, "s": 28510, "text": "\n05 May, 2022" }, { "code": null, "e": 28780, "s": 28538, "text": "Bootstrap 5 is the latest major release by Bootstrap where they have revamped the UI and made various changes. Badges are used for creating labels. Badges scale to match the size of the immediate parent element by using relative font sizing." }, { "code": null, "e": 28790, "s": 28780, "text": "Syntax: " }, { "code": null, "e": 28836, "s": 28790, "text": "<div class=\"badge bg-type\"> Contents... <div>" }, { "code": null, "e": 28915, "s": 28836, "text": "Types: Following are the eight types of backgrounds available in Bootstrap 5. " }, { "code": null, "e": 28926, "s": 28915, "text": "bg-primary" }, { "code": null, "e": 28939, "s": 28926, "text": "bg-secondary" }, { "code": null, "e": 28950, "s": 28939, "text": "bg-success" }, { "code": null, "e": 28960, "s": 28950, "text": "bg-danger" }, { "code": null, "e": 28971, "s": 28960, "text": "bg-warning" }, { "code": null, "e": 28979, "s": 28971, "text": "bg-info" }, { "code": null, "e": 28988, "s": 28979, "text": "bg-light" }, { "code": null, "e": 28996, "s": 28988, "text": "bg-dark" }, { "code": null, "e": 29096, "s": 28996, "text": "Example 1: This example demonstrates the working of the first four types of Badges in Bootstrap 5. " }, { "code": null, "e": 29101, "s": 29096, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <!-- Load Bootstrap --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css\" integrity=\"sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I\" crossorigin=\"anonymous\"></head><body> <div style=\"text-align: center;width: 600px;\"> <h1 style=\"color: green;\"> GeeksforGeeks </h1> </div> <div id=\"canvas\" style=\"width: 600px; height: 200px;margin:20px;\"> <h4> Hello World <span class=\"badge bg-primary\"> GeeksforGeeks </span> </h4> <h4> Hello World <span class=\"badge bg-secondary\"> GeeksforGeeks </span> </h4> <h4> Hello World <span class=\"badge bg-success\"> GeeksforGeeks </span> </h4> <h4> Hello World <span class=\"badge bg-danger\"> GeeksforGeeks </span> </h4> </div></body></html>", "e": 30197, "s": 29101, "text": null }, { "code": null, "e": 30205, "s": 30197, "text": "Output:" }, { "code": null, "e": 30300, "s": 30205, "text": "Example 2: This example demonstrates the working of last four types of Badges in Bootstrap 5. " }, { "code": null, "e": 30305, "s": 30300, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <!-- Load Bootstrap --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css\" integrity=\"sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I\" crossorigin=\"anonymous\"></head><body> <div style=\"text-align: center;width: 600px;\"> <h1 style=\"color: green;\"> GeeksforGeeks </h1> </div> <div id=\"canvas\" style=\"width: 600px; height: 200px;margin:20px;\"> <h4> Hello World <span class=\"badge bg-warning\"> GeeksforGeeks </span> </h4> <h4> Hello World <span class=\"badge bg-info\"> GeeksforGeeks </span> </h4> <h4> Hello World <span class=\"badge bg-light text-dark\"> GeeksforGeeks </span> </h4> <h4> Hello World <span class=\"badge bg-dark\"> GeeksforGeeks </span> </h4> </div></body></html>", "e": 31402, "s": 30305, "text": null }, { "code": null, "e": 31410, "s": 31402, "text": "Output:" }, { "code": null, "e": 31493, "s": 31410, "text": "Example 3: This example shows the working of notifications badges in Bootstrap 5. " }, { "code": null, "e": 31498, "s": 31493, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <!-- Load Bootstrap --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css\" integrity=\"sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I\" crossorigin=\"anonymous\"></head><body style=\"text-align:center;\"> <div class=\"container mt-3\"> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <button type=\"button\" class=\"btn btn-primary\"> Notifications <span class=\"badge bg-secondary\"> 10 </span> </button> </div></body></html>", "e": 32134, "s": 31498, "text": null }, { "code": null, "e": 32142, "s": 32134, "text": "Output:" }, { "code": null, "e": 32216, "s": 32142, "text": "Example 4: This example shows the working of Pill Badges in Bootstrap 5. " }, { "code": null, "e": 32221, "s": 32216, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <!-- Load Bootstrap --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css\" integrity=\"sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I\" crossorigin=\"anonymous\"></head><body style=\"text-align:center;\"> <div class=\"container mt-3\"> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <span class=\"badge rounded-pill bg-primary\"> Primary </span> <span class=\"badge rounded-pill bg-secondary\"> Secondary </span> <span class=\"badge rounded-pill bg-success\"> Success </span> <span class=\"badge rounded-pill bg-danger\"> Danger </span> <span class=\"badge rounded-pill bg-warning text-dark\"> Warning </span> <span class=\"badge rounded-pill bg-info\"> Info </span> <span class=\"badge rounded-pill bg-light text-dark\"> Light </span> <span class=\"badge rounded-pill bg-dark\"> Dark </span> </div></body></html>", "e": 33445, "s": 32221, "text": null }, { "code": null, "e": 33453, "s": 33445, "text": "Output:" }, { "code": null, "e": 33472, "s": 33453, "text": "Supported Browser:" }, { "code": null, "e": 33486, "s": 33472, "text": "Google Chrome" }, { "code": null, "e": 33504, "s": 33486, "text": "Internet Explorer" }, { "code": null, "e": 33512, "s": 33504, "text": "Firefox" }, { "code": null, "e": 33518, "s": 33512, "text": "Opera" }, { "code": null, "e": 33525, "s": 33518, "text": "Safari" }, { "code": null, "e": 33537, "s": 33525, "text": "ysachin2314" }, { "code": null, "e": 33549, "s": 33537, "text": "sahilintern" }, { "code": null, "e": 33559, "s": 33549, "text": "Bootstrap" }, { "code": null, "e": 33576, "s": 33559, "text": "Web Technologies" }, { "code": null, "e": 33674, "s": 33576, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33703, "s": 33674, "text": "Form validation using jQuery" }, { "code": null, "e": 33753, "s": 33703, "text": "How to change navigation bar color in Bootstrap ?" }, { "code": null, "e": 33794, "s": 33753, "text": "How to pass data into a bootstrap modal?" }, { "code": null, "e": 33850, "s": 33794, "text": "How to align navbar items to the right in Bootstrap 4 ?" }, { "code": null, "e": 33913, "s": 33850, "text": "How to set Bootstrap Timepicker using datetimepicker library ?" }, { "code": null, "e": 33953, "s": 33913, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 33986, "s": 33953, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 34031, "s": 33986, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 34074, "s": 34031, "text": "How to fetch data from an API in ReactJS ?" } ]
ES6 - Proxy API
ES6 implements intercession form of meta programming using Proxies. Similar to ReflectAPI, the Proxy API is another way of implementing meta programming in ES6. The Proxy object is used to define custom behavior for fundamental operations. A proxy object performs some operations on behalf of the real object. The various terminologies related to ES6 proxies are given below handler Placeholder object which contains traps traps The methods that provide property access. This is analogous to the concept of traps in operating systems target Object which the proxy virtualizes. It is often used as storage backend for the proxy. The syntax stated below is for the Proxy API, where, target can be any sort of object like array, function or another proxy and handler is an object whose properties are functions. This defines the behavior of the proxy. const proxy = new Proxy(target,handler) The handler object contains traps for Proxy. All traps are optional. If a trap has not been defined, the default behavior is to forward the operation to the target. Some common handler methods are as follows − A trap for a function call. A trap for the new operator. A trap for getting property values. A trap for setting property values. TA trap for the in operator. 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": 2587, "s": 2277, "text": "ES6 implements intercession form of meta programming using Proxies. Similar to ReflectAPI, the Proxy API is another way of implementing meta programming in ES6. The Proxy object is used to define custom behavior for fundamental operations. A proxy object performs some operations on behalf of the real object." }, { "code": null, "e": 2652, "s": 2587, "text": "The various terminologies related to ES6 proxies are given below" }, { "code": null, "e": 2660, "s": 2652, "text": "handler" }, { "code": null, "e": 2700, "s": 2660, "text": "Placeholder object which contains traps" }, { "code": null, "e": 2706, "s": 2700, "text": "traps" }, { "code": null, "e": 2811, "s": 2706, "text": "The methods that provide property access. This is analogous to the concept of traps in operating systems" }, { "code": null, "e": 2818, "s": 2811, "text": "target" }, { "code": null, "e": 2905, "s": 2818, "text": "Object which the proxy virtualizes. It is often used as storage backend for the proxy." }, { "code": null, "e": 3126, "s": 2905, "text": "The syntax stated below is for the Proxy API, where, target can be any sort of object like array, function or another proxy and handler is an object whose properties are functions. This defines the behavior of the proxy." }, { "code": null, "e": 3167, "s": 3126, "text": "const proxy = new Proxy(target,handler)\n" }, { "code": null, "e": 3377, "s": 3167, "text": "The handler object contains traps for Proxy. All traps are optional. If a trap has not been defined, the default behavior is to forward the operation to the target. Some common handler methods are as follows −" }, { "code": null, "e": 3405, "s": 3377, "text": "A trap for a function call." }, { "code": null, "e": 3434, "s": 3405, "text": "A trap for the new operator." }, { "code": null, "e": 3470, "s": 3434, "text": "A trap for getting property values." }, { "code": null, "e": 3506, "s": 3470, "text": "A trap for setting property values." }, { "code": null, "e": 3535, "s": 3506, "text": "TA trap for the in operator." }, { "code": null, "e": 3570, "s": 3535, "text": "\n 32 Lectures \n 3.5 hours \n" }, { "code": null, "e": 3584, "s": 3570, "text": " Sharad Kumar" }, { "code": null, "e": 3617, "s": 3584, "text": "\n 40 Lectures \n 5 hours \n" }, { "code": null, "e": 3635, "s": 3617, "text": " Richa Maheshwari" }, { "code": null, "e": 3668, "s": 3635, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 3682, "s": 3668, "text": " Anadi Sharma" }, { "code": null, "e": 3717, "s": 3682, "text": "\n 50 Lectures \n 6.5 hours \n" }, { "code": null, "e": 3734, "s": 3717, "text": " Gowthami Swarna" }, { "code": null, "e": 3767, "s": 3734, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 3783, "s": 3767, "text": " Deepti Trivedi" }, { "code": null, "e": 3818, "s": 3783, "text": "\n 31 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3826, "s": 3818, "text": " Shweta" }, { "code": null, "e": 3833, "s": 3826, "text": " Print" }, { "code": null, "e": 3844, "s": 3833, "text": " Add Notes" } ]
Break a long line into multiple lines in Python - GeeksforGeeks
23 Dec, 2020 Breaking a long line has nothing to do with the output, it is just trying to fix how our code appears. Writing a really long line in a single line makes code appear less clean and there are chances one may confuse it to be complex. Breaking down the same line can increase the readability of the code, rule out any confusion, and obviously makes it presentable. Usually, a line undergoes division after it crosses a certain amount of characters. This article discusses all the ways in which this can be achieved: Method 1: Using backslash A backslash(\) can be put between the line to make it appear separate like shown below. Also notice that all three cases produce exactly the same output only difference is in the way they are presented into the code: Example: Python3 print("BEFORE BREAKING:")print("How many times were you frustrated while looking out for a good collection of programming/ algorithm/ interview questions? What did you expect and what did you get? Geeks for geeks is a portal that has been created to provide well written, well thought and well explained solutions for selected questions.") print()print("AFTER BREAKING:")print("How many times were you frustrated while looking out "\ "for a good collection of programming/ algorithm/ "\ "interview questions? What did you expect and what "\ "did you get? Geeks for geeks is a portal that"\ " has been created to provide well written, we"\ "ll thought and well explained solutions for se"\ "lected questions.") print()line = "How many times were you frustrated while looking out "\ "for a good collection of programming/ algorithm/ "\ "interview questions? What did you expect and what "\ "did you get? Geeks for geeks is a portal that"\ " has been created to provide well written, we"\ "ll thought and well explained solutions for se"\ "lected questions."print("AFTER BREAKING USING A VARIABLE:")print(line) Output: BEFORE BREAKING: How many times were you frustrated while looking out for a good collection of programming/ algorithm/ interview questions? What did you expect and what did you get? Geeks for geeks is a portal that has been created to provide well written, well thought and well explained solutions for selected questions. AFTER BREAKING: How many times were you frustrated while looking out for a good collection of programming/ algorithm/ interview questions? What did you expect and what did you get? Geeks for geeks is a portal that has been created to provide well written, well thought and well explained solutions for selected questions. AFTER BREAKING USING A VARIABLE: How many times were you frustrated while looking out for a good collection of programming/ algorithm/ interview questions? What did you expect and what did you get? Geeks for geeks is a portal that has been created to provide well written, well thought and well explained solutions for selected questions. Method 2: Using string concatenation operator String concatenation operator (+), something so basic can easily replace backslashes in the above example to give out same output. Example: Python3 print("How many times were you" + " frustrated while looking" + " out for a good collection" + " of programming/ algorithm/" + "interview questions? What" + " did you expect and what " + "did you get? Geeks for gee" + "ks is a portal that has bee" + "n created to provide well wr" + "itten, well thought and wel" + "l explained solutions for se" + "lected questions.") Output: How many times were you frustrated while looking out for a good collection of programming/ algorithm/interview questions? What did you expect and what did you get? Geeks for geeks is a portal that has been created to provide well written, well thought and well explained solutions for selected questions. Method 3: Using parenthesis The same output can be achieved by keeping each fragment into parentheses and separating each fragment from each other using comma(,). Example: Python3 print(("How many times were you"), ("frustrated while looking"), ("out for a good collection"), ("of programming/ algorithm/"), ("interview questions? What"), ("did you expect and what"), ("did you get? Geeks for geeks"), ("is a portal that has been"), ("created to provide well"), ("written, well thought and well"), ("explained solutions for"), ("selected questions.")) Output: How many times were you frustrated while looking out for a good collection of programming/ algorithm/ interview questions? What did you expect and what did you get? Geeks for geeks is a portal that has been created to provide well written, well thought and well explained solutions for selected questions. python-basics Technical Scripter 2020 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? Selecting rows in pandas DataFrame based on conditions How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Get unique values from a list Defaultdict in Python Python OOPs Concepts Python | os.path.join() method Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24292, "s": 24264, "text": "\n23 Dec, 2020" }, { "code": null, "e": 24805, "s": 24292, "text": "Breaking a long line has nothing to do with the output, it is just trying to fix how our code appears. Writing a really long line in a single line makes code appear less clean and there are chances one may confuse it to be complex. Breaking down the same line can increase the readability of the code, rule out any confusion, and obviously makes it presentable. Usually, a line undergoes division after it crosses a certain amount of characters. This article discusses all the ways in which this can be achieved:" }, { "code": null, "e": 24831, "s": 24805, "text": "Method 1: Using backslash" }, { "code": null, "e": 25048, "s": 24831, "text": "A backslash(\\) can be put between the line to make it appear separate like shown below. Also notice that all three cases produce exactly the same output only difference is in the way they are presented into the code:" }, { "code": null, "e": 25057, "s": 25048, "text": "Example:" }, { "code": null, "e": 25065, "s": 25057, "text": "Python3" }, { "code": "print(\"BEFORE BREAKING:\")print(\"How many times were you frustrated while looking out for a good collection of programming/ algorithm/ interview questions? What did you expect and what did you get? Geeks for geeks is a portal that has been created to provide well written, well thought and well explained solutions for selected questions.\") print()print(\"AFTER BREAKING:\")print(\"How many times were you frustrated while looking out \"\\ \"for a good collection of programming/ algorithm/ \"\\ \"interview questions? What did you expect and what \"\\ \"did you get? Geeks for geeks is a portal that\"\\ \" has been created to provide well written, we\"\\ \"ll thought and well explained solutions for se\"\\ \"lected questions.\") print()line = \"How many times were you frustrated while looking out \"\\ \"for a good collection of programming/ algorithm/ \"\\ \"interview questions? What did you expect and what \"\\ \"did you get? Geeks for geeks is a portal that\"\\ \" has been created to provide well written, we\"\\ \"ll thought and well explained solutions for se\"\\ \"lected questions.\"print(\"AFTER BREAKING USING A VARIABLE:\")print(line)", "e": 26225, "s": 25065, "text": null }, { "code": null, "e": 26233, "s": 26225, "text": "Output:" }, { "code": null, "e": 26250, "s": 26233, "text": "BEFORE BREAKING:" }, { "code": null, "e": 26556, "s": 26250, "text": "How many times were you frustrated while looking out for a good collection of programming/ algorithm/ interview questions? What did you expect and what did you get? Geeks for geeks is a portal that has been created to provide well written, well thought and well explained solutions for selected questions." }, { "code": null, "e": 26572, "s": 26556, "text": "AFTER BREAKING:" }, { "code": null, "e": 26878, "s": 26572, "text": "How many times were you frustrated while looking out for a good collection of programming/ algorithm/ interview questions? What did you expect and what did you get? Geeks for geeks is a portal that has been created to provide well written, well thought and well explained solutions for selected questions." }, { "code": null, "e": 26911, "s": 26878, "text": "AFTER BREAKING USING A VARIABLE:" }, { "code": null, "e": 27217, "s": 26911, "text": "How many times were you frustrated while looking out for a good collection of programming/ algorithm/ interview questions? What did you expect and what did you get? Geeks for geeks is a portal that has been created to provide well written, well thought and well explained solutions for selected questions." }, { "code": null, "e": 27263, "s": 27217, "text": "Method 2: Using string concatenation operator" }, { "code": null, "e": 27394, "s": 27263, "text": "String concatenation operator (+), something so basic can easily replace backslashes in the above example to give out same output." }, { "code": null, "e": 27403, "s": 27394, "text": "Example:" }, { "code": null, "e": 27411, "s": 27403, "text": "Python3" }, { "code": "print(\"How many times were you\" + \" frustrated while looking\" + \" out for a good collection\" + \" of programming/ algorithm/\" + \"interview questions? What\" + \" did you expect and what \" + \"did you get? Geeks for gee\" + \"ks is a portal that has bee\" + \"n created to provide well wr\" + \"itten, well thought and wel\" + \"l explained solutions for se\" + \"lected questions.\")", "e": 27835, "s": 27411, "text": null }, { "code": null, "e": 27843, "s": 27835, "text": "Output:" }, { "code": null, "e": 28148, "s": 27843, "text": "How many times were you frustrated while looking out for a good collection of programming/ algorithm/interview questions? What did you expect and what did you get? Geeks for geeks is a portal that has been created to provide well written, well thought and well explained solutions for selected questions." }, { "code": null, "e": 28176, "s": 28148, "text": "Method 3: Using parenthesis" }, { "code": null, "e": 28311, "s": 28176, "text": "The same output can be achieved by keeping each fragment into parentheses and separating each fragment from each other using comma(,)." }, { "code": null, "e": 28320, "s": 28311, "text": "Example:" }, { "code": null, "e": 28328, "s": 28320, "text": "Python3" }, { "code": "print((\"How many times were you\"), (\"frustrated while looking\"), (\"out for a good collection\"), (\"of programming/ algorithm/\"), (\"interview questions? What\"), (\"did you expect and what\"), (\"did you get? Geeks for geeks\"), (\"is a portal that has been\"), (\"created to provide well\"), (\"written, well thought and well\"), (\"explained solutions for\"), (\"selected questions.\"))", "e": 28755, "s": 28328, "text": null }, { "code": null, "e": 28763, "s": 28755, "text": "Output:" }, { "code": null, "e": 29069, "s": 28763, "text": "How many times were you frustrated while looking out for a good collection of programming/ algorithm/ interview questions? What did you expect and what did you get? Geeks for geeks is a portal that has been created to provide well written, well thought and well explained solutions for selected questions." }, { "code": null, "e": 29083, "s": 29069, "text": "python-basics" }, { "code": null, "e": 29107, "s": 29083, "text": "Technical Scripter 2020" }, { "code": null, "e": 29114, "s": 29107, "text": "Python" }, { "code": null, "e": 29133, "s": 29114, "text": "Technical Scripter" }, { "code": null, "e": 29231, "s": 29133, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29240, "s": 29231, "text": "Comments" }, { "code": null, "e": 29253, "s": 29240, "text": "Old Comments" }, { "code": null, "e": 29285, "s": 29253, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29340, "s": 29285, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 29396, "s": 29340, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 29438, "s": 29396, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 29480, "s": 29438, "text": "Check if element exists in list in Python" }, { "code": null, "e": 29519, "s": 29480, "text": "Python | Get unique values from a list" }, { "code": null, "e": 29541, "s": 29519, "text": "Defaultdict in Python" }, { "code": null, "e": 29562, "s": 29541, "text": "Python OOPs Concepts" }, { "code": null, "e": 29593, "s": 29562, "text": "Python | os.path.join() method" } ]
N-Base modified Binary Search algorithm - GeeksforGeeks
28 Jan, 2022 N-Base modified Binary Search is an algorithm based on number bases that can be used to find an element in a sorted array arr[]. This algorithm is an extension of Bitwise binary search and has a similar running time. Examples: Input: arr[] = {0, 1, 4, 5, 8, 11, 15, 21, 45, 70, 100}, target = 45Output: 7Explanation: The value 45 is present at index 7 Input: arr[] = {1, 6, 8, 10}, target = 9Output: -1Explanation: The value 9 is not present in the given array. Intuition: All numbers of a number system can be expressed in another number systems having any number (e.g. 2, 3, 7) as base of that number system. For example, 7 of decimal number system can be expressed as (21)3 in a number system having base as 3. Therefore the concept of bitwise binary search can be implemented using any number N as base of a number system. Approach: The index for the target element is searched by adding powers of base (any positive integer starting from 2) to a sum (initially 0). When such a power is found, calculation is made to count the number of times it can be used to find the target index, and that value is added with the sum. The part of counting how many times a power can be used is similar to the “Bitwise binary search” from the binary search article. Define a base number, and a power of two greater or equal to the base (the power of two will help in counting how many times a power of base can be added to final index, efficiently)Compute the first power of the base (N) that is greater than the array size. ( Nk where k is an integer greater or equal to one and Xk is the first power of base greater or equal to the array size).Initialize an index (finId) as 0 which will store the final position where the target element should be at the end of all the iterations.Loop while computed power is greater than 0 and each time divide it by base value.Check how many times this power can be used and add that value to the finId.To check this, use the conditions mentioned below: Define a base number, and a power of two greater or equal to the base (the power of two will help in counting how many times a power of base can be added to final index, efficiently) Compute the first power of the base (N) that is greater than the array size. ( Nk where k is an integer greater or equal to one and Xk is the first power of base greater or equal to the array size). Initialize an index (finId) as 0 which will store the final position where the target element should be at the end of all the iterations. Loop while computed power is greater than 0 and each time divide it by base value.Check how many times this power can be used and add that value to the finId.To check this, use the conditions mentioned below: Check how many times this power can be used and add that value to the finId.To check this, use the conditions mentioned below: Check how many times this power can be used and add that value to the finId. To check this, use the conditions mentioned below: finId + power of base < array size(M) value at finId + power of base ≤ target While iteration is complete check if the value at final index is same as target or not. If it is not, then the value is not present in the array. Illustration: See the illustration below for better understanding. Illustration: arr[] = {1, 4, 5, 8, 11, 15, 21, 45, 70, 100}, array size(M) = 10, target = 45, base(N) = 3 Steps: Compute first power(power) of 3 (Base) greater than 10 (M), power = 27 in this case.Initialize a final index(finId) as 0 (position in arr[] where target value should be at the end).Now iterate through the powers of 3 (Base) that are less or equal to 27 and add them to the index as fallowing:1st iteration : finId = 0. power is 27 and can’t be used because finId + power > M. So, finId = 0.2nd iteration : finId = 0. power is 9 and can’t be used because element at finId + power > target i.e. arr[finId + power] > target. So finId = 0.3rd iteration : finId = 0. power is 3, this time power can be used because arr[finId + power] < target. Now count how many times 3 can be added to finId. In this case 3 can sum two times. finId after 3rd iteration will be 6 (finId += 3 + 3). 3 can’t be added more than 2 times because finId will pass the index where target value is. So finId = 0 + 3 + 3 = 6.4th iteration : finId = 6. power is 1, power can be used because arr[finId + power] ≤ target(45). Again count how many times 1 can be used. In this case 1 can be used only once. So add 1 only once with finId. So, finId = 6+1 = 7.after 4th iteration power is 0 so exit the loop.arr[7] = target. So the value is found at index 7. Compute first power(power) of 3 (Base) greater than 10 (M), power = 27 in this case. Initialize a final index(finId) as 0 (position in arr[] where target value should be at the end). Now iterate through the powers of 3 (Base) that are less or equal to 27 and add them to the index as fallowing:1st iteration : finId = 0. power is 27 and can’t be used because finId + power > M. So, finId = 0.2nd iteration : finId = 0. power is 9 and can’t be used because element at finId + power > target i.e. arr[finId + power] > target. So finId = 0.3rd iteration : finId = 0. power is 3, this time power can be used because arr[finId + power] < target. Now count how many times 3 can be added to finId. In this case 3 can sum two times. finId after 3rd iteration will be 6 (finId += 3 + 3). 3 can’t be added more than 2 times because finId will pass the index where target value is. So finId = 0 + 3 + 3 = 6.4th iteration : finId = 6. power is 1, power can be used because arr[finId + power] ≤ target(45). Again count how many times 1 can be used. In this case 1 can be used only once. So add 1 only once with finId. So, finId = 6+1 = 7. 1st iteration : finId = 0. power is 27 and can’t be used because finId + power > M. So, finId = 0.2nd iteration : finId = 0. power is 9 and can’t be used because element at finId + power > target i.e. arr[finId + power] > target. So finId = 0.3rd iteration : finId = 0. power is 3, this time power can be used because arr[finId + power] < target. Now count how many times 3 can be added to finId. In this case 3 can sum two times. finId after 3rd iteration will be 6 (finId += 3 + 3). 3 can’t be added more than 2 times because finId will pass the index where target value is. So finId = 0 + 3 + 3 = 6.4th iteration : finId = 6. power is 1, power can be used because arr[finId + power] ≤ target(45). Again count how many times 1 can be used. In this case 1 can be used only once. So add 1 only once with finId. So, finId = 6+1 = 7. 1st iteration : finId = 0. power is 27 and can’t be used because finId + power > M. So, finId = 0. 2nd iteration : finId = 0. power is 9 and can’t be used because element at finId + power > target i.e. arr[finId + power] > target. So finId = 0. 3rd iteration : finId = 0. power is 3, this time power can be used because arr[finId + power] < target. Now count how many times 3 can be added to finId. In this case 3 can sum two times. finId after 3rd iteration will be 6 (finId += 3 + 3). 3 can’t be added more than 2 times because finId will pass the index where target value is. So finId = 0 + 3 + 3 = 6. 4th iteration : finId = 6. power is 1, power can be used because arr[finId + power] ≤ target(45). Again count how many times 1 can be used. In this case 1 can be used only once. So add 1 only once with finId. So, finId = 6+1 = 7. after 4th iteration power is 0 so exit the loop. arr[7] = target. So the value is found at index 7. Notes: At each iteration power can be used maximum (Base – 1) timesBase can be any positive integer starting from 2Array needs to be sorted to perform this search algorithm At each iteration power can be used maximum (Base – 1) times Base can be any positive integer starting from 2 Array needs to be sorted to perform this search algorithm Below is the implementation of the above approach (in comparison with a classic binary search algorithm): C++ Java Python3 C# Javascript // C++ code to implement the above approach#include<bits/stdc++.h>using namespace std; #define N 3#define PowerOf2 4 int Numeric_Base_Search(int arr[], int M, int target){ unsigned long long i, step1, step2 = PowerOf2, times; // Find the first power of N // greater than the array size for (step1 = 1; step1 < M; step1 *= N); for (i = 0; step1; step1 /= N) // Each time a power can be used // count how many times // it can be used if (i + step1 < M && arr[i + step1] <= target){ for (times = 1; step2; step2 >>= 1) if (i + (step1 * (times + step2)) < M && arr[i + (step1 * (times + step2))] <= target) times += step2; step2 = PowerOf2; // Add to final result // how many times // can the power be used i += times * step1; } // Return the index // if the element is present in array // else return -1 return arr[i] == target ? i : -1;} // Driver codeint main(){ int arr[10] = {1, 4, 5, 8, 11, 15, 21, 45, 70, 100}; int target = 45, M = 10; int answer = Numeric_Base_Search(arr, M, target); cout<<answer; return 0;} // Java code to implement the above approachclass GFG { static int N = 3; static int PowerOf2 = 4; static int Numeric_Base_Search(int[] arr, int M, int target) { int i, step1, step2 = PowerOf2, times; // Find the first power of N // greater than the array size for (step1 = 1; step1 < M; step1 *= N) ; for (i = 0; step1 > 0; step1 /= N) { // Each time a power can be used // count how many times // it can be used if (i + step1 < M && arr[i + step1] <= target) { for (times = 1; step2 > 0; step2 >>= 1) if (i + (step1 * (times + step2)) < M && arr[i + (step1 * (times + step2))] <= target) times += step2; step2 = PowerOf2; // Add to final result // how many times // can the power be used i += times * step1; } } // Return the index // if the element is present in array // else return -1 return arr[i] == target ? i : -1; } // Driver code public static void main(String args[]) { int[] arr = { 1, 4, 5, 8, 11, 15, 21, 45, 70, 100 }; int target = 45, M = 10; int answer = Numeric_Base_Search(arr, M, target); System.out.println(answer); }} // This code is contributed by Saurabh Jaiswal # Python code for the above approachN = 3PowerOf2 = 4 def Numeric_Base_Search(arr, M, target): i = None step1 = None step2 = PowerOf2 times = None # Find the first power of N # greater than the array size step1 = 1 while(step1 < M): step1 *= N i = 0 while(step1): step1 = step1 // N # Each time a power can be used # count how many times # it can be used if (i + step1 < M and arr[i + step1] <= target): times=1 while(step2): step2 >>= 1 if (i + (step1 * (times + step2)) < M and arr[i + (step1 * (times + step2))] <= target): times += step2; step2 = PowerOf2; # Add to final result # how many times # can the power be used i += times * step1 # Return the index # if the element is present in array # else return -1 return i if arr[i] == target else -1 # Driver codearr = [1, 4, 5, 8, 11, 15, 21, 45, 70, 100]target = 45M = 10answer = Numeric_Base_Search(arr, M, target)print(answer) # This code is contributed by Saurabh Jaiswal // C# code to implement the above approachusing System;class GFG { static int N = 3; static int PowerOf2 = 4; static int Numeric_Base_Search(int[] arr, int M, int target) { int i, step1, step2 = PowerOf2, times; // Find the first power of N // greater than the array size for (step1 = 1; step1 < M; step1 *= N) ; for (i = 0; step1 > 0; step1 /= N) { // Each time a power can be used // count how many times // it can be used if (i + step1 < M && arr[i + step1] <= target) { for (times = 1; step2 > 0; step2 >>= 1) if (i + (step1 * (times + step2)) < M && arr[i + (step1 * (times + step2))] <= target) times += step2; step2 = PowerOf2; // Add to final result // how many times // can the power be used i += times * step1; } } // Return the index // if the element is present in array // else return -1 return arr[i] == target ? i : -1; } // Driver code public static void Main() { int[] arr = { 1, 4, 5, 8, 11, 15, 21, 45, 70, 100 }; int target = 45, M = 10; int answer = Numeric_Base_Search(arr, M, target); Console.WriteLine(answer); }} // This code is contributed by ukasp. <script> // JavaScript code for the above approach let N = 3 let PowerOf2 = 4 function Numeric_Base_Search(arr, M, target) { let i, step1, step2 = PowerOf2, times; // Find the first power of N // greater than the array size for (step1 = 1; step1 < M; step1 *= N); for (i = 0; step1; step1 /= N) // Each time a power can be used // count how many times // it can be used if (i + step1 < M && arr[i + step1] <= target) { for (times = 1; step2; step2 >>= 1) if (i + (step1 * (times + step2)) < M && arr[i + (step1 * (times + step2))] <= target) times += step2; step2 = PowerOf2; // Add to final result // how many times // can the power be used i += times * step1; } // Return the index // if the element is present in array // else return -1 return arr[i] == target ? i : -1; } // Driver code let arr = [1, 4, 5, 8, 11, 15, 21, 45, 70, 100]; let target = 45, M = 10; let answer = Numeric_Base_Search(arr, M, target); document.write(answer); // This code is contributed by Potta Lokesh </script> 7 Time Complexity: O(log N M * log 2 N)Auxiliary Space: O(1) lokeshpotta20 gfgking ukasp _saurabh_jaiswal Algo-Geek 2021 Algorithms-Searching base-conversion Binary Search Algo Geek Bit Magic Mathematical Searching Searching Mathematical Bit Magic Binary Search Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Check if an edge is a part of any Minimum Spanning Tree Bit Manipulation technique to replace boolean arrays of fixed size less than 64 Check if the given string is valid English word or not Divide given number into two even parts Sort strings on the basis of their numeric part Bitwise Operators in C/C++ Left Shift and Right Shift Operators in C/C++ Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Count set bits in an integer How to swap two numbers without using a temporary variable?
[ { "code": null, "e": 27683, "s": 27655, "text": "\n28 Jan, 2022" }, { "code": null, "e": 27900, "s": 27683, "text": "N-Base modified Binary Search is an algorithm based on number bases that can be used to find an element in a sorted array arr[]. This algorithm is an extension of Bitwise binary search and has a similar running time." }, { "code": null, "e": 27911, "s": 27900, "text": "Examples: " }, { "code": null, "e": 28036, "s": 27911, "text": "Input: arr[] = {0, 1, 4, 5, 8, 11, 15, 21, 45, 70, 100}, target = 45Output: 7Explanation: The value 45 is present at index 7" }, { "code": null, "e": 28146, "s": 28036, "text": "Input: arr[] = {1, 6, 8, 10}, target = 9Output: -1Explanation: The value 9 is not present in the given array." }, { "code": null, "e": 28511, "s": 28146, "text": "Intuition: All numbers of a number system can be expressed in another number systems having any number (e.g. 2, 3, 7) as base of that number system. For example, 7 of decimal number system can be expressed as (21)3 in a number system having base as 3. Therefore the concept of bitwise binary search can be implemented using any number N as base of a number system." }, { "code": null, "e": 28940, "s": 28511, "text": "Approach: The index for the target element is searched by adding powers of base (any positive integer starting from 2) to a sum (initially 0). When such a power is found, calculation is made to count the number of times it can be used to find the target index, and that value is added with the sum. The part of counting how many times a power can be used is similar to the “Bitwise binary search” from the binary search article." }, { "code": null, "e": 29666, "s": 28940, "text": "Define a base number, and a power of two greater or equal to the base (the power of two will help in counting how many times a power of base can be added to final index, efficiently)Compute the first power of the base (N) that is greater than the array size. ( Nk where k is an integer greater or equal to one and Xk is the first power of base greater or equal to the array size).Initialize an index (finId) as 0 which will store the final position where the target element should be at the end of all the iterations.Loop while computed power is greater than 0 and each time divide it by base value.Check how many times this power can be used and add that value to the finId.To check this, use the conditions mentioned below:" }, { "code": null, "e": 29849, "s": 29666, "text": "Define a base number, and a power of two greater or equal to the base (the power of two will help in counting how many times a power of base can be added to final index, efficiently)" }, { "code": null, "e": 30048, "s": 29849, "text": "Compute the first power of the base (N) that is greater than the array size. ( Nk where k is an integer greater or equal to one and Xk is the first power of base greater or equal to the array size)." }, { "code": null, "e": 30186, "s": 30048, "text": "Initialize an index (finId) as 0 which will store the final position where the target element should be at the end of all the iterations." }, { "code": null, "e": 30395, "s": 30186, "text": "Loop while computed power is greater than 0 and each time divide it by base value.Check how many times this power can be used and add that value to the finId.To check this, use the conditions mentioned below:" }, { "code": null, "e": 30522, "s": 30395, "text": "Check how many times this power can be used and add that value to the finId.To check this, use the conditions mentioned below:" }, { "code": null, "e": 30599, "s": 30522, "text": "Check how many times this power can be used and add that value to the finId." }, { "code": null, "e": 30650, "s": 30599, "text": "To check this, use the conditions mentioned below:" }, { "code": null, "e": 30688, "s": 30650, "text": "finId + power of base < array size(M)" }, { "code": null, "e": 30728, "s": 30688, "text": "value at finId + power of base ≤ target" }, { "code": null, "e": 30874, "s": 30728, "text": "While iteration is complete check if the value at final index is same as target or not. If it is not, then the value is not present in the array." }, { "code": null, "e": 30941, "s": 30874, "text": "Illustration: See the illustration below for better understanding." }, { "code": null, "e": 31047, "s": 30941, "text": "Illustration: arr[] = {1, 4, 5, 8, 11, 15, 21, 45, 70, 100}, array size(M) = 10, target = 45, base(N) = 3" }, { "code": null, "e": 31054, "s": 31047, "text": "Steps:" }, { "code": null, "e": 32276, "s": 31054, "text": "Compute first power(power) of 3 (Base) greater than 10 (M), power = 27 in this case.Initialize a final index(finId) as 0 (position in arr[] where target value should be at the end).Now iterate through the powers of 3 (Base) that are less or equal to 27 and add them to the index as fallowing:1st iteration : finId = 0. power is 27 and can’t be used because finId + power > M. So, finId = 0.2nd iteration : finId = 0. power is 9 and can’t be used because element at finId + power > target i.e. arr[finId + power] > target. So finId = 0.3rd iteration : finId = 0. power is 3, this time power can be used because arr[finId + power] < target. Now count how many times 3 can be added to finId. In this case 3 can sum two times. finId after 3rd iteration will be 6 (finId += 3 + 3). 3 can’t be added more than 2 times because finId will pass the index where target value is. So finId = 0 + 3 + 3 = 6.4th iteration : finId = 6. power is 1, power can be used because arr[finId + power] ≤ target(45). Again count how many times 1 can be used. In this case 1 can be used only once. So add 1 only once with finId. So, finId = 6+1 = 7.after 4th iteration power is 0 so exit the loop.arr[7] = target. So the value is found at index 7." }, { "code": null, "e": 32361, "s": 32276, "text": "Compute first power(power) of 3 (Base) greater than 10 (M), power = 27 in this case." }, { "code": null, "e": 32459, "s": 32361, "text": "Initialize a final index(finId) as 0 (position in arr[] where target value should be at the end)." }, { "code": null, "e": 33402, "s": 32459, "text": "Now iterate through the powers of 3 (Base) that are less or equal to 27 and add them to the index as fallowing:1st iteration : finId = 0. power is 27 and can’t be used because finId + power > M. So, finId = 0.2nd iteration : finId = 0. power is 9 and can’t be used because element at finId + power > target i.e. arr[finId + power] > target. So finId = 0.3rd iteration : finId = 0. power is 3, this time power can be used because arr[finId + power] < target. Now count how many times 3 can be added to finId. In this case 3 can sum two times. finId after 3rd iteration will be 6 (finId += 3 + 3). 3 can’t be added more than 2 times because finId will pass the index where target value is. So finId = 0 + 3 + 3 = 6.4th iteration : finId = 6. power is 1, power can be used because arr[finId + power] ≤ target(45). Again count how many times 1 can be used. In this case 1 can be used only once. So add 1 only once with finId. So, finId = 6+1 = 7." }, { "code": null, "e": 34234, "s": 33402, "text": "1st iteration : finId = 0. power is 27 and can’t be used because finId + power > M. So, finId = 0.2nd iteration : finId = 0. power is 9 and can’t be used because element at finId + power > target i.e. arr[finId + power] > target. So finId = 0.3rd iteration : finId = 0. power is 3, this time power can be used because arr[finId + power] < target. Now count how many times 3 can be added to finId. In this case 3 can sum two times. finId after 3rd iteration will be 6 (finId += 3 + 3). 3 can’t be added more than 2 times because finId will pass the index where target value is. So finId = 0 + 3 + 3 = 6.4th iteration : finId = 6. power is 1, power can be used because arr[finId + power] ≤ target(45). Again count how many times 1 can be used. In this case 1 can be used only once. So add 1 only once with finId. So, finId = 6+1 = 7." }, { "code": null, "e": 34333, "s": 34234, "text": "1st iteration : finId = 0. power is 27 and can’t be used because finId + power > M. So, finId = 0." }, { "code": null, "e": 34479, "s": 34333, "text": "2nd iteration : finId = 0. power is 9 and can’t be used because element at finId + power > target i.e. arr[finId + power] > target. So finId = 0." }, { "code": null, "e": 34839, "s": 34479, "text": "3rd iteration : finId = 0. power is 3, this time power can be used because arr[finId + power] < target. Now count how many times 3 can be added to finId. In this case 3 can sum two times. finId after 3rd iteration will be 6 (finId += 3 + 3). 3 can’t be added more than 2 times because finId will pass the index where target value is. So finId = 0 + 3 + 3 = 6." }, { "code": null, "e": 35069, "s": 34839, "text": "4th iteration : finId = 6. power is 1, power can be used because arr[finId + power] ≤ target(45). Again count how many times 1 can be used. In this case 1 can be used only once. So add 1 only once with finId. So, finId = 6+1 = 7." }, { "code": null, "e": 35118, "s": 35069, "text": "after 4th iteration power is 0 so exit the loop." }, { "code": null, "e": 35169, "s": 35118, "text": "arr[7] = target. So the value is found at index 7." }, { "code": null, "e": 35176, "s": 35169, "text": "Notes:" }, { "code": null, "e": 35342, "s": 35176, "text": "At each iteration power can be used maximum (Base – 1) timesBase can be any positive integer starting from 2Array needs to be sorted to perform this search algorithm" }, { "code": null, "e": 35403, "s": 35342, "text": "At each iteration power can be used maximum (Base – 1) times" }, { "code": null, "e": 35452, "s": 35403, "text": "Base can be any positive integer starting from 2" }, { "code": null, "e": 35510, "s": 35452, "text": "Array needs to be sorted to perform this search algorithm" }, { "code": null, "e": 35616, "s": 35510, "text": "Below is the implementation of the above approach (in comparison with a classic binary search algorithm):" }, { "code": null, "e": 35620, "s": 35616, "text": "C++" }, { "code": null, "e": 35625, "s": 35620, "text": "Java" }, { "code": null, "e": 35633, "s": 35625, "text": "Python3" }, { "code": null, "e": 35636, "s": 35633, "text": "C#" }, { "code": null, "e": 35647, "s": 35636, "text": "Javascript" }, { "code": "// C++ code to implement the above approach#include<bits/stdc++.h>using namespace std; #define N 3#define PowerOf2 4 int Numeric_Base_Search(int arr[], int M, int target){ unsigned long long i, step1, step2 = PowerOf2, times; // Find the first power of N // greater than the array size for (step1 = 1; step1 < M; step1 *= N); for (i = 0; step1; step1 /= N) // Each time a power can be used // count how many times // it can be used if (i + step1 < M && arr[i + step1] <= target){ for (times = 1; step2; step2 >>= 1) if (i + (step1 * (times + step2)) < M && arr[i + (step1 * (times + step2))] <= target) times += step2; step2 = PowerOf2; // Add to final result // how many times // can the power be used i += times * step1; } // Return the index // if the element is present in array // else return -1 return arr[i] == target ? i : -1;} // Driver codeint main(){ int arr[10] = {1, 4, 5, 8, 11, 15, 21, 45, 70, 100}; int target = 45, M = 10; int answer = Numeric_Base_Search(arr, M, target); cout<<answer; return 0;}", "e": 37027, "s": 35647, "text": null }, { "code": "// Java code to implement the above approachclass GFG { static int N = 3; static int PowerOf2 = 4; static int Numeric_Base_Search(int[] arr, int M, int target) { int i, step1, step2 = PowerOf2, times; // Find the first power of N // greater than the array size for (step1 = 1; step1 < M; step1 *= N) ; for (i = 0; step1 > 0; step1 /= N) { // Each time a power can be used // count how many times // it can be used if (i + step1 < M && arr[i + step1] <= target) { for (times = 1; step2 > 0; step2 >>= 1) if (i + (step1 * (times + step2)) < M && arr[i + (step1 * (times + step2))] <= target) times += step2; step2 = PowerOf2; // Add to final result // how many times // can the power be used i += times * step1; } } // Return the index // if the element is present in array // else return -1 return arr[i] == target ? i : -1; } // Driver code public static void main(String args[]) { int[] arr = { 1, 4, 5, 8, 11, 15, 21, 45, 70, 100 }; int target = 45, M = 10; int answer = Numeric_Base_Search(arr, M, target); System.out.println(answer); }} // This code is contributed by Saurabh Jaiswal", "e": 38580, "s": 37027, "text": null }, { "code": "# Python code for the above approachN = 3PowerOf2 = 4 def Numeric_Base_Search(arr, M, target): i = None step1 = None step2 = PowerOf2 times = None # Find the first power of N # greater than the array size step1 = 1 while(step1 < M): step1 *= N i = 0 while(step1): step1 = step1 // N # Each time a power can be used # count how many times # it can be used if (i + step1 < M and arr[i + step1] <= target): times=1 while(step2): step2 >>= 1 if (i + (step1 * (times + step2)) < M and arr[i + (step1 * (times + step2))] <= target): times += step2; step2 = PowerOf2; # Add to final result # how many times # can the power be used i += times * step1 # Return the index # if the element is present in array # else return -1 return i if arr[i] == target else -1 # Driver codearr = [1, 4, 5, 8, 11, 15, 21, 45, 70, 100]target = 45M = 10answer = Numeric_Base_Search(arr, M, target)print(answer) # This code is contributed by Saurabh Jaiswal", "e": 39740, "s": 38580, "text": null }, { "code": "// C# code to implement the above approachusing System;class GFG { static int N = 3; static int PowerOf2 = 4; static int Numeric_Base_Search(int[] arr, int M, int target) { int i, step1, step2 = PowerOf2, times; // Find the first power of N // greater than the array size for (step1 = 1; step1 < M; step1 *= N) ; for (i = 0; step1 > 0; step1 /= N) { // Each time a power can be used // count how many times // it can be used if (i + step1 < M && arr[i + step1] <= target) { for (times = 1; step2 > 0; step2 >>= 1) if (i + (step1 * (times + step2)) < M && arr[i + (step1 * (times + step2))] <= target) times += step2; step2 = PowerOf2; // Add to final result // how many times // can the power be used i += times * step1; } } // Return the index // if the element is present in array // else return -1 return arr[i] == target ? i : -1; } // Driver code public static void Main() { int[] arr = { 1, 4, 5, 8, 11, 15, 21, 45, 70, 100 }; int target = 45, M = 10; int answer = Numeric_Base_Search(arr, M, target); Console.WriteLine(answer); }} // This code is contributed by ukasp.", "e": 41273, "s": 39740, "text": null }, { "code": "<script> // JavaScript code for the above approach let N = 3 let PowerOf2 = 4 function Numeric_Base_Search(arr, M, target) { let i, step1, step2 = PowerOf2, times; // Find the first power of N // greater than the array size for (step1 = 1; step1 < M; step1 *= N); for (i = 0; step1; step1 /= N) // Each time a power can be used // count how many times // it can be used if (i + step1 < M && arr[i + step1] <= target) { for (times = 1; step2; step2 >>= 1) if (i + (step1 * (times + step2)) < M && arr[i + (step1 * (times + step2))] <= target) times += step2; step2 = PowerOf2; // Add to final result // how many times // can the power be used i += times * step1; } // Return the index // if the element is present in array // else return -1 return arr[i] == target ? i : -1; } // Driver code let arr = [1, 4, 5, 8, 11, 15, 21, 45, 70, 100]; let target = 45, M = 10; let answer = Numeric_Base_Search(arr, M, target); document.write(answer); // This code is contributed by Potta Lokesh </script>", "e": 42581, "s": 41273, "text": null }, { "code": null, "e": 42586, "s": 42584, "text": "7" }, { "code": null, "e": 42647, "s": 42588, "text": "Time Complexity: O(log N M * log 2 N)Auxiliary Space: O(1)" }, { "code": null, "e": 42663, "s": 42649, "text": "lokeshpotta20" }, { "code": null, "e": 42671, "s": 42663, "text": "gfgking" }, { "code": null, "e": 42677, "s": 42671, "text": "ukasp" }, { "code": null, "e": 42694, "s": 42677, "text": "_saurabh_jaiswal" }, { "code": null, "e": 42709, "s": 42694, "text": "Algo-Geek 2021" }, { "code": null, "e": 42730, "s": 42709, "text": "Algorithms-Searching" }, { "code": null, "e": 42746, "s": 42730, "text": "base-conversion" }, { "code": null, "e": 42760, "s": 42746, "text": "Binary Search" }, { "code": null, "e": 42770, "s": 42760, "text": "Algo Geek" }, { "code": null, "e": 42780, "s": 42770, "text": "Bit Magic" }, { "code": null, "e": 42793, "s": 42780, "text": "Mathematical" }, { "code": null, "e": 42803, "s": 42793, "text": "Searching" }, { "code": null, "e": 42813, "s": 42803, "text": "Searching" }, { "code": null, "e": 42826, "s": 42813, "text": "Mathematical" }, { "code": null, "e": 42836, "s": 42826, "text": "Bit Magic" }, { "code": null, "e": 42850, "s": 42836, "text": "Binary Search" }, { "code": null, "e": 42948, "s": 42850, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 43004, "s": 42948, "text": "Check if an edge is a part of any Minimum Spanning Tree" }, { "code": null, "e": 43084, "s": 43004, "text": "Bit Manipulation technique to replace boolean arrays of fixed size less than 64" }, { "code": null, "e": 43139, "s": 43084, "text": "Check if the given string is valid English word or not" }, { "code": null, "e": 43179, "s": 43139, "text": "Divide given number into two even parts" }, { "code": null, "e": 43227, "s": 43179, "text": "Sort strings on the basis of their numeric part" }, { "code": null, "e": 43254, "s": 43227, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 43300, "s": 43254, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 43368, "s": 43300, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 43397, "s": 43368, "text": "Count set bits in an integer" } ]
Convert.ToSingle Method in C#
Convert a specified value to a single-precision floating-point number using the Convert.ToSingle() method in C#. Here is our bool − bool boolVal = false; Now, let us use the ToSingle() method to convert the value to a single precision floating-point. float floatVal; floatVal = Convert.ToSingle(boolVal); Live Demo using System; public class Demo { public static void Main() { bool boolVal = false; float floatVal; floatVal = Convert.ToSingle(boolVal); Console.WriteLine("Converted {0} to {1}", boolVal, floatVal); } } Converted False to 0
[ { "code": null, "e": 1175, "s": 1062, "text": "Convert a specified value to a single-precision floating-point number using the Convert.ToSingle() method in C#." }, { "code": null, "e": 1194, "s": 1175, "text": "Here is our bool −" }, { "code": null, "e": 1216, "s": 1194, "text": "bool boolVal = false;" }, { "code": null, "e": 1313, "s": 1216, "text": "Now, let us use the ToSingle() method to convert the value to a single precision floating-point." }, { "code": null, "e": 1367, "s": 1313, "text": "float floatVal;\nfloatVal = Convert.ToSingle(boolVal);" }, { "code": null, "e": 1378, "s": 1367, "text": " Live Demo" }, { "code": null, "e": 1612, "s": 1378, "text": "using System;\npublic class Demo {\n public static void Main() {\n bool boolVal = false;\n float floatVal;\n floatVal = Convert.ToSingle(boolVal);\n Console.WriteLine(\"Converted {0} to {1}\", boolVal, floatVal);\n }\n}" }, { "code": null, "e": 1633, "s": 1612, "text": "Converted False to 0" } ]
Bootstrap 5 alpha | Icons Library - GeeksforGeeks
14 Aug, 2020 For the very first time, Bootstrap has its own icon library, custom-designed and built for bootstrap components and documentation. Bootstrap Icons are designed to figure with Bootstrap components, from form controls to navigation. Bootstrap Icons are SVGs, in order that they scale quickly and simply and may be styled with CSS. While they’re built for Bootstrap, they’ll add any project. They’re open-sourced under the MIT license, so you’re free to download, use, and customize as you need. How to Install: Bootstrap icons are published to npm, but they can also be downloaded if needed. Install Bootstrap Icons via command line with npm. npm install bootstrap-icons Usage: Bootstrap Icons are SVGs. So, you can include in your HTML code in various ways on the basis of the type of your project that you are working on. Copy paste SVGs as Embedded HTMLSVG Sprite with <use> elementAs an External Image Copy paste SVGs as Embedded HTML SVG Sprite with <use> element As an External Image Note: Bootstrap Icons include a width and height of “1 em” by default to allow for easy resizing via font-size. Copy paste SVGs as Embedded HTML : Embed your icons within the HTML of your page (as opposed to an external image file). Here we’ve used a custom width and height.<svg class="bi bi-chevron-right " width="64" height="64" viewBox="0 0 20 20" fill="currentColor" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" d="M6.646 3.646a.5.5 0 01.708 0l6 6a.5.5 0 010 .708l-6 6a.5.5 0 01-.708-.708L12.293 10 6.646 4.354a.5.5 0 010-.708z"/></svg>Example:<!DOCTYPE html><html lang="en"> <head> <title>Bootstrap Cards</title> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/v5.0.0/css/bootstrap.min.css" /> </head> <body> <svg class="bi bi-chevron-right" width="64" height="64" viewBox="0 0 20 20" fill="currentColor" xmlns="http://www.w3.org/2000/svg"> <path fill-rule="evenodd" d="M6.646 3.646a.5.5 0 01.708 0l6 6a.5.5 0 010 .708l-6 6a.5.5 0 01-.708-.708L12.293 10 6.646 4.354a.5.5 0 010-.708z" /> </svg> </body></html>Output: Copy paste SVGs as Embedded HTML : Embed your icons within the HTML of your page (as opposed to an external image file). Here we’ve used a custom width and height. <svg class="bi bi-chevron-right " width="64" height="64" viewBox="0 0 20 20" fill="currentColor" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" d="M6.646 3.646a.5.5 0 01.708 0l6 6a.5.5 0 010 .708l-6 6a.5.5 0 01-.708-.708L12.293 10 6.646 4.354a.5.5 0 010-.708z"/></svg> Example: <!DOCTYPE html><html lang="en"> <head> <title>Bootstrap Cards</title> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/v5.0.0/css/bootstrap.min.css" /> </head> <body> <svg class="bi bi-chevron-right" width="64" height="64" viewBox="0 0 20 20" fill="currentColor" xmlns="http://www.w3.org/2000/svg"> <path fill-rule="evenodd" d="M6.646 3.646a.5.5 0 01.708 0l6 6a.5.5 0 010 .708l-6 6a.5.5 0 01-.708-.708L12.293 10 6.646 4.354a.5.5 0 010-.708z" /> </svg> </body></html> Output: SVG Sprite with <use> element: Use the SVG sprite to insert any icon through the <use> element. Use the icon’s filename as the fragment identifier (e.g., heart is #heart). SVG sprites allow you to reference an external file similar to an <img> element, but with the power of currentColor for easy theming.Example:<svg class="bi" width="40" height="40" fill="currentColor"> <use xlink:href="bootstrap-icons.svg#heart-fill"/></svg><svg class="bi" width="40" height="40" fill="currentColor"> <use xlink:href="bootstrap-icons.svg#toggles"/></svg><svg class="bi" width="40" height="40" fill="currentColor"> <use xlink:href="bootstrap-icons.svg#shop"/></svg>Output: SVG Sprite with <use> element: Use the SVG sprite to insert any icon through the <use> element. Use the icon’s filename as the fragment identifier (e.g., heart is #heart). SVG sprites allow you to reference an external file similar to an <img> element, but with the power of currentColor for easy theming. Example: <svg class="bi" width="40" height="40" fill="currentColor"> <use xlink:href="bootstrap-icons.svg#heart-fill"/></svg><svg class="bi" width="40" height="40" fill="currentColor"> <use xlink:href="bootstrap-icons.svg#toggles"/></svg><svg class="bi" width="40" height="40" fill="currentColor"> <use xlink:href="bootstrap-icons.svg#shop"/></svg> Output: As an External Image: Copy the Bootstrap icons SVGs to any directory of your choice and reference them like normal images with the <img> tag.Example:<img src="/Icons/img/bootstrap.svg" alt="" width="40" height="40" title="Icons">Output: As an External Image: Copy the Bootstrap icons SVGs to any directory of your choice and reference them like normal images with the <img> tag. Example: <img src="/Icons/img/bootstrap.svg" alt="" width="40" height="40" title="Icons"> Output: Styling of Icons:For styling of Icons, consider them same as text. Color can also be changed by using a .text-* class or custom CSS.Example:<svg class="bi bi-alert-triangle text-success " width="40" height="40" viewBox="0 0 20 20" fill="currentColor" xmlns="http://www.w3.org/2000/svg"> .....</svg>Output: For styling of Icons, consider them same as text. Color can also be changed by using a .text-* class or custom CSS. Example: <svg class="bi bi-alert-triangle text-success " width="40" height="40" viewBox="0 0 20 20" fill="currentColor" xmlns="http://www.w3.org/2000/svg"> .....</svg> Output: Bootstrap-Misc Bootstrap Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to change navigation bar color in Bootstrap ? Form validation using jQuery How to align navbar items to the right in Bootstrap 4 ? How to pass data into a bootstrap modal? How to Show Images on Click using HTML ? Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28360, "s": 28332, "text": "\n14 Aug, 2020" }, { "code": null, "e": 28491, "s": 28360, "text": "For the very first time, Bootstrap has its own icon library, custom-designed and built for bootstrap components and documentation." }, { "code": null, "e": 28853, "s": 28491, "text": "Bootstrap Icons are designed to figure with Bootstrap components, from form controls to navigation. Bootstrap Icons are SVGs, in order that they scale quickly and simply and may be styled with CSS. While they’re built for Bootstrap, they’ll add any project. They’re open-sourced under the MIT license, so you’re free to download, use, and customize as you need." }, { "code": null, "e": 28869, "s": 28853, "text": "How to Install:" }, { "code": null, "e": 28950, "s": 28869, "text": "Bootstrap icons are published to npm, but they can also be downloaded if needed." }, { "code": null, "e": 29001, "s": 28950, "text": "Install Bootstrap Icons via command line with npm." }, { "code": null, "e": 29029, "s": 29001, "text": "npm install bootstrap-icons" }, { "code": null, "e": 29036, "s": 29029, "text": "Usage:" }, { "code": null, "e": 29182, "s": 29036, "text": "Bootstrap Icons are SVGs. So, you can include in your HTML code in various ways on the basis of the type of your project that you are working on." }, { "code": null, "e": 29264, "s": 29182, "text": "Copy paste SVGs as Embedded HTMLSVG Sprite with <use> elementAs an External Image" }, { "code": null, "e": 29297, "s": 29264, "text": "Copy paste SVGs as Embedded HTML" }, { "code": null, "e": 29327, "s": 29297, "text": "SVG Sprite with <use> element" }, { "code": null, "e": 29348, "s": 29327, "text": "As an External Image" }, { "code": null, "e": 29460, "s": 29348, "text": "Note: Bootstrap Icons include a width and height of “1 em” by default to allow for easy resizing via font-size." }, { "code": null, "e": 30734, "s": 29460, "text": "Copy paste SVGs as Embedded HTML : Embed your icons within the HTML of your page (as opposed to an external image file). Here we’ve used a custom width and height.<svg class=\"bi bi-chevron-right \" width=\"64\" height=\"64\" viewBox=\"0 0 20 20\" fill=\"currentColor\" xmlns=\"http://www.w3.org/2000/svg\"><path fill-rule=\"evenodd\" d=\"M6.646 3.646a.5.5 0 01.708 0l6 6a.5.5 0 010 .708l-6 6a.5.5 0 01-.708-.708L12.293 10 6.646 4.354a.5.5 0 010-.708z\"/></svg>Example:<!DOCTYPE html><html lang=\"en\"> <head> <title>Bootstrap Cards</title> <meta charset=\"utf-8\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" /> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/v5.0.0/css/bootstrap.min.css\" /> </head> <body> <svg class=\"bi bi-chevron-right\" width=\"64\" height=\"64\" viewBox=\"0 0 20 20\" fill=\"currentColor\" xmlns=\"http://www.w3.org/2000/svg\"> <path fill-rule=\"evenodd\" d=\"M6.646 3.646a.5.5 0 01.708 0l6 6a.5.5 0 010 .708l-6 6a.5.5 0 01-.708-.708L12.293 10 6.646 4.354a.5.5 0 010-.708z\" /> </svg> </body></html>Output:" }, { "code": null, "e": 30898, "s": 30734, "text": "Copy paste SVGs as Embedded HTML : Embed your icons within the HTML of your page (as opposed to an external image file). Here we’ve used a custom width and height." }, { "code": "<svg class=\"bi bi-chevron-right \" width=\"64\" height=\"64\" viewBox=\"0 0 20 20\" fill=\"currentColor\" xmlns=\"http://www.w3.org/2000/svg\"><path fill-rule=\"evenodd\" d=\"M6.646 3.646a.5.5 0 01.708 0l6 6a.5.5 0 010 .708l-6 6a.5.5 0 01-.708-.708L12.293 10 6.646 4.354a.5.5 0 010-.708z\"/></svg>", "e": 31205, "s": 30898, "text": null }, { "code": null, "e": 31214, "s": 31205, "text": "Example:" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <title>Bootstrap Cards</title> <meta charset=\"utf-8\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" /> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/v5.0.0/css/bootstrap.min.css\" /> </head> <body> <svg class=\"bi bi-chevron-right\" width=\"64\" height=\"64\" viewBox=\"0 0 20 20\" fill=\"currentColor\" xmlns=\"http://www.w3.org/2000/svg\"> <path fill-rule=\"evenodd\" d=\"M6.646 3.646a.5.5 0 01.708 0l6 6a.5.5 0 010 .708l-6 6a.5.5 0 01-.708-.708L12.293 10 6.646 4.354a.5.5 0 010-.708z\" /> </svg> </body></html>", "e": 32004, "s": 31214, "text": null }, { "code": null, "e": 32012, "s": 32004, "text": "Output:" }, { "code": null, "e": 32690, "s": 32012, "text": "SVG Sprite with <use> element: Use the SVG sprite to insert any icon through the <use> element. Use the icon’s filename as the fragment identifier (e.g., heart is #heart). SVG sprites allow you to reference an external file similar to an <img> element, but with the power of currentColor for easy theming.Example:<svg class=\"bi\" width=\"40\" height=\"40\" fill=\"currentColor\"> <use xlink:href=\"bootstrap-icons.svg#heart-fill\"/></svg><svg class=\"bi\" width=\"40\" height=\"40\" fill=\"currentColor\"> <use xlink:href=\"bootstrap-icons.svg#toggles\"/></svg><svg class=\"bi\" width=\"40\" height=\"40\" fill=\"currentColor\"> <use xlink:href=\"bootstrap-icons.svg#shop\"/></svg>Output:" }, { "code": null, "e": 32996, "s": 32690, "text": "SVG Sprite with <use> element: Use the SVG sprite to insert any icon through the <use> element. Use the icon’s filename as the fragment identifier (e.g., heart is #heart). SVG sprites allow you to reference an external file similar to an <img> element, but with the power of currentColor for easy theming." }, { "code": null, "e": 33005, "s": 32996, "text": "Example:" }, { "code": "<svg class=\"bi\" width=\"40\" height=\"40\" fill=\"currentColor\"> <use xlink:href=\"bootstrap-icons.svg#heart-fill\"/></svg><svg class=\"bi\" width=\"40\" height=\"40\" fill=\"currentColor\"> <use xlink:href=\"bootstrap-icons.svg#toggles\"/></svg><svg class=\"bi\" width=\"40\" height=\"40\" fill=\"currentColor\"> <use xlink:href=\"bootstrap-icons.svg#shop\"/></svg>", "e": 33363, "s": 33005, "text": null }, { "code": null, "e": 33371, "s": 33363, "text": "Output:" }, { "code": null, "e": 33617, "s": 33371, "text": "As an External Image: Copy the Bootstrap icons SVGs to any directory of your choice and reference them like normal images with the <img> tag.Example:<img src=\"/Icons/img/bootstrap.svg\" alt=\"\" width=\"40\" height=\"40\" title=\"Icons\">Output:" }, { "code": null, "e": 33759, "s": 33617, "text": "As an External Image: Copy the Bootstrap icons SVGs to any directory of your choice and reference them like normal images with the <img> tag." }, { "code": null, "e": 33768, "s": 33759, "text": "Example:" }, { "code": "<img src=\"/Icons/img/bootstrap.svg\" alt=\"\" width=\"40\" height=\"40\" title=\"Icons\">", "e": 33858, "s": 33768, "text": null }, { "code": null, "e": 33866, "s": 33858, "text": "Output:" }, { "code": null, "e": 34191, "s": 33866, "text": "Styling of Icons:For styling of Icons, consider them same as text. Color can also be changed by using a .text-* class or custom CSS.Example:<svg class=\"bi bi-alert-triangle text-success \" width=\"40\" height=\"40\" viewBox=\"0 0 20 20\" fill=\"currentColor\" xmlns=\"http://www.w3.org/2000/svg\"> .....</svg>Output:" }, { "code": null, "e": 34307, "s": 34191, "text": "For styling of Icons, consider them same as text. Color can also be changed by using a .text-* class or custom CSS." }, { "code": null, "e": 34316, "s": 34307, "text": "Example:" }, { "code": "<svg class=\"bi bi-alert-triangle text-success \" width=\"40\" height=\"40\" viewBox=\"0 0 20 20\" fill=\"currentColor\" xmlns=\"http://www.w3.org/2000/svg\"> .....</svg>", "e": 34494, "s": 34316, "text": null }, { "code": null, "e": 34502, "s": 34494, "text": "Output:" }, { "code": null, "e": 34517, "s": 34502, "text": "Bootstrap-Misc" }, { "code": null, "e": 34527, "s": 34517, "text": "Bootstrap" }, { "code": null, "e": 34544, "s": 34527, "text": "Web Technologies" }, { "code": null, "e": 34642, "s": 34544, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34651, "s": 34642, "text": "Comments" }, { "code": null, "e": 34664, "s": 34651, "text": "Old Comments" }, { "code": null, "e": 34714, "s": 34664, "text": "How to change navigation bar color in Bootstrap ?" }, { "code": null, "e": 34743, "s": 34714, "text": "Form validation using jQuery" }, { "code": null, "e": 34799, "s": 34743, "text": "How to align navbar items to the right in Bootstrap 4 ?" }, { "code": null, "e": 34840, "s": 34799, "text": "How to pass data into a bootstrap modal?" }, { "code": null, "e": 34881, "s": 34840, "text": "How to Show Images on Click using HTML ?" }, { "code": null, "e": 34923, "s": 34881, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 34956, "s": 34923, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 35018, "s": 34956, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 35068, "s": 35018, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Default values in a Map in C++ STL
01 Jun, 2022 Prerequisite: Map in STLA map is a container which is used to store a key-value pair. By default, In Primitive datatypes such as int, char, bool, float in C/C++ are undefined if variables are not initialized, But a Map is initially empty when it is declared. When this map is accessed with the [ ] (e.g map<int,int> mpp; mpp[1]; ) if the key is not present in the map , it gets added and its value is by default set to 0 (i.e value initialization gets invoked for the int) .To initialize the map with a random default value below is the approach:Approach: Declare a structure(say struct node) with a default value.Initialize Map with key mapped to struct node. Declare a structure(say struct node) with a default value. Initialize Map with key mapped to struct node. Syntax: // For Structure struct Node { int value = -1; } // For Map with every key mapped to default value -1 Map < int, Node > M; Below is the illustration of the Map with a default value -1: CPP14 // C++ program to illustrate a Map// initialize with default value#include <bits/stdc++.h>using namespace std; // Structure Nodestruct Node { int value = -1;}; // Driver Codeint main(){ // Map initialize with key value // pair with each pair mapped with // structure Node map<int, Node> Map; // Print the default value of 1 // store in Map cout << Map[1].value << endl; return 0;} -1 gabaa406 chhabradhanvi Anwesh Panda STL C++ Competitive Programming STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Bitwise Operators in C/C++ Priority Queue in C++ Standard Template Library (STL) vector erase() and clear() in C++ Substring in C++ Object Oriented Programming in C++ Competitive Programming - A Complete Guide Practice for cracking any coding interview Arrow operator -> in C/C++ with Examples Modulo 10^9+7 (1000000007) Prefix Sum Array - Implementation and Applications in Competitive Programming
[ { "code": null, "e": 52, "s": 24, "text": "\n01 Jun, 2022" }, { "code": null, "e": 613, "s": 52, "text": "Prerequisite: Map in STLA map is a container which is used to store a key-value pair. By default, In Primitive datatypes such as int, char, bool, float in C/C++ are undefined if variables are not initialized, But a Map is initially empty when it is declared. When this map is accessed with the [ ] (e.g map<int,int> mpp; mpp[1]; ) if the key is not present in the map , it gets added and its value is by default set to 0 (i.e value initialization gets invoked for the int) .To initialize the map with a random default value below is the approach:Approach: " }, { "code": null, "e": 718, "s": 613, "text": "Declare a structure(say struct node) with a default value.Initialize Map with key mapped to struct node." }, { "code": null, "e": 777, "s": 718, "text": "Declare a structure(say struct node) with a default value." }, { "code": null, "e": 824, "s": 777, "text": "Initialize Map with key mapped to struct node." }, { "code": null, "e": 834, "s": 824, "text": "Syntax: " }, { "code": null, "e": 963, "s": 834, "text": "// For Structure \nstruct Node {\n int value = -1;\n}\n\n// For Map with every key mapped to default value -1\nMap < int, Node > M; " }, { "code": null, "e": 1026, "s": 963, "text": "Below is the illustration of the Map with a default value -1: " }, { "code": null, "e": 1032, "s": 1026, "text": "CPP14" }, { "code": "// C++ program to illustrate a Map// initialize with default value#include <bits/stdc++.h>using namespace std; // Structure Nodestruct Node { int value = -1;}; // Driver Codeint main(){ // Map initialize with key value // pair with each pair mapped with // structure Node map<int, Node> Map; // Print the default value of 1 // store in Map cout << Map[1].value << endl; return 0;}", "e": 1442, "s": 1032, "text": null }, { "code": null, "e": 1445, "s": 1442, "text": "-1" }, { "code": null, "e": 1456, "s": 1447, "text": "gabaa406" }, { "code": null, "e": 1470, "s": 1456, "text": "chhabradhanvi" }, { "code": null, "e": 1483, "s": 1470, "text": "Anwesh Panda" }, { "code": null, "e": 1487, "s": 1483, "text": "STL" }, { "code": null, "e": 1491, "s": 1487, "text": "C++" }, { "code": null, "e": 1515, "s": 1491, "text": "Competitive Programming" }, { "code": null, "e": 1519, "s": 1515, "text": "STL" }, { "code": null, "e": 1523, "s": 1519, "text": "CPP" }, { "code": null, "e": 1621, "s": 1523, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1648, "s": 1621, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 1702, "s": 1648, "text": "Priority Queue in C++ Standard Template Library (STL)" }, { "code": null, "e": 1736, "s": 1702, "text": "vector erase() and clear() in C++" }, { "code": null, "e": 1753, "s": 1736, "text": "Substring in C++" }, { "code": null, "e": 1788, "s": 1753, "text": "Object Oriented Programming in C++" }, { "code": null, "e": 1831, "s": 1788, "text": "Competitive Programming - A Complete Guide" }, { "code": null, "e": 1874, "s": 1831, "text": "Practice for cracking any coding interview" }, { "code": null, "e": 1915, "s": 1874, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 1942, "s": 1915, "text": "Modulo 10^9+7 (1000000007)" } ]
Preferences DataStore in Android
24 Jan, 2021 Preference Data Store is used to store data permanently in android. Earlier we had to Shared Preferences for the same but since it is deprecated we are using Data Store now. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Kotlin language. Step 1: Create a new project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language Step 2: Add dependency inside build.gradle(app) Add the Data Store, Lifecycle, and Coroutines dependency inside the build.gradle(app) and click on the sync now button. // Preferences DataStore implementation “androidx.datastore:datastore-preferences:1.0.0-alpha01” // Lifecycle components implementation “androidx.lifecycle:lifecycle-livedata-ktx:2.2.0” implementation “androidx.lifecycle:lifecycle-extensions:2.2.0” implementation “androidx.lifecycle:lifecycle-common-java8:2.2.0” implementation “androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0” // Kotlin coroutines components implementation “org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.4.10” api “org.jetbrains.kotlinx:kotlinx-coroutines-core:1.4.1” api “org.jetbrains.kotlinx:kotlinx-coroutines-android:1.4.1” Step 3: Working with the activity_main.xml file Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file. This is for the basic layout used in the app. 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:gravity="center_horizontal" android:orientation="vertical" tools:context=".MainActivity"> <EditText android:id="@+id/et_name" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="10dp" android:layout_marginTop="20dp" android:ems="10" android:hint="Name" /> <EditText android:id="@+id/et_age" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="10dp" android:ems="10" android:hint="Age" android:inputType="number" /> <Button android:id="@+id/btn_save" android:layout_width="150dp" android:layout_height="wrap_content" android:layout_margin="10dp" android:background="#FF7043" android:padding="10dp" android:text="Save user" android:textColor="@android:color/white" /> <TextView android:id="@+id/tv_name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="10dp" android:text="Name" android:textColor="@android:color/black" android:textSize="20sp" /> <TextView android:id="@+id/tv_age" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="10dp" android:text="Age" android:textColor="@android:color/black" android:textSize="20sp" /> </LinearLayout> Step 4: Working with the UserManager.kt class Create a new kotlin class and name it UserManager, this class holds the code for saving and retrieving data from the preference Data Store. Comments are added inside the code to understand the code in more detail. Kotlin import android.content.Contextimport androidx.datastore.preferences.createDataStoreimport androidx.datastore.preferences.editimport androidx.datastore.preferences.preferencesKeyimport kotlinx.coroutines.flow.Flowimport kotlinx.coroutines.flow.map class UserManager(context: Context) { // Create the dataStore and give it a name same as shared preferences private val dataStore = context.createDataStore(name = "user_prefs") // Create some keys we will use them to store and retrieve the data companion object { val USER_AGE_KEY = preferencesKey<Int>("USER_AGE") val USER_NAME_KEY = preferencesKey<String>("USER_NAME") } // Store user data // refer to the data store and using edit // we can store values using the keys suspend fun storeUser(age: Int, name: String) { dataStore.edit { it[USER_AGE_KEY] = age it[USER_NAME_KEY] = name // here it refers to the preferences we are editing } } // Create an age flow to retrieve age from the preferences // flow comes from the kotlin coroutine val userAgeFlow: Flow<Int> = dataStore.data.map { it[USER_AGE_KEY] ?: 0 } // Create a name flow to retrieve name from the preferences val userNameFlow: Flow<String> = dataStore.data.map { it[USER_NAME_KEY] ?: "" }} Step 5: Working with the MainActivity.kt file Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail. Kotlin import android.os.Bundleimport android.widget.Buttonimport android.widget.EditTextimport android.widget.TextViewimport androidx.appcompat.app.AppCompatActivityimport androidx.lifecycle.asLiveDataimport androidx.lifecycle.observeimport kotlinx.coroutines.GlobalScopeimport kotlinx.coroutines.launch class MainActivity : AppCompatActivity() { lateinit var etName: EditText lateinit var etAge: EditText lateinit var tvName: TextView lateinit var tvAge: TextView lateinit var saveButton: Button lateinit var userManager: UserManager var age = 0 var name = "" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) etName = findViewById(R.id.et_name) etAge = findViewById(R.id.et_age) tvName = findViewById(R.id.tv_name) tvAge = findViewById(R.id.tv_age) saveButton = findViewById(R.id.btn_save) // Get reference to our userManager class userManager = UserManager(this) // this function saves the data to // preference data store on click of // save Button buttonSave() // this function retrieves the saved data // as soon as they are stored and even // after app is closed and started again observeData() } private fun buttonSave() { // Gets the user input and saves it saveButton.setOnClickListener { name = etName.text.toString() age = etAge.text.toString().toInt() // Stores the values // Since the storeUser function of UserManager // class is a suspend function // So this has to be done in a coroutine scope GlobalScope.launch { userManager.storeUser(age, name) } } } private fun observeData() { // Updates age // every time user age changes it will be observed by userAgeFlow // here it refers to the value returned from the userAgeFlow function // of UserManager class this.userManager.userAgeFlow.asLiveData().observe(this) { age = it tvAge.text = it.toString() } // Updates name // every time user name changes it will be observed by userNameFlow // here it refers to the value returned from the usernameFlow function // of UserManager class userManager.userNameFlow.asLiveData().observe(this) { name = it tvName.text = it.toString() } }} Github repo here. android Android Kotlin 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 How to Communicate Between Fragments in Android? Flutter - Custom Bottom Navigation Bar Retrofit with Kotlin Coroutine in Android How to Add Views Dynamically and Store Data in Arraylist in Android? Android UI Layouts How to Communicate Between Fragments in Android? Kotlin Array Retrofit with Kotlin Coroutine in Android
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Jan, 2021" }, { "code": null, "e": 370, "s": 28, "text": "Preference Data Store is used to store data permanently in android. Earlier we had to Shared Preferences for the same but since it is deprecated we are using Data Store now. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Kotlin language." }, { "code": null, "e": 399, "s": 370, "text": "Step 1: Create a new project" }, { "code": null, "e": 562, "s": 399, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language" }, { "code": null, "e": 610, "s": 562, "text": "Step 2: Add dependency inside build.gradle(app)" }, { "code": null, "e": 730, "s": 610, "text": "Add the Data Store, Lifecycle, and Coroutines dependency inside the build.gradle(app) and click on the sync now button." }, { "code": null, "e": 758, "s": 730, "text": " // Preferences DataStore" }, { "code": null, "e": 833, "s": 758, "text": " implementation “androidx.datastore:datastore-preferences:1.0.0-alpha01”" }, { "code": null, "e": 860, "s": 833, "text": " // Lifecycle components" }, { "code": null, "e": 928, "s": 860, "text": " implementation “androidx.lifecycle:lifecycle-livedata-ktx:2.2.0”" }, { "code": null, "e": 994, "s": 928, "text": " implementation “androidx.lifecycle:lifecycle-extensions:2.2.0”" }, { "code": null, "e": 1062, "s": 994, "text": " implementation “androidx.lifecycle:lifecycle-common-java8:2.2.0”" }, { "code": null, "e": 1131, "s": 1062, "text": " implementation “androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0”" }, { "code": null, "e": 1166, "s": 1131, "text": " // Kotlin coroutines components" }, { "code": null, "e": 1233, "s": 1166, "text": " implementation “org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.4.10”" }, { "code": null, "e": 1294, "s": 1233, "text": " api “org.jetbrains.kotlinx:kotlinx-coroutines-core:1.4.1”" }, { "code": null, "e": 1358, "s": 1294, "text": " api “org.jetbrains.kotlinx:kotlinx-coroutines-android:1.4.1”" }, { "code": null, "e": 1406, "s": 1358, "text": "Step 3: Working with the activity_main.xml file" }, { "code": null, "e": 1568, "s": 1406, "text": "Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file. This is for the basic layout used in the app." }, { "code": null, "e": 1572, "s": 1568, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:gravity=\"center_horizontal\" android:orientation=\"vertical\" tools:context=\".MainActivity\"> <EditText android:id=\"@+id/et_name\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"10dp\" android:layout_marginTop=\"20dp\" android:ems=\"10\" android:hint=\"Name\" /> <EditText android:id=\"@+id/et_age\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"10dp\" android:ems=\"10\" android:hint=\"Age\" android:inputType=\"number\" /> <Button android:id=\"@+id/btn_save\" android:layout_width=\"150dp\" android:layout_height=\"wrap_content\" android:layout_margin=\"10dp\" android:background=\"#FF7043\" android:padding=\"10dp\" android:text=\"Save user\" android:textColor=\"@android:color/white\" /> <TextView android:id=\"@+id/tv_name\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_margin=\"10dp\" android:text=\"Name\" android:textColor=\"@android:color/black\" android:textSize=\"20sp\" /> <TextView android:id=\"@+id/tv_age\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_margin=\"10dp\" android:text=\"Age\" android:textColor=\"@android:color/black\" android:textSize=\"20sp\" /> </LinearLayout>", "e": 3331, "s": 1572, "text": null }, { "code": null, "e": 3377, "s": 3331, "text": "Step 4: Working with the UserManager.kt class" }, { "code": null, "e": 3591, "s": 3377, "text": "Create a new kotlin class and name it UserManager, this class holds the code for saving and retrieving data from the preference Data Store. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 3598, "s": 3591, "text": "Kotlin" }, { "code": "import android.content.Contextimport androidx.datastore.preferences.createDataStoreimport androidx.datastore.preferences.editimport androidx.datastore.preferences.preferencesKeyimport kotlinx.coroutines.flow.Flowimport kotlinx.coroutines.flow.map class UserManager(context: Context) { // Create the dataStore and give it a name same as shared preferences private val dataStore = context.createDataStore(name = \"user_prefs\") // Create some keys we will use them to store and retrieve the data companion object { val USER_AGE_KEY = preferencesKey<Int>(\"USER_AGE\") val USER_NAME_KEY = preferencesKey<String>(\"USER_NAME\") } // Store user data // refer to the data store and using edit // we can store values using the keys suspend fun storeUser(age: Int, name: String) { dataStore.edit { it[USER_AGE_KEY] = age it[USER_NAME_KEY] = name // here it refers to the preferences we are editing } } // Create an age flow to retrieve age from the preferences // flow comes from the kotlin coroutine val userAgeFlow: Flow<Int> = dataStore.data.map { it[USER_AGE_KEY] ?: 0 } // Create a name flow to retrieve name from the preferences val userNameFlow: Flow<String> = dataStore.data.map { it[USER_NAME_KEY] ?: \"\" }}", "e": 4942, "s": 3598, "text": null }, { "code": null, "e": 4988, "s": 4942, "text": "Step 5: Working with the MainActivity.kt file" }, { "code": null, "e": 5174, "s": 4988, "text": "Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 5181, "s": 5174, "text": "Kotlin" }, { "code": "import android.os.Bundleimport android.widget.Buttonimport android.widget.EditTextimport android.widget.TextViewimport androidx.appcompat.app.AppCompatActivityimport androidx.lifecycle.asLiveDataimport androidx.lifecycle.observeimport kotlinx.coroutines.GlobalScopeimport kotlinx.coroutines.launch class MainActivity : AppCompatActivity() { lateinit var etName: EditText lateinit var etAge: EditText lateinit var tvName: TextView lateinit var tvAge: TextView lateinit var saveButton: Button lateinit var userManager: UserManager var age = 0 var name = \"\" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) etName = findViewById(R.id.et_name) etAge = findViewById(R.id.et_age) tvName = findViewById(R.id.tv_name) tvAge = findViewById(R.id.tv_age) saveButton = findViewById(R.id.btn_save) // Get reference to our userManager class userManager = UserManager(this) // this function saves the data to // preference data store on click of // save Button buttonSave() // this function retrieves the saved data // as soon as they are stored and even // after app is closed and started again observeData() } private fun buttonSave() { // Gets the user input and saves it saveButton.setOnClickListener { name = etName.text.toString() age = etAge.text.toString().toInt() // Stores the values // Since the storeUser function of UserManager // class is a suspend function // So this has to be done in a coroutine scope GlobalScope.launch { userManager.storeUser(age, name) } } } private fun observeData() { // Updates age // every time user age changes it will be observed by userAgeFlow // here it refers to the value returned from the userAgeFlow function // of UserManager class this.userManager.userAgeFlow.asLiveData().observe(this) { age = it tvAge.text = it.toString() } // Updates name // every time user name changes it will be observed by userNameFlow // here it refers to the value returned from the usernameFlow function // of UserManager class userManager.userNameFlow.asLiveData().observe(this) { name = it tvName.text = it.toString() } }}", "e": 7736, "s": 5181, "text": null }, { "code": null, "e": 7754, "s": 7736, "text": "Github repo here." }, { "code": null, "e": 7762, "s": 7754, "text": "android" }, { "code": null, "e": 7770, "s": 7762, "text": "Android" }, { "code": null, "e": 7777, "s": 7770, "text": "Kotlin" }, { "code": null, "e": 7785, "s": 7777, "text": "Android" }, { "code": null, "e": 7883, "s": 7785, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7952, "s": 7883, "text": "How to Add Views Dynamically and Store Data in Arraylist in Android?" }, { "code": null, "e": 7984, "s": 7952, "text": "Android SDK and it's Components" }, { "code": null, "e": 8033, "s": 7984, "text": "How to Communicate Between Fragments in Android?" }, { "code": null, "e": 8072, "s": 8033, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 8114, "s": 8072, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 8183, "s": 8114, "text": "How to Add Views Dynamically and Store Data in Arraylist in Android?" }, { "code": null, "e": 8202, "s": 8183, "text": "Android UI Layouts" }, { "code": null, "e": 8251, "s": 8202, "text": "How to Communicate Between Fragments in Android?" }, { "code": null, "e": 8264, "s": 8251, "text": "Kotlin Array" } ]
Minimum Increment operations to make Array unique
08 Jul, 2022 Given an array A[] of integers. In one move you can choose any element A[i], and increment it by 1. The task is to return the minimum number of moves needed to make every value in the array A[] unique.Examples: Input: A[] = [3, 2, 1, 2, 1, 7] Output: 6 Explanation: After 6 moves, the array could be [3, 4, 1, 2, 5, 7]. It can be shown that it is impossible for the array to have all unique values with 5 or less moves. Input: A[] = [1, 2, 2] Output: 1 Explanation: After 1 move [2 -> 3], the array could be [1, 2, 3]. A simple solution to make each duplicate value unique is to keep incrementing it repeatedly until it is not unique. However, we might do a lot of extra work, if we have an array of all ones.So, what we can do instead is to evaluate what our increments should be. If for example, we have [1, 1, 1, 3, 5], we don’t need to process all the increments of duplicated 1’s. We could take two ones (taken = [1, 1]) and continue processing. Whenever we find an empty(unused value) place like 2 or 4 we can then recover that our increment will be 2-1, 4-1 respectively.Thus, we first count the values and for each possible value X in the array: If there are 2 or more values X in A, save the extra duplicated values to increment later. If there are 0 values X in A, then a saved value gets incremented to X. Below is the implementation of the above approach: Java Python3 C# // Java Implementation of above approachimport java.util.*; class GFG { // function to find minimum increment required static int minIncrementForUnique(int[] A) { // collect frequency of each element TreeMap<Integer, Integer> dict = new TreeMap<Integer, Integer>(); HashSet<Integer> used = new HashSet<Integer>(); // Load Frequency Map (Element -> Count) and Used Set for (int i : A) { if (dict.containsKey(i)) dict.put(i, dict.get(i) + 1); else { dict.put(i, 1); used.add(i); } } int maxUsed = 0; // Works for +ve numbers int ans = 0; for (Map.Entry<Integer, Integer> entry : dict.entrySet()) { int value = entry.getKey(); int freq = entry.getValue(); if (freq <= 1) //If not a duplicate, skip continue; int duplicates = freq - 1; // Number of duplicates 1 less than count // Start with next best option for this duplicate: // CurNum + 1 or an earlier maximum number that has been used int cur = Math.max(value + 1, maxUsed); while (duplicates > 0) { if (!used.contains(cur)) { ans += cur - value; // Number of increments = Available Spot - Duplicate Value used.add(cur); duplicates--; maxUsed = cur; } cur++; } } // return answer return ans; } // Driver code public static void main(String[] args) { int[] A = { 3, 2, 1, 2, 1, 2, 6, 7 }; System.out.print(minIncrementForUnique(A)); }} // This code is contributed by Aditya # Python3 Implementation of above approachimport collections # function to find minimum increment requireddef minIncrementForUnique(A): # collect frequency of each element count = collections.Counter(A) # array of unique values taken taken = [] ans = 0 for x in range(100000): if count[x] >= 2: taken.extend([x] * (count[x] - 1)) elif taken and count[x] == 0: ans += x - taken.pop() # return answer return ans # Driver codeA = [3, 2, 1, 2, 1, 7]print(minIncrementForUnique(A)) // C# Implementation of above approachusing System;using System.Collections.Generic; class GFG{ // function to find minimum increment requiredstatic int minIncrementForUnique(int []A){ // collect frequency of each element Dictionary<int,int> mpp = new Dictionary<int,int>(); foreach(int i in A) { if(mpp.ContainsKey(i)) mpp[i] = mpp[i] + 1; else mpp.Add(i, 1); } // array of unique values taken List<int> taken = new List<int>(); int ans = 0; for (int x = 0; x < 100000; x++) { if (mpp.ContainsKey(x) && mpp[x] >= 2) taken.Add(x * (mpp[x] - 1)); else if(taken.Count > 0 && ((mpp.ContainsKey(x) && mpp[x] == 0)||!mpp.ContainsKey(x))) { ans += x - taken[taken.Count - 1]; taken.RemoveAt(taken.Count - 1); } } // return answer return ans;} // Driver codepublic static void Main(String[] args){ int []A = {3, 2, 1, 2, 1, 7}; Console.Write(minIncrementForUnique(A));}} // This code contributed by PrinciRaj1992 12 Time Complexity: O(n*log(n))Auxiliary Space: O(n) mohit kumar 29 Rajput-Ji princiraj1992 imshubhamkr50 adityanamjoshi subhammahato348 Arrays Mathematical Python Programs Arrays Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Multidimensional Arrays in Java Stack Data Structure (Introduction and Program) Linear Search 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 Operators in C / C++
[ { "code": null, "e": 54, "s": 26, "text": "\n08 Jul, 2022" }, { "code": null, "e": 267, "s": 54, "text": "Given an array A[] of integers. In one move you can choose any element A[i], and increment it by 1. The task is to return the minimum number of moves needed to make every value in the array A[] unique.Examples: " }, { "code": null, "e": 579, "s": 267, "text": "Input: A[] = [3, 2, 1, 2, 1, 7]\nOutput: 6\nExplanation: After 6 moves, the array could be \n[3, 4, 1, 2, 5, 7].\nIt can be shown that it is impossible for the array \nto have all unique values with 5 or less moves.\n\nInput: A[] = [1, 2, 2]\nOutput: 1\nExplanation: After 1 move [2 -> 3], the array could be [1, 2, 3]." }, { "code": null, "e": 1218, "s": 581, "text": "A simple solution to make each duplicate value unique is to keep incrementing it repeatedly until it is not unique. However, we might do a lot of extra work, if we have an array of all ones.So, what we can do instead is to evaluate what our increments should be. If for example, we have [1, 1, 1, 3, 5], we don’t need to process all the increments of duplicated 1’s. We could take two ones (taken = [1, 1]) and continue processing. Whenever we find an empty(unused value) place like 2 or 4 we can then recover that our increment will be 2-1, 4-1 respectively.Thus, we first count the values and for each possible value X in the array: " }, { "code": null, "e": 1309, "s": 1218, "text": "If there are 2 or more values X in A, save the extra duplicated values to increment later." }, { "code": null, "e": 1381, "s": 1309, "text": "If there are 0 values X in A, then a saved value gets incremented to X." }, { "code": null, "e": 1434, "s": 1381, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 1439, "s": 1434, "text": "Java" }, { "code": null, "e": 1447, "s": 1439, "text": "Python3" }, { "code": null, "e": 1450, "s": 1447, "text": "C#" }, { "code": "// Java Implementation of above approachimport java.util.*; class GFG { // function to find minimum increment required static int minIncrementForUnique(int[] A) { // collect frequency of each element TreeMap<Integer, Integer> dict = new TreeMap<Integer, Integer>(); HashSet<Integer> used = new HashSet<Integer>(); // Load Frequency Map (Element -> Count) and Used Set for (int i : A) { if (dict.containsKey(i)) dict.put(i, dict.get(i) + 1); else { dict.put(i, 1); used.add(i); } } int maxUsed = 0; // Works for +ve numbers int ans = 0; for (Map.Entry<Integer, Integer> entry : dict.entrySet()) { int value = entry.getKey(); int freq = entry.getValue(); if (freq <= 1) //If not a duplicate, skip continue; int duplicates = freq - 1; // Number of duplicates 1 less than count // Start with next best option for this duplicate: // CurNum + 1 or an earlier maximum number that has been used int cur = Math.max(value + 1, maxUsed); while (duplicates > 0) { if (!used.contains(cur)) { ans += cur - value; // Number of increments = Available Spot - Duplicate Value used.add(cur); duplicates--; maxUsed = cur; } cur++; } } // return answer return ans; } // Driver code public static void main(String[] args) { int[] A = { 3, 2, 1, 2, 1, 2, 6, 7 }; System.out.print(minIncrementForUnique(A)); }} // This code is contributed by Aditya", "e": 3248, "s": 1450, "text": null }, { "code": "# Python3 Implementation of above approachimport collections # function to find minimum increment requireddef minIncrementForUnique(A): # collect frequency of each element count = collections.Counter(A) # array of unique values taken taken = [] ans = 0 for x in range(100000): if count[x] >= 2: taken.extend([x] * (count[x] - 1)) elif taken and count[x] == 0: ans += x - taken.pop() # return answer return ans # Driver codeA = [3, 2, 1, 2, 1, 7]print(minIncrementForUnique(A))", "e": 3790, "s": 3248, "text": null }, { "code": "// C# Implementation of above approachusing System;using System.Collections.Generic; class GFG{ // function to find minimum increment requiredstatic int minIncrementForUnique(int []A){ // collect frequency of each element Dictionary<int,int> mpp = new Dictionary<int,int>(); foreach(int i in A) { if(mpp.ContainsKey(i)) mpp[i] = mpp[i] + 1; else mpp.Add(i, 1); } // array of unique values taken List<int> taken = new List<int>(); int ans = 0; for (int x = 0; x < 100000; x++) { if (mpp.ContainsKey(x) && mpp[x] >= 2) taken.Add(x * (mpp[x] - 1)); else if(taken.Count > 0 && ((mpp.ContainsKey(x) && mpp[x] == 0)||!mpp.ContainsKey(x))) { ans += x - taken[taken.Count - 1]; taken.RemoveAt(taken.Count - 1); } } // return answer return ans;} // Driver codepublic static void Main(String[] args){ int []A = {3, 2, 1, 2, 1, 7}; Console.Write(minIncrementForUnique(A));}} // This code contributed by PrinciRaj1992", "e": 4890, "s": 3790, "text": null }, { "code": null, "e": 4893, "s": 4890, "text": "12" }, { "code": null, "e": 4944, "s": 4893, "text": "Time Complexity: O(n*log(n))Auxiliary Space: O(n) " }, { "code": null, "e": 4959, "s": 4944, "text": "mohit kumar 29" }, { "code": null, "e": 4969, "s": 4959, "text": "Rajput-Ji" }, { "code": null, "e": 4983, "s": 4969, "text": "princiraj1992" }, { "code": null, "e": 4997, "s": 4983, "text": "imshubhamkr50" }, { "code": null, "e": 5012, "s": 4997, "text": "adityanamjoshi" }, { "code": null, "e": 5028, "s": 5012, "text": "subhammahato348" }, { "code": null, "e": 5035, "s": 5028, "text": "Arrays" }, { "code": null, "e": 5048, "s": 5035, "text": "Mathematical" }, { "code": null, "e": 5064, "s": 5048, "text": "Python Programs" }, { "code": null, "e": 5071, "s": 5064, "text": "Arrays" }, { "code": null, "e": 5084, "s": 5071, "text": "Mathematical" }, { "code": null, "e": 5182, "s": 5084, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5250, "s": 5182, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 5294, "s": 5250, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 5326, "s": 5294, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 5374, "s": 5326, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 5388, "s": 5374, "text": "Linear Search" }, { "code": null, "e": 5431, "s": 5388, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 5491, "s": 5431, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 5506, "s": 5491, "text": "C++ Data Types" }, { "code": null, "e": 5530, "s": 5506, "text": "Merge two sorted arrays" } ]
How to specify the double border using CSS ?
30 Apr, 2021 The task is to specify the double border using CSS. In this article, we are going to use the border-style property to style the border. Property used: border-style property: This property is used to set the style of an element’s four borders. Approach: Create the HTML page with some elements. Now, using the border-style property style the border with value double. Example: HTML <!DOCTYPE html><html><head> <style type="text/css"> body { text-align: center; } h1.double { border-width: 5px; border-style: double; Border-color: green } h1.double2 { border-width: 10px; border-style: double; Border-color: green } h1.double3 { border-width: 15px; border-style: double; Border-color: green } </style></head> <body> <h1 class="double">GeeksForGeeks</h1> <h1 class="double2">GeeksForGeeks</h1> <h1 class="double3">GeeksForGeeks</h1></body> </html> Output: CSS-Basics CSS-Properties CSS-Questions 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": "\n30 Apr, 2021" }, { "code": null, "e": 164, "s": 28, "text": "The task is to specify the double border using CSS. In this article, we are going to use the border-style property to style the border." }, { "code": null, "e": 179, "s": 164, "text": "Property used:" }, { "code": null, "e": 271, "s": 179, "text": "border-style property: This property is used to set the style of an element’s four borders." }, { "code": null, "e": 281, "s": 271, "text": "Approach:" }, { "code": null, "e": 322, "s": 281, "text": "Create the HTML page with some elements." }, { "code": null, "e": 395, "s": 322, "text": "Now, using the border-style property style the border with value double." }, { "code": null, "e": 404, "s": 395, "text": "Example:" }, { "code": null, "e": 409, "s": 404, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <style type=\"text/css\"> body { text-align: center; } h1.double { border-width: 5px; border-style: double; Border-color: green } h1.double2 { border-width: 10px; border-style: double; Border-color: green } h1.double3 { border-width: 15px; border-style: double; Border-color: green } </style></head> <body> <h1 class=\"double\">GeeksForGeeks</h1> <h1 class=\"double2\">GeeksForGeeks</h1> <h1 class=\"double3\">GeeksForGeeks</h1></body> </html>", "e": 1086, "s": 409, "text": null }, { "code": null, "e": 1094, "s": 1086, "text": "Output:" }, { "code": null, "e": 1105, "s": 1094, "text": "CSS-Basics" }, { "code": null, "e": 1120, "s": 1105, "text": "CSS-Properties" }, { "code": null, "e": 1134, "s": 1120, "text": "CSS-Questions" }, { "code": null, "e": 1138, "s": 1134, "text": "CSS" }, { "code": null, "e": 1155, "s": 1138, "text": "Web Technologies" } ]
Directory traversal tools in Python
27 Dec, 2019 os.walk() method of the OS module can be used for listing out all the directories. This method basically generates the file names in the directory tree either top-down or bottom-up. For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple (dirpath, dirnames, filenames). dirpath: A string that is the path to the directory dirnames: All the sub-directories from root. filenames: All the files from root and directories. Syntax: os.walk(top, topdown=True, onerror=None, followlinks=False) Parameters:top: Starting directory for os.walk().topdown: If this optional argument is True then the directories are scanned from top-down otherwise from bottom-up. This is True by default.onerror: It is a function that handles errors that may occur.followlinks: This visits directories pointed to by symlinks, if set to True. Return Type: For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple (dirpath, dirnames, filenames). Example: Suppose the directory looks like this: We want to list out all the subdirectories and file inside the directory Tree. Below is the implementation. # Python program to list out # all the sub-directories and files import os # List to store all # directories L = [] # Traversing through Test for root, dirs, files in os.walk('Test'): # Adding the empty directory to # list L.append((root, dirs, files)) print("List of all sub-directories and files:") for i in L: print(i) Output: List of all sub-directories and files: ('Test', ['B', 'C', 'D', 'A'], []) ('Test/B', [], []) ('Test/C', [], ['test2.txt']) ('Test/D', ['E'], []) ('Test/D/E', [], []) ('Test/A', ['A2', 'A1'], []) ('Test/A/A2', [], []) ('Test/A/A1', [], ['test1.txt']) The above code can be shortened using List Comprehension which is a more Pythonic way. Below is the implementation. # Python program to list out # all the sub-directories and files import os # List comprehension to enter # all directories to list L = [(root, dirs, files) for root, dirs, files, in os.walk('Test')] print("List of all sub-directories and files:") for i in L: print(i) Output: List of all sub-directories and files: ('Test', ['B', 'C', 'D', 'A'], []) ('Test/B', [], []) ('Test/C', [], ['test2.txt']) ('Test/D', ['E'], []) ('Test/D/E', [], []) ('Test/A', ['A2', 'A1'], []) ('Test/A/A2', [], []) ('Test/A/A1', [], ['test1.txt']) Python directory-program python-file-handling Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Iterate over a list in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n27 Dec, 2019" }, { "code": null, "e": 341, "s": 28, "text": "os.walk() method of the OS module can be used for listing out all the directories. This method basically generates the file names in the directory tree either top-down or bottom-up. For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple (dirpath, dirnames, filenames)." }, { "code": null, "e": 393, "s": 341, "text": "dirpath: A string that is the path to the directory" }, { "code": null, "e": 438, "s": 393, "text": "dirnames: All the sub-directories from root." }, { "code": null, "e": 490, "s": 438, "text": "filenames: All the files from root and directories." }, { "code": null, "e": 558, "s": 490, "text": "Syntax: os.walk(top, topdown=True, onerror=None, followlinks=False)" }, { "code": null, "e": 885, "s": 558, "text": "Parameters:top: Starting directory for os.walk().topdown: If this optional argument is True then the directories are scanned from top-down otherwise from bottom-up. This is True by default.onerror: It is a function that handles errors that may occur.followlinks: This visits directories pointed to by symlinks, if set to True." }, { "code": null, "e": 1029, "s": 885, "text": "Return Type: For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple (dirpath, dirnames, filenames)." }, { "code": null, "e": 1077, "s": 1029, "text": "Example: Suppose the directory looks like this:" }, { "code": null, "e": 1185, "s": 1077, "text": "We want to list out all the subdirectories and file inside the directory Tree. Below is the implementation." }, { "code": "# Python program to list out # all the sub-directories and files import os # List to store all # directories L = [] # Traversing through Test for root, dirs, files in os.walk('Test'): # Adding the empty directory to # list L.append((root, dirs, files)) print(\"List of all sub-directories and files:\") for i in L: print(i)", "e": 1542, "s": 1185, "text": null }, { "code": null, "e": 1550, "s": 1542, "text": "Output:" }, { "code": null, "e": 1801, "s": 1550, "text": "List of all sub-directories and files:\n('Test', ['B', 'C', 'D', 'A'], [])\n('Test/B', [], [])\n('Test/C', [], ['test2.txt'])\n('Test/D', ['E'], [])\n('Test/D/E', [], [])\n('Test/A', ['A2', 'A1'], [])\n('Test/A/A2', [], [])\n('Test/A/A1', [], ['test1.txt'])\n" }, { "code": null, "e": 1917, "s": 1801, "text": "The above code can be shortened using List Comprehension which is a more Pythonic way. Below is the implementation." }, { "code": "# Python program to list out # all the sub-directories and files import os # List comprehension to enter # all directories to list L = [(root, dirs, files) for root, dirs, files, in os.walk('Test')] print(\"List of all sub-directories and files:\") for i in L: print(i)", "e": 2212, "s": 1917, "text": null }, { "code": null, "e": 2220, "s": 2212, "text": "Output:" }, { "code": null, "e": 2471, "s": 2220, "text": "List of all sub-directories and files:\n('Test', ['B', 'C', 'D', 'A'], [])\n('Test/B', [], [])\n('Test/C', [], ['test2.txt'])\n('Test/D', ['E'], [])\n('Test/D/E', [], [])\n('Test/A', ['A2', 'A1'], [])\n('Test/A/A2', [], [])\n('Test/A/A1', [], ['test1.txt'])\n" }, { "code": null, "e": 2496, "s": 2471, "text": "Python directory-program" }, { "code": null, "e": 2517, "s": 2496, "text": "python-file-handling" }, { "code": null, "e": 2524, "s": 2517, "text": "Python" }, { "code": null, "e": 2622, "s": 2524, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2640, "s": 2622, "text": "Python Dictionary" }, { "code": null, "e": 2682, "s": 2640, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2704, "s": 2682, "text": "Enumerate() in Python" }, { "code": null, "e": 2739, "s": 2704, "text": "Read a file line by line in Python" }, { "code": null, "e": 2765, "s": 2739, "text": "Python String | replace()" }, { "code": null, "e": 2797, "s": 2765, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2826, "s": 2797, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2853, "s": 2826, "text": "Python Classes and Objects" }, { "code": null, "e": 2874, "s": 2853, "text": "Python OOPs Concepts" } ]
GATE | GATE-CS-2009 | Question 60
27 Jul, 2021 In the following process state transition diagram for a uniprocessor system, assume that there are always some processes in the ready state: Now consider the following statements: I. If a process makes a transition D, it would result in another process making transition A immediately. II. A process P2 in blocked state can make transition E while another process P1 is in running state. III. The OS uses preemptive scheduling. IV. The OS uses non-preemptive scheduling. Which of the above statements are TRUE? (A) I and II(B) I and III(C) II and III(D) II and IVAnswer: (C)Explanation: I is false. If a process makes a transition D, it would result in another process making transition B, not A.II is true. A process can move to ready state when I/O completes irrespective of other process being in running state or not.III is true because there is a transition from running to ready state.IV is false as the OS uses preemptive scheduling. Watch GeeksforGeeks Video Explanation : CPU Scheduling GATE Previous Year Questions with Viomesh Singh - YouTubeGeeksforGeeks GATE Computer Science17.5K subscribersCPU Scheduling GATE Previous Year Questions with Viomesh SinghWatch 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:0026:39 / 39:01•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=y1BbjvO_xog" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question GATE-CS-2009 GATE-GATE-CS-2009 GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GATE | GATE-CS-2014-(Set-2) | Question 65 GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33 GATE | GATE CS 2008 | Question 46 GATE | GATE-CS-2015 (Set 3) | Question 65 GATE | GATE-CS-2014-(Set-3) | Question 65 GATE | GATE CS 2011 | Question 49 GATE | GATE CS 1996 | Question 38 GATE | GATE-CS-2004 | Question 31 GATE | GATE-CS-2016 (Set 1) | Question 45 GATE | GATE CS 1996 | Question 63
[ { "code": null, "e": 52, "s": 24, "text": "\n27 Jul, 2021" }, { "code": null, "e": 232, "s": 52, "text": "In the following process state transition diagram for a uniprocessor system, assume that there are always some processes in the ready state: Now consider the following statements:" }, { "code": null, "e": 532, "s": 232, "text": "I. If a process makes a transition D, it would result in \n another process making transition A immediately.\nII. A process P2 in blocked state can make transition E \n while another process P1 is in running state.\nIII. The OS uses preemptive scheduling.\nIV. The OS uses non-preemptive scheduling." }, { "code": null, "e": 572, "s": 532, "text": "Which of the above statements are TRUE?" }, { "code": null, "e": 1002, "s": 572, "text": "(A) I and II(B) I and III(C) II and III(D) II and IVAnswer: (C)Explanation: I is false. If a process makes a transition D, it would result in another process making transition B, not A.II is true. A process can move to ready state when I/O completes irrespective of other process being in running state or not.III is true because there is a transition from running to ready state.IV is false as the OS uses preemptive scheduling." }, { "code": null, "e": 1042, "s": 1002, "text": "Watch GeeksforGeeks Video Explanation :" }, { "code": null, "e": 1998, "s": 1042, "text": "CPU Scheduling GATE Previous Year Questions with Viomesh Singh - YouTubeGeeksforGeeks GATE Computer Science17.5K subscribersCPU Scheduling GATE Previous Year Questions with Viomesh SinghWatch 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:0026:39 / 39:01•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=y1BbjvO_xog\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question" }, { "code": null, "e": 2011, "s": 1998, "text": "GATE-CS-2009" }, { "code": null, "e": 2029, "s": 2011, "text": "GATE-GATE-CS-2009" }, { "code": null, "e": 2034, "s": 2029, "text": "GATE" }, { "code": null, "e": 2132, "s": 2034, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2174, "s": 2132, "text": "GATE | GATE-CS-2014-(Set-2) | Question 65" }, { "code": null, "e": 2236, "s": 2174, "text": "GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33" }, { "code": null, "e": 2270, "s": 2236, "text": "GATE | GATE CS 2008 | Question 46" }, { "code": null, "e": 2312, "s": 2270, "text": "GATE | GATE-CS-2015 (Set 3) | Question 65" }, { "code": null, "e": 2354, "s": 2312, "text": "GATE | GATE-CS-2014-(Set-3) | Question 65" }, { "code": null, "e": 2388, "s": 2354, "text": "GATE | GATE CS 2011 | Question 49" }, { "code": null, "e": 2422, "s": 2388, "text": "GATE | GATE CS 1996 | Question 38" }, { "code": null, "e": 2456, "s": 2422, "text": "GATE | GATE-CS-2004 | Question 31" }, { "code": null, "e": 2498, "s": 2456, "text": "GATE | GATE-CS-2016 (Set 1) | Question 45" } ]
Delete a file in C#
Use File.Delete method to delete a file. Firstly, set the path of the file you want to delete. String myPath = @"C:\New\amit.txt"; Now, use the File.Delete method to delete the file. File.Delete(myPath); The following is the complete code − Live Demo using System; using System.IO; public class Program { public static void Main() { String myPath = @"C:\New\amit.txt"; Console.WriteLine("Deleting File"); File.Delete(myPath); } } Deleting File
[ { "code": null, "e": 1228, "s": 1187, "text": "Use File.Delete method to delete a file." }, { "code": null, "e": 1282, "s": 1228, "text": "Firstly, set the path of the file you want to delete." }, { "code": null, "e": 1318, "s": 1282, "text": "String myPath = @\"C:\\New\\amit.txt\";" }, { "code": null, "e": 1370, "s": 1318, "text": "Now, use the File.Delete method to delete the file." }, { "code": null, "e": 1391, "s": 1370, "text": "File.Delete(myPath);" }, { "code": null, "e": 1428, "s": 1391, "text": "The following is the complete code −" }, { "code": null, "e": 1439, "s": 1428, "text": " Live Demo" }, { "code": null, "e": 1642, "s": 1439, "text": "using System;\nusing System.IO;\npublic class Program {\n public static void Main() {\n String myPath = @\"C:\\New\\amit.txt\";\n Console.WriteLine(\"Deleting File\");\n File.Delete(myPath);\n }\n}" }, { "code": null, "e": 1656, "s": 1642, "text": "Deleting File" } ]
Ruby | Enumerable find_all() function
05 Dec, 2019 The find_all() of enumerable is an inbuilt method in Ruby returns the items in the enumerable which satisfies the given condition in the block. It returns an enumerator if no block is given. Syntax: enu.find_all { |obj| block } Parameters: The function takes a block whose condition is used to find the elements. Return Value: It returns the items in the enum which satisfies the condition in the block. Iy t returns an enumerator if no block is given. Example 1: # Ruby program for find_all method in Enumerable # Initialize enu = (1..10) # Printsenu.find_all { |obj| obj % 2 == 1} Output: [1, 3, 5, 7, 9] Example 2: # Ruby program for find_all method in Enumerable # Initialize enu = [1, 7, 10, 11] # Printsenu.find_all Output: Enumerator: [1, 7, 10, 11]:find_all Ruby Collections Ruby Enumerable-class Ruby-Methods Ruby Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Make a Custom Array of Hashes in Ruby? Ruby | Enumerator each_with_index function Ruby | unless Statement and unless Modifier Ruby For Beginners Ruby | Array class find_index() operation Ruby | String concat Method Ruby | Types of Variables Ruby | Array shift() function Ruby on Rails Introduction
[ { "code": null, "e": 28, "s": 0, "text": "\n05 Dec, 2019" }, { "code": null, "e": 219, "s": 28, "text": "The find_all() of enumerable is an inbuilt method in Ruby returns the items in the enumerable which satisfies the given condition in the block. It returns an enumerator if no block is given." }, { "code": null, "e": 256, "s": 219, "text": "Syntax: enu.find_all { |obj| block }" }, { "code": null, "e": 341, "s": 256, "text": "Parameters: The function takes a block whose condition is used to find the elements." }, { "code": null, "e": 481, "s": 341, "text": "Return Value: It returns the items in the enum which satisfies the condition in the block. Iy t returns an enumerator if no block is given." }, { "code": null, "e": 492, "s": 481, "text": "Example 1:" }, { "code": "# Ruby program for find_all method in Enumerable # Initialize enu = (1..10) # Printsenu.find_all { |obj| obj % 2 == 1}", "e": 613, "s": 492, "text": null }, { "code": null, "e": 621, "s": 613, "text": "Output:" }, { "code": null, "e": 638, "s": 621, "text": "[1, 3, 5, 7, 9]\n" }, { "code": null, "e": 649, "s": 638, "text": "Example 2:" }, { "code": "# Ruby program for find_all method in Enumerable # Initialize enu = [1, 7, 10, 11] # Printsenu.find_all", "e": 755, "s": 649, "text": null }, { "code": null, "e": 763, "s": 755, "text": "Output:" }, { "code": null, "e": 800, "s": 763, "text": "Enumerator: [1, 7, 10, 11]:find_all\n" }, { "code": null, "e": 817, "s": 800, "text": "Ruby Collections" }, { "code": null, "e": 839, "s": 817, "text": "Ruby Enumerable-class" }, { "code": null, "e": 852, "s": 839, "text": "Ruby-Methods" }, { "code": null, "e": 857, "s": 852, "text": "Ruby" }, { "code": null, "e": 955, "s": 857, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1001, "s": 955, "text": "How to Make a Custom Array of Hashes in Ruby?" }, { "code": null, "e": 1044, "s": 1001, "text": "Ruby | Enumerator each_with_index function" }, { "code": null, "e": 1088, "s": 1044, "text": "Ruby | unless Statement and unless Modifier" }, { "code": null, "e": 1107, "s": 1088, "text": "Ruby For Beginners" }, { "code": null, "e": 1149, "s": 1107, "text": "Ruby | Array class find_index() operation" }, { "code": null, "e": 1177, "s": 1149, "text": "Ruby | String concat Method" }, { "code": null, "e": 1203, "s": 1177, "text": "Ruby | Types of Variables" }, { "code": null, "e": 1233, "s": 1203, "text": "Ruby | Array shift() function" } ]
Python string length | len()
08 Jul, 2022 Python len() function returns the length of the string. Syntax: len(string) Return: It returns an integer which is the length of the string. len() methods with string in Python. Python3 string = "Geeksforgeeks"print(len(string)) Output: 13 Here we are counting length of the tuples and list. Python # Python program to demonstrate the use of# len() method # with tupletup = (1,2,3)print(len(tup)) # with listl = [1,2,3,4]print(len(l)) Output: 3 4 Python3 print(len(True)) Output: TypeError: object of type 'bool' has no len() Python3 # Python program to demonstrate the use of# len() method dic = {'a':1, 'b': 2}print(len(dic)) s = { 1, 2, 3, 4}print(len(s)) Output: 2 4 Python3 class Public: def __init__(self, number): self.number = number def __len__(self): return self.number obj = Public(12)print(len(obj)) Output: 12 Time complexity : len() function has time complexity of O(1). in average and amortized case kumar_satyam rajeev0719singh devendrasalunke python-string Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Different ways to create Pandas Dataframe Enumerate() in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Convert integer to string in Python Python OOPs Concepts Python | os.path.join() method How to drop one or multiple columns in Pandas Dataframe
[ { "code": null, "e": 53, "s": 25, "text": "\n08 Jul, 2022" }, { "code": null, "e": 110, "s": 53, "text": "Python len() function returns the length of the string. " }, { "code": null, "e": 131, "s": 110, "text": "Syntax: len(string) " }, { "code": null, "e": 197, "s": 131, "text": "Return: It returns an integer which is the length of the string. " }, { "code": null, "e": 234, "s": 197, "text": "len() methods with string in Python." }, { "code": null, "e": 242, "s": 234, "text": "Python3" }, { "code": "string = \"Geeksforgeeks\"print(len(string))", "e": 285, "s": 242, "text": null }, { "code": null, "e": 293, "s": 285, "text": "Output:" }, { "code": null, "e": 296, "s": 293, "text": "13" }, { "code": null, "e": 348, "s": 296, "text": "Here we are counting length of the tuples and list." }, { "code": null, "e": 355, "s": 348, "text": "Python" }, { "code": "# Python program to demonstrate the use of# len() method # with tupletup = (1,2,3)print(len(tup)) # with listl = [1,2,3,4]print(len(l))", "e": 495, "s": 355, "text": null }, { "code": null, "e": 504, "s": 495, "text": "Output: " }, { "code": null, "e": 508, "s": 504, "text": "3\n4" }, { "code": null, "e": 516, "s": 508, "text": "Python3" }, { "code": "print(len(True))", "e": 533, "s": 516, "text": null }, { "code": null, "e": 541, "s": 533, "text": "Output:" }, { "code": null, "e": 587, "s": 541, "text": "TypeError: object of type 'bool' has no len()" }, { "code": null, "e": 595, "s": 587, "text": "Python3" }, { "code": "# Python program to demonstrate the use of# len() method dic = {'a':1, 'b': 2}print(len(dic)) s = { 1, 2, 3, 4}print(len(s))", "e": 724, "s": 595, "text": null }, { "code": null, "e": 732, "s": 724, "text": "Output:" }, { "code": null, "e": 736, "s": 732, "text": "2\n4" }, { "code": null, "e": 744, "s": 736, "text": "Python3" }, { "code": "class Public: def __init__(self, number): self.number = number def __len__(self): return self.number obj = Public(12)print(len(obj))", "e": 902, "s": 744, "text": null }, { "code": null, "e": 910, "s": 902, "text": "Output:" }, { "code": null, "e": 913, "s": 910, "text": "12" }, { "code": null, "e": 932, "s": 913, "text": "Time complexity : " }, { "code": null, "e": 1007, "s": 932, "text": "len() function has time complexity of O(1). in average and amortized case" }, { "code": null, "e": 1020, "s": 1007, "text": "kumar_satyam" }, { "code": null, "e": 1036, "s": 1020, "text": "rajeev0719singh" }, { "code": null, "e": 1052, "s": 1036, "text": "devendrasalunke" }, { "code": null, "e": 1066, "s": 1052, "text": "python-string" }, { "code": null, "e": 1073, "s": 1066, "text": "Python" }, { "code": null, "e": 1171, "s": 1073, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1213, "s": 1171, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1235, "s": 1213, "text": "Enumerate() in Python" }, { "code": null, "e": 1261, "s": 1235, "text": "Python String | replace()" }, { "code": null, "e": 1293, "s": 1261, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1322, "s": 1293, "text": "*args and **kwargs in Python" }, { "code": null, "e": 1349, "s": 1322, "text": "Python Classes and Objects" }, { "code": null, "e": 1385, "s": 1349, "text": "Convert integer to string in Python" }, { "code": null, "e": 1406, "s": 1385, "text": "Python OOPs Concepts" }, { "code": null, "e": 1437, "s": 1406, "text": "Python | os.path.join() method" } ]
How To Setup And Use Anonsurf On kali Linux
17 Oct, 2021 Anonsurf is one of the good anonymizing tools of Linux distribution. It helps us make our network tunnel secure. This tool uses TOR iptables to anonymize our network system. First of all, you can make a separate directory for this tool for your convenience and git clone the following URL or you can simply run this command in the terminal: For a separate directory: mkdir Anonsurf && cd Anonsurf Clone the URL in your terminal: git clone https://github.com/Und3rf10w/kali-anonsurf.git Now change the directory and go to the kali-anonsurf run the installer script: sudo ./installer.sh Example 1: Now run this command for anonsurf start. sudo anonsurf Example 2: To start this tool just simply run this command, a pop-up will show on your screen. anonsurf start If you want to kill all the background processes, you can choose yes or just go ahead. It will clear the miscellaneous space from your disk. Example 3: If this tool isn’t running and you are running the stop command a pop up will show as shown in figure anonsurf stop Example 4: You can restart it again if you face any problem during the task. anonsurf restart Example 5: Change id This tool connects our system with the tor browser and if we want to change or IP address then we can use this command, in the following images you can see our system is connected with tor or not. anonsurf changeid Before: After: Example 6: You can check what is current IP address is after connecting with tor network. anonsurf myip Example 7: Change status This helps us to check that our tool is still running or not, you can find details of browser download/upload speed. anonsurf status That’s all was overview for this tool now you can explore yourself many things. After finishing your work you can stop it by stop command. 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 nohup Command in Linux with Examples mv command in Linux with examples chmod command in Linux with examples Array Basics in Shell Scripting | Set 1 Introduction to Linux Operating System Basic Operators in Shell Scripting
[ { "code": null, "e": 28, "s": 0, "text": "\n17 Oct, 2021" }, { "code": null, "e": 203, "s": 28, "text": "Anonsurf is one of the good anonymizing tools of Linux distribution. It helps us make our network tunnel secure. This tool uses TOR iptables to anonymize our network system. " }, { "code": null, "e": 370, "s": 203, "text": "First of all, you can make a separate directory for this tool for your convenience and git clone the following URL or you can simply run this command in the terminal:" }, { "code": null, "e": 396, "s": 370, "text": "For a separate directory:" }, { "code": null, "e": 426, "s": 396, "text": "mkdir Anonsurf && cd Anonsurf" }, { "code": null, "e": 458, "s": 426, "text": "Clone the URL in your terminal:" }, { "code": null, "e": 515, "s": 458, "text": "git clone https://github.com/Und3rf10w/kali-anonsurf.git" }, { "code": null, "e": 594, "s": 515, "text": "Now change the directory and go to the kali-anonsurf run the installer script:" }, { "code": null, "e": 614, "s": 594, "text": "sudo ./installer.sh" }, { "code": null, "e": 666, "s": 614, "text": "Example 1: Now run this command for anonsurf start." }, { "code": null, "e": 680, "s": 666, "text": "sudo anonsurf" }, { "code": null, "e": 775, "s": 680, "text": "Example 2: To start this tool just simply run this command, a pop-up will show on your screen." }, { "code": null, "e": 790, "s": 775, "text": "anonsurf start" }, { "code": null, "e": 931, "s": 790, "text": "If you want to kill all the background processes, you can choose yes or just go ahead. It will clear the miscellaneous space from your disk." }, { "code": null, "e": 1044, "s": 931, "text": "Example 3: If this tool isn’t running and you are running the stop command a pop up will show as shown in figure" }, { "code": null, "e": 1058, "s": 1044, "text": "anonsurf stop" }, { "code": null, "e": 1135, "s": 1058, "text": "Example 4: You can restart it again if you face any problem during the task." }, { "code": null, "e": 1152, "s": 1135, "text": "anonsurf restart" }, { "code": null, "e": 1173, "s": 1152, "text": "Example 5: Change id" }, { "code": null, "e": 1370, "s": 1173, "text": "This tool connects our system with the tor browser and if we want to change or IP address then we can use this command, in the following images you can see our system is connected with tor or not." }, { "code": null, "e": 1388, "s": 1370, "text": "anonsurf changeid" }, { "code": null, "e": 1396, "s": 1388, "text": "Before:" }, { "code": null, "e": 1403, "s": 1396, "text": "After:" }, { "code": null, "e": 1493, "s": 1403, "text": "Example 6: You can check what is current IP address is after connecting with tor network." }, { "code": null, "e": 1507, "s": 1493, "text": "anonsurf myip" }, { "code": null, "e": 1532, "s": 1507, "text": "Example 7: Change status" }, { "code": null, "e": 1649, "s": 1532, "text": "This helps us to check that our tool is still running or not, you can find details of browser download/upload speed." }, { "code": null, "e": 1665, "s": 1649, "text": "anonsurf status" }, { "code": null, "e": 1804, "s": 1665, "text": "That’s all was overview for this tool now you can explore yourself many things. After finishing your work you can stop it by stop command." }, { "code": null, "e": 1815, "s": 1804, "text": "Kali-Linux" }, { "code": null, "e": 1827, "s": 1815, "text": "Linux-Tools" }, { "code": null, "e": 1838, "s": 1827, "text": "Linux-Unix" }, { "code": null, "e": 1936, "s": 1838, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1962, "s": 1936, "text": "Docker - COPY Instruction" }, { "code": null, "e": 1997, "s": 1962, "text": "scp command in Linux with Examples" }, { "code": null, "e": 2034, "s": 1997, "text": "chown command in Linux with Examples" }, { "code": null, "e": 2063, "s": 2034, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 2100, "s": 2063, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 2134, "s": 2100, "text": "mv command in Linux with examples" }, { "code": null, "e": 2171, "s": 2134, "text": "chmod command in Linux with examples" }, { "code": null, "e": 2211, "s": 2171, "text": "Array Basics in Shell Scripting | Set 1" }, { "code": null, "e": 2250, "s": 2211, "text": "Introduction to Linux Operating System" } ]
SQL | UNIQUE Constraint
06 Sep, 2018 SQL Constraints Unique constraint in SQL is used to check whether the sub query has duplicate tuples in it’s result. It returns a boolean value indicating the presence/absence of duplicate tuples. Unique construct returns true only if the sub query has no duplicate tuples, else it return false. Important Points: Evaluates to true on an empty sub query. Returns true only if there are unique tuples present as the output of the sub query (two tuples are unique if the value of any attribute of the two tuples differ). Returns true if the sub query has two duplicate rows with at least one attribute as NULL. Syntax: SELECT table.ID FROM table WHERE UNIQUE (SELECT table2.ID FROM table2 WHERE table.ID = table2.ID); Note: During the execution, first the outer query is evaluated to obtain table.ID. Following this, the inner sub query is processed which produces a new relation that contains the output of inner query such that table.ID == table2.ID. If every row in the new relation is unique then unique returns true and the corresponding table.ID is added as a tuple in the output relation produced. However, if every row in the new relation is not unique then unique evaluates to false and the corresponding table.ID is not add to the output relation. Unique applied to a sub query return false if and only if there are two tuples t1 and t2 such that t1 = t2. It considers t1 and t2 to be two different tuple, when unique is applied to a sub query that contains t1 and t2 such that t1 = t2 and at least one of the attribute of these tuples contains a NULL value. Unique predicate in this case evaluates to true. This is because, a NULL value in SQL is treated as an unknown value therefore, two NULL values are considered to be distinct. Note: The SQL statement without UNIQUE clause can also be written as: SELECT table.ID FROM table WHERE 1 <= (SELECT count(table2.ID) FROM table2 WHERE table.ID = table2.ID); Queries Example 1: Find all the instructors that taught at most one course in the year 2017.Instructor relation: SELECT I.EMPLOYEEID, I.NAME FROM Instructor as I WHERE UNIQUE (SELECT Inst.EMPLOYEEID FROM Instructor as Inst WHERE I.EMPLOYEEID = Inst.EMPLOYEEID and Inst.YEAR = 2017); Output: Explanation: In the Instructor relation, only instructors Will and Smith teach a single course during the year 2017. The sub query corresponding to these instructors contains only a single tuple and therefore the unique clause corresponding to these instructors evaluates to true thereby producing these two instructors in the output relation. Example 2: Find all the courses in Computer Science department that has only a single instructor allotted to that course.Course relation: SELECT C.COURSEID, C.NAME FROM Course as C WHERE UNIQUE (SELECT T.INSTRUCTORID FROM Course as T WHERE T.COURSEID = C.COURSEID and C.DEPARTMENT = 'Computer Science'); Output: Explanation: In the course relation, the only courses in computer science department that has a single instructor allotted are Operating System and Programming. The unique constraint corresponding to these two courses has only a single tuple consisting of the corresponding instructors. So, the unique clause for these two courses evaluates to true and these courses are displayed in output relation. Other courses in the Course relation either have two or more instructors or they do not belong to computer science department and therefore, those courses aren’t displayed in the output relation. This article is contributed by Mayank Kumar. 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. lonewolf_ab SQL-Clauses-Operators SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. CTE in SQL How to Update Multiple Columns in Single Update Statement in SQL? SQL Interview Questions SQL | Views Difference between DELETE, DROP and TRUNCATE MySQL | Group_CONCAT() Function Window functions in SQL SQL | GROUP BY Difference between DDL and DML in DBMS Difference between DELETE and TRUNCATE
[ { "code": null, "e": 54, "s": 26, "text": "\n06 Sep, 2018" }, { "code": null, "e": 70, "s": 54, "text": "SQL Constraints" }, { "code": null, "e": 350, "s": 70, "text": "Unique constraint in SQL is used to check whether the sub query has duplicate tuples in it’s result. It returns a boolean value indicating the presence/absence of duplicate tuples. Unique construct returns true only if the sub query has no duplicate tuples, else it return false." }, { "code": null, "e": 368, "s": 350, "text": "Important Points:" }, { "code": null, "e": 409, "s": 368, "text": "Evaluates to true on an empty sub query." }, { "code": null, "e": 573, "s": 409, "text": "Returns true only if there are unique tuples present as the output of the sub query (two tuples are unique if the value of any attribute of the two tuples differ)." }, { "code": null, "e": 663, "s": 573, "text": "Returns true if the sub query has two duplicate rows with at least one attribute as NULL." }, { "code": null, "e": 671, "s": 663, "text": "Syntax:" }, { "code": null, "e": 800, "s": 671, "text": "SELECT table.ID\nFROM table\nWHERE UNIQUE (SELECT table2.ID\n FROM table2\n WHERE table.ID = table2.ID);\n" }, { "code": null, "e": 1340, "s": 800, "text": "Note: During the execution, first the outer query is evaluated to obtain table.ID. Following this, the inner sub query is processed which produces a new relation that contains the output of inner query such that table.ID == table2.ID. If every row in the new relation is unique then unique returns true and the corresponding table.ID is added as a tuple in the output relation produced. However, if every row in the new relation is not unique then unique evaluates to false and the corresponding table.ID is not add to the output relation." }, { "code": null, "e": 1826, "s": 1340, "text": "Unique applied to a sub query return false if and only if there are two tuples t1 and t2 such that t1 = t2. It considers t1 and t2 to be two different tuple, when unique is applied to a sub query that contains t1 and t2 such that t1 = t2 and at least one of the attribute of these tuples contains a NULL value. Unique predicate in this case evaluates to true. This is because, a NULL value in SQL is treated as an unknown value therefore, two NULL values are considered to be distinct." }, { "code": null, "e": 1896, "s": 1826, "text": "Note: The SQL statement without UNIQUE clause can also be written as:" }, { "code": null, "e": 2029, "s": 1896, "text": "SELECT table.ID\nFROM table\nWHERE 1 <= (SELECT count(table2.ID)\n FROM table2\n WHERE table.ID = table2.ID);" }, { "code": null, "e": 2037, "s": 2029, "text": "Queries" }, { "code": null, "e": 2142, "s": 2037, "text": "Example 1: Find all the instructors that taught at most one course in the year 2017.Instructor relation:" }, { "code": null, "e": 2366, "s": 2142, "text": "SELECT I.EMPLOYEEID, I.NAME\nFROM Instructor as I\nWHERE UNIQUE (SELECT Inst.EMPLOYEEID\n FROM Instructor as Inst\n WHERE I.EMPLOYEEID = Inst.EMPLOYEEID\n and Inst.YEAR = 2017);" }, { "code": null, "e": 2374, "s": 2366, "text": "Output:" }, { "code": null, "e": 2718, "s": 2374, "text": "Explanation: In the Instructor relation, only instructors Will and Smith teach a single course during the year 2017. The sub query corresponding to these instructors contains only a single tuple and therefore the unique clause corresponding to these instructors evaluates to true thereby producing these two instructors in the output relation." }, { "code": null, "e": 2856, "s": 2718, "text": "Example 2: Find all the courses in Computer Science department that has only a single instructor allotted to that course.Course relation:" }, { "code": null, "e": 3077, "s": 2856, "text": "SELECT C.COURSEID, C.NAME\nFROM Course as C\nWHERE UNIQUE (SELECT T.INSTRUCTORID\n FROM Course as T\n WHERE T.COURSEID = C.COURSEID \n and C.DEPARTMENT = 'Computer Science');" }, { "code": null, "e": 3085, "s": 3077, "text": "Output:" }, { "code": null, "e": 3682, "s": 3085, "text": "Explanation: In the course relation, the only courses in computer science department that has a single instructor allotted are Operating System and Programming. The unique constraint corresponding to these two courses has only a single tuple consisting of the corresponding instructors. So, the unique clause for these two courses evaluates to true and these courses are displayed in output relation. Other courses in the Course relation either have two or more instructors or they do not belong to computer science department and therefore, those courses aren’t displayed in the output relation." }, { "code": null, "e": 3982, "s": 3682, "text": "This article is contributed by Mayank Kumar. 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": 4107, "s": 3982, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 4119, "s": 4107, "text": "lonewolf_ab" }, { "code": null, "e": 4141, "s": 4119, "text": "SQL-Clauses-Operators" }, { "code": null, "e": 4145, "s": 4141, "text": "SQL" }, { "code": null, "e": 4149, "s": 4145, "text": "SQL" }, { "code": null, "e": 4247, "s": 4149, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4258, "s": 4247, "text": "CTE in SQL" }, { "code": null, "e": 4324, "s": 4258, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 4348, "s": 4324, "text": "SQL Interview Questions" }, { "code": null, "e": 4360, "s": 4348, "text": "SQL | Views" }, { "code": null, "e": 4405, "s": 4360, "text": "Difference between DELETE, DROP and TRUNCATE" }, { "code": null, "e": 4437, "s": 4405, "text": "MySQL | Group_CONCAT() Function" }, { "code": null, "e": 4461, "s": 4437, "text": "Window functions in SQL" }, { "code": null, "e": 4476, "s": 4461, "text": "SQL | GROUP BY" }, { "code": null, "e": 4515, "s": 4476, "text": "Difference between DDL and DML in DBMS" } ]
wxPython – Change font colour of RadioBox
01 Sep, 2021 In this article we are going to learn how can we change the foreground colour of Radio Box present in the frame. In order to do that we are going to use SetForegroundColour() method. SetForegroundColour() function takes wx.Colour argument which will be used as foreground colour for Radio Box. Syntax: wx.RadioBox.SetForegroundColour(self, colour)Parameters Code Example: Python3 import wx class FrameUI(wx.Frame): def __init__(self, parent, title): super(FrameUI, self).__init__(parent, title = title, size =(300, 200)) # function for in-frame components self.InitUI() def InitUI(self): # parent panel for radio box pnl = wx.Panel(self) # list of choices lblList = ['Radio One', 'Radio Two'] # create radio box containing above list self.rbox = wx.RadioBox(pnl, label ='RadioBox', pos =(80, 10), choices = lblList, majorDimension = 1, style = wx.RA_SPECIFY_ROWS) # change foreground colour for radio box self.rbox.SetForegroundColour((0, 0, 255, 255)) # set frame in centre self.Centre() # set size of frame self.SetSize((400, 250)) # show output frame self.Show(True) # wx App instanceex = wx.App()# Example instanceFrameUI(None, 'RadioButton and RadioBox')ex.MainLoop() Output Window: abhishek0719kadiyan Python wxPython-RadioBox Python-gui Python-wxPython 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 Python | os.path.join() method 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": 28, "s": 0, "text": "\n01 Sep, 2021" }, { "code": null, "e": 323, "s": 28, "text": "In this article we are going to learn how can we change the foreground colour of Radio Box present in the frame. In order to do that we are going to use SetForegroundColour() method. SetForegroundColour() function takes wx.Colour argument which will be used as foreground colour for Radio Box. " }, { "code": null, "e": 388, "s": 323, "text": "Syntax: wx.RadioBox.SetForegroundColour(self, colour)Parameters " }, { "code": null, "e": 404, "s": 388, "text": "Code Example: " }, { "code": null, "e": 412, "s": 404, "text": "Python3" }, { "code": "import wx class FrameUI(wx.Frame): def __init__(self, parent, title): super(FrameUI, self).__init__(parent, title = title, size =(300, 200)) # function for in-frame components self.InitUI() def InitUI(self): # parent panel for radio box pnl = wx.Panel(self) # list of choices lblList = ['Radio One', 'Radio Two'] # create radio box containing above list self.rbox = wx.RadioBox(pnl, label ='RadioBox', pos =(80, 10), choices = lblList, majorDimension = 1, style = wx.RA_SPECIFY_ROWS) # change foreground colour for radio box self.rbox.SetForegroundColour((0, 0, 255, 255)) # set frame in centre self.Centre() # set size of frame self.SetSize((400, 250)) # show output frame self.Show(True) # wx App instanceex = wx.App()# Example instanceFrameUI(None, 'RadioButton and RadioBox')ex.MainLoop()", "e": 1380, "s": 412, "text": null }, { "code": null, "e": 1397, "s": 1380, "text": "Output Window: " }, { "code": null, "e": 1419, "s": 1399, "text": "abhishek0719kadiyan" }, { "code": null, "e": 1444, "s": 1419, "text": "Python wxPython-RadioBox" }, { "code": null, "e": 1455, "s": 1444, "text": "Python-gui" }, { "code": null, "e": 1471, "s": 1455, "text": "Python-wxPython" }, { "code": null, "e": 1478, "s": 1471, "text": "Python" }, { "code": null, "e": 1576, "s": 1478, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1608, "s": 1576, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1635, "s": 1608, "text": "Python Classes and Objects" }, { "code": null, "e": 1656, "s": 1635, "text": "Python OOPs Concepts" }, { "code": null, "e": 1687, "s": 1656, "text": "Python | os.path.join() method" }, { "code": null, "e": 1743, "s": 1687, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 1766, "s": 1743, "text": "Introduction To PYTHON" }, { "code": null, "e": 1808, "s": 1766, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 1850, "s": 1808, "text": "Check if element exists in list in Python" }, { "code": null, "e": 1889, "s": 1850, "text": "Python | datetime.timedelta() function" } ]
Create a directory in Python
29 Dec, 2020 The OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. The os and os.path modules include many functions to interact with the file system. 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. There are different methods available in the OS module for creating a director. These are – os.mkdir() os.makedirs() os.mkdir() method in Python is used to create a directory named path with the specified numeric mode. This method raise FileExistsError if the directory to be created already exists. Syntax: os.mkdir(path, mode = 0o777, *, dir_fd = None) Parameter:path: A path-like object representing a file system path. A path-like object is either a string or bytes object representing a path.mode (optional): A Integer value representing mode of the directory to be created. If this parameter is omitted then default value Oo777 is used.dir_fd (optional): A file descriptor referring to a directory. The default value of this parameter is None.If the specified path is absolute then dir_fd is ignored. Note: The ‘*’ in parameter list indicates that all following parameters (Here in our case ‘dir_fd’) are keyword-only parameters and they can be provided using their name, not as positional parameter. Return Type: This method does not return any value. Example #1: Use of os.mkdir() method to create directory/file # Python program to explain os.mkdir() method # importing os moduleimport os # Directorydirectory = "GeeksforGeeks" # Parent Directory pathparent_dir = "D:/Pycharm projects/" # Pathpath = os.path.join(parent_dir, directory) # Create the directory# 'GeeksForGeeks' in# '/home / User / Documents'os.mkdir(path)print("Directory '% s' created" % directory) # Directorydirectory = "Geeks" # Parent Directory pathparent_dir = "D:/Pycharm projects" # modemode = 0o666 # Pathpath = os.path.join(parent_dir, directory) # Create the directory# 'GeeksForGeeks' in# '/home / User / Documents'# with mode 0o666os.mkdir(path, mode)print("Directory '% s' created" % directory) Output: Directory 'GeeksforGeeks' created Directory 'Geeks' created Example #2: Errors while using os.mkdir() method. # Python program to explain os.mkdir() method # importing os module import os # Directory directory = "GeeksForGeeks" # Parent Directory path parent_dir = "D:/Pycharm projects/" # Path path = os.path.join(parent_dir, directory) # Create the directory # 'GeeksForGeeks' in # '/home / User / Documents' os.mkdir(path) print("Directory '% s' created" % directory) # if directory / file that # is to be created already # exists then 'FileExistsError' # will be raised by os.mkdir() method # Similarly, if the specified path # is invalid 'FileNotFoundError' Error # will be raised Output: Traceback (most recent call last): File "gfg.py", line 18, in os.mkdir(path) FileExistsError: [WinError 183] Cannot create a file when that file / /already exists: 'D:/Pycharm projects/GeeksForGeeks' Example #3: Handling error while using os.mkdir() method. # Python program to explain os.mkdir() method # importing os module import os # path path = 'D:/Pycharm projects / GeeksForGeeks' # Create the directory # 'GeeksForGeeks' in # '/home / User / Documents' try: os.mkdir(path) except OSError as error: print(error) Output: [WinError 183] Cannot create a file when that file/ /already exists: 'D:/Pycharm projects/GeeksForGeeks' os.makedirs() method in Python is used to create a directory recursively. That means while making leaf directory if any intermediate-level directory is missing, os.makedirs() method will create them all.For example, consider the following path: D:/Pycharm projects/GeeksForGeeks/Authors/Nikhil Suppose we want to create directory ‘Nikhil’ but Directory ‘GeeksForGeeks’ and ‘Authors’ are unavailable in the path. Then os.makedirs() method will create all unavailable/missing directories in the specified path. ‘GeeksForGeeks’ and ‘Authors’ will be created first then ‘Nikhil’ directory will be created. Syntax: os.makedirs(path, mode = 0o777, exist_ok = False) Parameter:path: A path-like object representing a file system path. A path-like object is either a string or bytes object representing a path.mode (optional): A Integer value representing mode of the newly created directory. If this parameter is omitted then the default value Oo777 is used.exist_ok (optional): A default value False is used for this parameter. If the target directory already exists an OSError is raised if its value is False otherwise not. Return Type: This method does not return any value. Example #1: Use of os.makedirs() method to create directory. # Python program to explain os.makedirs() method # importing os module import os # Leaf directory directory = "Nikhil" # Parent Directories parent_dir = "D:/Pycharm projects/GeeksForGeeks/Authors" # Path path = os.path.join(parent_dir, directory) # Create the directory # 'Nikhil' os.makedirs(path) print("Directory '% s' created" % directory) # Directory 'GeeksForGeeks' and 'Authors' will # be created too # if it does not exists # Leaf directory directory = "c" # Parent Directories parent_dir = "D:/Pycharm projects/GeeksforGeeks/a/b" # mode mode = 0o666 path = os.path.join(parent_dir, directory) # Create the directory 'c' os.makedirs(path, mode) print("Directory '% s' created" % directory) # 'GeeksForGeeks', 'a', and 'b' # will also be created if # it does not exists # If any of the intermediate level # directory is missing # os.makedirs() method will # create them # os.makedirs() method can be # used to create a directory tree Output: Directory 'Nikhil' created Directory 'c' created Example #2: # Python program to explain os.makedirs() method # importing os module import os # os.makedirs() method will raise # an OSError if the directory # to be created already exists # Directory directory = "Nikhil" # Parent Directory path parent_dir = "D:/Pycharm projects/GeeksForGeeks/Authors" # Path path = os.path.join(parent_dir, directory) # Create the directory # 'Nikhil' os.makedirs(path) print("Directory '% s' created" % directory) Output: Traceback (most recent call last): File "gfg.py", line 22, in os.makedirs(path) File "C:\Users\Nikhil Aggarwal\AppData\Local\Programs\Python/ / \Python38-32\lib\os.py", line 221, in makedirs mkdir(name, mode) FileExistsError: [WinError 183] Cannot create a file when that/ / file already exists: 'D:/Pycharm projects/GeeksForGeeks/Authors\\Nikhil' Example #3: Handling errors while using os.makedirs() method. # Python program to explain os.makedirs() method # importing os moduleimport os # os.makedirs() method will raise# an OSError if the directory# to be created already exists# But It can be suppressed by# setting the value of a parameter# exist_ok as True # Directorydirectory = "Nikhil" # Parent Directory pathparent_dir = "D:/Pycharm projects/GeeksForGeeks/Authors" # Pathpath = os.path.join(parent_dir, directory) # Create the directory# 'Nikhil'try: os.makedirs(path, exist_ok = True) print("Directory '%s' created successfully" % directory)except OSError as error: print("Directory '%s' can not be created" % directory) # By setting exist_ok as True# error caused due already# existing directory can be suppressed# but other OSError may be raised# due to other error like# invalid path name Output: Directory 'Nikhil' created successfully Python file-handling-programs 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.
[ { "code": null, "e": 54, "s": 26, "text": "\n29 Dec, 2020" }, { "code": null, "e": 555, "s": 54, "text": "The OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. The os and os.path modules include many functions to interact with the file system. 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." }, { "code": null, "e": 647, "s": 555, "text": "There are different methods available in the OS module for creating a director. These are –" }, { "code": null, "e": 658, "s": 647, "text": "os.mkdir()" }, { "code": null, "e": 672, "s": 658, "text": "os.makedirs()" }, { "code": null, "e": 855, "s": 672, "text": "os.mkdir() method in Python is used to create a directory named path with the specified numeric mode. This method raise FileExistsError if the directory to be created already exists." }, { "code": null, "e": 910, "s": 855, "text": "Syntax: os.mkdir(path, mode = 0o777, *, dir_fd = None)" }, { "code": null, "e": 1362, "s": 910, "text": "Parameter:path: A path-like object representing a file system path. A path-like object is either a string or bytes object representing a path.mode (optional): A Integer value representing mode of the directory to be created. If this parameter is omitted then default value Oo777 is used.dir_fd (optional): A file descriptor referring to a directory. The default value of this parameter is None.If the specified path is absolute then dir_fd is ignored." }, { "code": null, "e": 1562, "s": 1362, "text": "Note: The ‘*’ in parameter list indicates that all following parameters (Here in our case ‘dir_fd’) are keyword-only parameters and they can be provided using their name, not as positional parameter." }, { "code": null, "e": 1614, "s": 1562, "text": "Return Type: This method does not return any value." }, { "code": null, "e": 1676, "s": 1614, "text": "Example #1: Use of os.mkdir() method to create directory/file" }, { "code": "# Python program to explain os.mkdir() method # importing os moduleimport os # Directorydirectory = \"GeeksforGeeks\" # Parent Directory pathparent_dir = \"D:/Pycharm projects/\" # Pathpath = os.path.join(parent_dir, directory) # Create the directory# 'GeeksForGeeks' in# '/home / User / Documents'os.mkdir(path)print(\"Directory '% s' created\" % directory) # Directorydirectory = \"Geeks\" # Parent Directory pathparent_dir = \"D:/Pycharm projects\" # modemode = 0o666 # Pathpath = os.path.join(parent_dir, directory) # Create the directory# 'GeeksForGeeks' in# '/home / User / Documents'# with mode 0o666os.mkdir(path, mode)print(\"Directory '% s' created\" % directory)", "e": 2348, "s": 1676, "text": null }, { "code": null, "e": 2356, "s": 2348, "text": "Output:" }, { "code": null, "e": 2417, "s": 2356, "text": "Directory 'GeeksforGeeks' created\nDirectory 'Geeks' created\n" }, { "code": null, "e": 2467, "s": 2417, "text": "Example #2: Errors while using os.mkdir() method." }, { "code": "# Python program to explain os.mkdir() method # importing os module import os # Directory directory = \"GeeksForGeeks\" # Parent Directory path parent_dir = \"D:/Pycharm projects/\" # Path path = os.path.join(parent_dir, directory) # Create the directory # 'GeeksForGeeks' in # '/home / User / Documents' os.mkdir(path) print(\"Directory '% s' created\" % directory) # if directory / file that # is to be created already # exists then 'FileExistsError' # will be raised by os.mkdir() method # Similarly, if the specified path # is invalid 'FileNotFoundError' Error # will be raised ", "e": 3075, "s": 2467, "text": null }, { "code": null, "e": 3083, "s": 3075, "text": "Output:" }, { "code": null, "e": 3308, "s": 3083, "text": "Traceback (most recent call last):\n File \"gfg.py\", line 18, in \n os.mkdir(path)\nFileExistsError: [WinError 183] Cannot create a file when that file /\n /already exists: 'D:/Pycharm projects/GeeksForGeeks'\n" }, { "code": null, "e": 3366, "s": 3308, "text": "Example #3: Handling error while using os.mkdir() method." }, { "code": "# Python program to explain os.mkdir() method # importing os module import os # path path = 'D:/Pycharm projects / GeeksForGeeks' # Create the directory # 'GeeksForGeeks' in # '/home / User / Documents' try: os.mkdir(path) except OSError as error: print(error) ", "e": 3652, "s": 3366, "text": null }, { "code": null, "e": 3660, "s": 3652, "text": "Output:" }, { "code": null, "e": 3780, "s": 3660, "text": "[WinError 183] Cannot create a file when that file/\n /already exists: 'D:/Pycharm projects/GeeksForGeeks'\n" }, { "code": null, "e": 4025, "s": 3780, "text": "os.makedirs() method in Python is used to create a directory recursively. That means while making leaf directory if any intermediate-level directory is missing, os.makedirs() method will create them all.For example, consider the following path:" }, { "code": null, "e": 4075, "s": 4025, "text": "D:/Pycharm projects/GeeksForGeeks/Authors/Nikhil\n" }, { "code": null, "e": 4383, "s": 4075, "text": "Suppose we want to create directory ‘Nikhil’ but Directory ‘GeeksForGeeks’ and ‘Authors’ are unavailable in the path. Then os.makedirs() method will create all unavailable/missing directories in the specified path. ‘GeeksForGeeks’ and ‘Authors’ will be created first then ‘Nikhil’ directory will be created." }, { "code": null, "e": 4441, "s": 4383, "text": "Syntax: os.makedirs(path, mode = 0o777, exist_ok = False)" }, { "code": null, "e": 4900, "s": 4441, "text": "Parameter:path: A path-like object representing a file system path. A path-like object is either a string or bytes object representing a path.mode (optional): A Integer value representing mode of the newly created directory. If this parameter is omitted then the default value Oo777 is used.exist_ok (optional): A default value False is used for this parameter. If the target directory already exists an OSError is raised if its value is False otherwise not." }, { "code": null, "e": 4952, "s": 4900, "text": "Return Type: This method does not return any value." }, { "code": null, "e": 5013, "s": 4952, "text": "Example #1: Use of os.makedirs() method to create directory." }, { "code": "# Python program to explain os.makedirs() method # importing os module import os # Leaf directory directory = \"Nikhil\" # Parent Directories parent_dir = \"D:/Pycharm projects/GeeksForGeeks/Authors\" # Path path = os.path.join(parent_dir, directory) # Create the directory # 'Nikhil' os.makedirs(path) print(\"Directory '% s' created\" % directory) # Directory 'GeeksForGeeks' and 'Authors' will # be created too # if it does not exists # Leaf directory directory = \"c\" # Parent Directories parent_dir = \"D:/Pycharm projects/GeeksforGeeks/a/b\" # mode mode = 0o666 path = os.path.join(parent_dir, directory) # Create the directory 'c' os.makedirs(path, mode) print(\"Directory '% s' created\" % directory) # 'GeeksForGeeks', 'a', and 'b' # will also be created if # it does not exists # If any of the intermediate level # directory is missing # os.makedirs() method will # create them # os.makedirs() method can be # used to create a directory tree ", "e": 6031, "s": 5013, "text": null }, { "code": null, "e": 6039, "s": 6031, "text": "Output:" }, { "code": null, "e": 6089, "s": 6039, "text": "Directory 'Nikhil' created\nDirectory 'c' created\n" }, { "code": null, "e": 6101, "s": 6089, "text": "Example #2:" }, { "code": "# Python program to explain os.makedirs() method # importing os module import os # os.makedirs() method will raise # an OSError if the directory # to be created already exists # Directory directory = \"Nikhil\" # Parent Directory path parent_dir = \"D:/Pycharm projects/GeeksForGeeks/Authors\" # Path path = os.path.join(parent_dir, directory) # Create the directory # 'Nikhil' os.makedirs(path) print(\"Directory '% s' created\" % directory) ", "e": 6572, "s": 6101, "text": null }, { "code": null, "e": 6580, "s": 6572, "text": "Output:" }, { "code": null, "e": 6964, "s": 6580, "text": "Traceback (most recent call last):\n File \"gfg.py\", line 22, in \n os.makedirs(path)\n File \"C:\\Users\\Nikhil Aggarwal\\AppData\\Local\\Programs\\Python/\n / \\Python38-32\\lib\\os.py\", line 221, in makedirs\n mkdir(name, mode)\nFileExistsError: [WinError 183] Cannot create a file when that/\n / file already exists: 'D:/Pycharm projects/GeeksForGeeks/Authors\\\\Nikhil'\n" }, { "code": null, "e": 7026, "s": 6964, "text": "Example #3: Handling errors while using os.makedirs() method." }, { "code": "# Python program to explain os.makedirs() method # importing os moduleimport os # os.makedirs() method will raise# an OSError if the directory# to be created already exists# But It can be suppressed by# setting the value of a parameter# exist_ok as True # Directorydirectory = \"Nikhil\" # Parent Directory pathparent_dir = \"D:/Pycharm projects/GeeksForGeeks/Authors\" # Pathpath = os.path.join(parent_dir, directory) # Create the directory# 'Nikhil'try: os.makedirs(path, exist_ok = True) print(\"Directory '%s' created successfully\" % directory)except OSError as error: print(\"Directory '%s' can not be created\" % directory) # By setting exist_ok as True# error caused due already# existing directory can be suppressed# but other OSError may be raised# due to other error like# invalid path name", "e": 7836, "s": 7026, "text": null }, { "code": null, "e": 7844, "s": 7836, "text": "Output:" }, { "code": null, "e": 7885, "s": 7844, "text": "Directory 'Nikhil' created successfully\n" }, { "code": null, "e": 7915, "s": 7885, "text": "Python file-handling-programs" }, { "code": null, "e": 7941, "s": 7915, "text": "Python os-module-programs" }, { "code": null, "e": 7962, "s": 7941, "text": "python-file-handling" }, { "code": null, "e": 7979, "s": 7962, "text": "python-os-module" }, { "code": null, "e": 7986, "s": 7979, "text": "Python" } ]
How to count the number of words in a string in PHP ?
27 May, 2020 Given a string containing some words and the task is to count number of words in a string str in PHP. In order to do this task, we have the following approaches: Approach 1: Using str_word_count() Method: The str_word_count() method is used to counts the number of words in a string. Syntax: str_word_count(string, return, char) Example: PHP <?php// PHP program to count number of// words in a string $str = " Geeks for Geeks "; // Using str_word_count() function to// count number of words in a string$len = str_word_count($str); // Printing the resultecho $len; ?> 3 Approach 2: Here the idea is to use trim(), preg_replace(), count() and explode() method. Step 1: Remove the trailing and leading white spaces using the trim() method and remove the multiple whitespace into a single space using preg_replace() method. Step 2: Convert the string into an array using the explode() method. Step 3: Now count() method counts the number of elements in an array. Step 4: Resultant is the number of words in a string. Example: PHP <?php// PHP program to count number// of words in a string // Function to count the wordsfunction get_num_of_words($string) { $string = preg_replace('/\s+/', ' ', trim($string)); $words = explode(" ", $string); return count($words);} $str = " Geeks for Geeks "; // Function call $len = get_num_of_words($str); // Printing the resultecho $len; ?> 3 Approach 3: Here the idea is to use trim(), substr_count(), and str_replace() method. Step 1: Remove the trailing and leading white spaces using the trim() method. Step 2: Convert the multiple white spaces into single space using the substr_count() and str_replace() method. Step 3: Now counts the number of word in a string using substr_count($str, ” “)+1 and return the result. Example: PHP <?php// PHP program to count number// of word in a string // Function to count the wordsfunction get_num_of_words($string) { $str = trim($string); while (substr_count($str, " ") > 0) { $str = str_replace(" ", " ", $str); } return substr_count($str, " ")+1;} $str = " Geeks for Geeks "; // Function call $len = get_num_of_words($str); // Printing the resultecho $len; ?> 3 PHP-string PHP PHP Programs Web Technologies Web technologies Questions PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n27 May, 2020" }, { "code": null, "e": 190, "s": 28, "text": "Given a string containing some words and the task is to count number of words in a string str in PHP. In order to do this task, we have the following approaches:" }, { "code": null, "e": 312, "s": 190, "text": "Approach 1: Using str_word_count() Method: The str_word_count() method is used to counts the number of words in a string." }, { "code": null, "e": 320, "s": 312, "text": "Syntax:" }, { "code": null, "e": 358, "s": 320, "text": "str_word_count(string, return, char)\n" }, { "code": null, "e": 367, "s": 358, "text": "Example:" }, { "code": null, "e": 371, "s": 367, "text": "PHP" }, { "code": "<?php// PHP program to count number of// words in a string $str = \" Geeks for Geeks \"; // Using str_word_count() function to// count number of words in a string$len = str_word_count($str); // Printing the resultecho $len; ?>", "e": 607, "s": 371, "text": null }, { "code": null, "e": 609, "s": 607, "text": "3" }, { "code": null, "e": 700, "s": 609, "text": "Approach 2: Here the idea is to use trim(), preg_replace(), count() and explode() method. " }, { "code": null, "e": 861, "s": 700, "text": "Step 1: Remove the trailing and leading white spaces using the trim() method and remove the multiple whitespace into a single space using preg_replace() method." }, { "code": null, "e": 930, "s": 861, "text": "Step 2: Convert the string into an array using the explode() method." }, { "code": null, "e": 1000, "s": 930, "text": "Step 3: Now count() method counts the number of elements in an array." }, { "code": null, "e": 1054, "s": 1000, "text": "Step 4: Resultant is the number of words in a string." }, { "code": null, "e": 1063, "s": 1054, "text": "Example:" }, { "code": null, "e": 1067, "s": 1063, "text": "PHP" }, { "code": "<?php// PHP program to count number// of words in a string // Function to count the wordsfunction get_num_of_words($string) { $string = preg_replace('/\\s+/', ' ', trim($string)); $words = explode(\" \", $string); return count($words);} $str = \" Geeks for Geeks \"; // Function call $len = get_num_of_words($str); // Printing the resultecho $len; ?>", "e": 1444, "s": 1067, "text": null }, { "code": null, "e": 1446, "s": 1444, "text": "3" }, { "code": null, "e": 1533, "s": 1446, "text": "Approach 3: Here the idea is to use trim(), substr_count(), and str_replace() method. " }, { "code": null, "e": 1611, "s": 1533, "text": "Step 1: Remove the trailing and leading white spaces using the trim() method." }, { "code": null, "e": 1722, "s": 1611, "text": "Step 2: Convert the multiple white spaces into single space using the substr_count() and str_replace() method." }, { "code": null, "e": 1827, "s": 1722, "text": "Step 3: Now counts the number of word in a string using substr_count($str, ” “)+1 and return the result." }, { "code": null, "e": 1836, "s": 1827, "text": "Example:" }, { "code": null, "e": 1840, "s": 1836, "text": "PHP" }, { "code": "<?php// PHP program to count number// of word in a string // Function to count the wordsfunction get_num_of_words($string) { $str = trim($string); while (substr_count($str, \" \") > 0) { $str = str_replace(\" \", \" \", $str); } return substr_count($str, \" \")+1;} $str = \" Geeks for Geeks \"; // Function call $len = get_num_of_words($str); // Printing the resultecho $len; ?>", "e": 2250, "s": 1840, "text": null }, { "code": null, "e": 2252, "s": 2250, "text": "3" }, { "code": null, "e": 2263, "s": 2252, "text": "PHP-string" }, { "code": null, "e": 2267, "s": 2263, "text": "PHP" }, { "code": null, "e": 2280, "s": 2267, "text": "PHP Programs" }, { "code": null, "e": 2297, "s": 2280, "text": "Web Technologies" }, { "code": null, "e": 2324, "s": 2297, "text": "Web technologies Questions" }, { "code": null, "e": 2328, "s": 2324, "text": "PHP" } ]
Aptitude - Ratios Online Quiz
Following quiz provides Multiple Choice Questions (MCQs) related to Ratios. You will have to read all the given answers and click over the correct answer. If you are not sure about the answer then you can check the answer using Show Answer button. You can use Next Quiz button to check new set of questions in the quiz. Q 1 - If three numbers are in the ratio 3:7:11 and double the sum is 84, then the ratio of squares of the numbers is A - 9:25:49 B - 9:49:121 C - 16:25:36 D - 16:25:49 Explanation Let the numbers are 3x:7x:11x It is given that 2(3x+7x+11x) = 84 => x=2 Ratio 6:14:22 or 3:7:11 Their squares 9:49:121 Q 2 - Two numbers are respectively 80% and 60% more than a third number. What is the ratio between two numbers? A - 7:8 B - 8:9 C - 9:8 D - 4:3 Explanation Let the third number be x => The first and second number becomes 1.8x and 1.6x Their ratio will be 1.8x/1.6x=1.8/1.6=9/8 = 9:8 Q 3 - If A=(1/3)B and B=(1/2)C, then A:B:C =? A - 1:3:6 B - 2:3:6 C - 3:2:6 D - 3:1:2 Explanation A/B = 1/3 and B/C =1/2 ∴ A :B = 1 :3 and B :C = 1:2 = 3:6 ∴ A :B :C = 1 :3:6 Q 4 - If 7:x ::17.5 :22.5 , then x=? A - 5.5 B - 7.5 C - 6 D - 9 Explanation X * 17.5 =7*22.5 => X= 7*22.5/17.5 = 7*225/175 =9. Q 5 - What no. must be added to every term of 3:5 to make the proportion 5:6 ? A - 6 B - 7 C - 12 D - 13 Explanation Let the number to be included be X , Then , (3+x)/(5+x) = 5/6 => 6 (3+x)= 5 (5+x) =>x=(25-18) = 7. Henceforth, the no. to be included is 7. Q 6 - If 32 understudies In a class are females and the proportion of females to guys understudy is 16:9 , then what % of the class is females ? A - 32% B - 36% C - 56.25% D - 64% Explanation Let the females be16x and males 9x . Then, 16 x = 32 => x=2 So, there are 32 females and 18 males in the class. Percentage of females = {32/50*100)% = 64 % Q 7 - What ought to be added to each of the four numbers 6, 14, 18, 38 to make them corresponding? A - 1 B - 2 C - 3 D - 4 Explanation Let the number to be added be x. Then, 6+X/14+x= 18+x/38+x => (6+x) (38+x)= (14+ x) (18 +x) => 228 +44x+x<sup>2</sup> = 252+32x+x<sup>2</sup> = 12x=24 => x=2 . ∴ the required number is 2. Q 8 - If a surpasses B by 40 % and B is not as much as C by 20 %, then A:C =? A - 3:1 B - 3:2 C - 26:25 D - 28:25 Explanation B= 80% of C= 80/100*C= 4c/5 and A= 140% of B=(140b/100) =7B/5 A= 7b/5= 7/5*4C/5 =28C/25 =>A/C =28/25 ∴ A: C = 28:25 Q 9 - The proportion of salary of An and B is 5:3 and that of their use is 9:5. On the off chance that they spare Rs. 2600 and Rs. 1800, then their livelihoods are: A - 9000, 5400 B - 10000, 6000 C - 6000, 3600 D - 8000, 4800 Explanation Let the income of A and B be Rs 5x and Rs 3x respectively and let their expenditure be Rs. 9y and 5y respectively. Then, 5x- 9y =2600 ...(i) and 3x-5y =1800 ...(ii) On multiplying (ii) by 9 and (i) by 5 and subtracting, we get 2x = 3200 => x = 1600. ∴ A income = (5*1600)= 8000, B income = (3*1600)= 4800 Q 10 - Two equivalent glasses are 1/3 and 1/4 loaded with milk. They are then topped off with the water and the substances are blended in a tumbler. The milk's proportion and water in the tumbler is: A - 7:5 B - 7:17 C - 3:7 D - 11:23 Explanation First glass contains milk =1/3, water=2/3. Second contains milk =1/4,water=3/4. New tumbler contains milk=(1/3+1/4)=7/12,water=(2/3+3/4)=17/12. Ratio of milk and water in it =7/12:7/12=7:17. 87 Lectures 22.5 hours Programming Line Print Add Notes Bookmark this page
[ { "code": null, "e": 4212, "s": 3892, "text": "Following quiz provides Multiple Choice Questions (MCQs) related to Ratios. You will have to read all the given answers and click over the correct answer. If you are not sure about the answer then you can check the answer using Show Answer button. You can use Next Quiz button to check new set of questions in the quiz." }, { "code": null, "e": 4329, "s": 4212, "text": "Q 1 - If three numbers are in the ratio 3:7:11 and double the sum is 84, then the ratio of squares of the numbers is" }, { "code": null, "e": 4341, "s": 4329, "text": "A - 9:25:49" }, { "code": null, "e": 4354, "s": 4341, "text": "B - 9:49:121" }, { "code": null, "e": 4367, "s": 4354, "text": "C - 16:25:36" }, { "code": null, "e": 4380, "s": 4367, "text": "D - 16:25:49" }, { "code": null, "e": 4392, "s": 4380, "text": "Explanation" }, { "code": null, "e": 4514, "s": 4392, "text": "Let the numbers are 3x:7x:11x\nIt is given that 2(3x+7x+11x) = 84\n => x=2\nRatio 6:14:22 or 3:7:11\n Their squares 9:49:121\n" }, { "code": null, "e": 4626, "s": 4514, "text": "Q 2 - Two numbers are respectively 80% and 60% more than a third number. What is the ratio between two numbers?" }, { "code": null, "e": 4634, "s": 4626, "text": "A - 7:8" }, { "code": null, "e": 4642, "s": 4634, "text": "B - 8:9" }, { "code": null, "e": 4650, "s": 4642, "text": "C - 9:8" }, { "code": null, "e": 4658, "s": 4650, "text": "D - 4:3" }, { "code": null, "e": 4670, "s": 4658, "text": "Explanation" }, { "code": null, "e": 4798, "s": 4670, "text": "Let the third number be x\n=> The first and second number becomes 1.8x and 1.6x\nTheir ratio will be 1.8x/1.6x=1.8/1.6=9/8 = 9:8\n" }, { "code": null, "e": 4845, "s": 4798, "text": "Q 3 - If A=(1/3)B and B=(1/2)C, then A:B:C =? " }, { "code": null, "e": 4855, "s": 4845, "text": "A - 1:3:6" }, { "code": null, "e": 4865, "s": 4855, "text": "B - 2:3:6" }, { "code": null, "e": 4875, "s": 4865, "text": "C - 3:2:6" }, { "code": null, "e": 4885, "s": 4875, "text": "D - 3:1:2" }, { "code": null, "e": 4897, "s": 4885, "text": "Explanation" }, { "code": null, "e": 4975, "s": 4897, "text": "A/B = 1/3 and B/C =1/2\n∴ A :B = 1 :3 and B :C = 1:2 = 3:6\n∴ A :B :C = 1 :3:6\n" }, { "code": null, "e": 5013, "s": 4975, "text": "Q 4 - If 7:x ::17.5 :22.5 , then x=? " }, { "code": null, "e": 5021, "s": 5013, "text": "A - 5.5" }, { "code": null, "e": 5029, "s": 5021, "text": "B - 7.5" }, { "code": null, "e": 5035, "s": 5029, "text": "C - 6" }, { "code": null, "e": 5041, "s": 5035, "text": "D - 9" }, { "code": null, "e": 5053, "s": 5041, "text": "Explanation" }, { "code": null, "e": 5108, "s": 5053, "text": "X * 17.5 =7*22.5 \n=> X= 7*22.5/17.5 \n= 7*225/175 =9.\n" }, { "code": null, "e": 5187, "s": 5108, "text": "Q 5 - What no. must be added to every term of 3:5 to make the proportion 5:6 ?" }, { "code": null, "e": 5193, "s": 5187, "text": "A - 6" }, { "code": null, "e": 5199, "s": 5193, "text": "B - 7" }, { "code": null, "e": 5206, "s": 5199, "text": "C - 12" }, { "code": null, "e": 5213, "s": 5206, "text": "D - 13" }, { "code": null, "e": 5225, "s": 5213, "text": "Explanation" }, { "code": null, "e": 5369, "s": 5225, "text": "Let the number to be included be X , Then ,\n(3+x)/(5+x) = 5/6 \n=> 6 (3+x)= 5 (5+x) \n=>x=(25-18) = 7. \nHenceforth, the no. to be included is 7.\n" }, { "code": null, "e": 5514, "s": 5369, "text": "Q 6 - If 32 understudies In a class are females and the proportion of females to guys understudy is 16:9 , then what % of the class is females ?" }, { "code": null, "e": 5522, "s": 5514, "text": "A - 32%" }, { "code": null, "e": 5530, "s": 5522, "text": "B - 36%" }, { "code": null, "e": 5541, "s": 5530, "text": "C - 56.25%" }, { "code": null, "e": 5549, "s": 5541, "text": "D - 64%" }, { "code": null, "e": 5561, "s": 5549, "text": "Explanation" }, { "code": null, "e": 5723, "s": 5561, "text": "Let the females be16x and males 9x .\nThen, 16 x = 32 \n=> x=2\n So, there are 32 females and 18 males in the class. \n Percentage of females = {32/50*100)% = 64 %\n" }, { "code": null, "e": 5822, "s": 5723, "text": "Q 7 - What ought to be added to each of the four numbers 6, 14, 18, 38 to make them corresponding?" }, { "code": null, "e": 5828, "s": 5822, "text": "A - 1" }, { "code": null, "e": 5834, "s": 5828, "text": "B - 2" }, { "code": null, "e": 5840, "s": 5834, "text": "C - 3" }, { "code": null, "e": 5846, "s": 5840, "text": "D - 4" }, { "code": null, "e": 5858, "s": 5846, "text": "Explanation" }, { "code": null, "e": 6052, "s": 5858, "text": "Let the number to be added be x. Then,\n6+X/14+x= 18+x/38+x\n=> (6+x) (38+x)= (14+ x) (18 +x)\n=> 228 +44x+x<sup>2</sup> = 252+32x+x<sup>2</sup>\n= 12x=24 \n=> x=2 .\n∴ the required number is 2.\n" }, { "code": null, "e": 6131, "s": 6052, "text": "Q 8 - If a surpasses B by 40 % and B is not as much as C by 20 %, then A:C =? " }, { "code": null, "e": 6139, "s": 6131, "text": "A - 3:1" }, { "code": null, "e": 6147, "s": 6139, "text": "B - 3:2" }, { "code": null, "e": 6157, "s": 6147, "text": "C - 26:25" }, { "code": null, "e": 6167, "s": 6157, "text": "D - 28:25" }, { "code": null, "e": 6179, "s": 6167, "text": "Explanation" }, { "code": null, "e": 6299, "s": 6179, "text": "B= 80% of C= 80/100*C= 4c/5 and \nA= 140% of B=(140b/100) =7B/5\n A= 7b/5= 7/5*4C/5 =28C/25\n=>A/C =28/25\n ∴ A: C = 28:25\n" }, { "code": null, "e": 6465, "s": 6299, "text": "Q 9 - The proportion of salary of An and B is 5:3 and that of their use is 9:5. On the off chance that they spare Rs. 2600 and Rs. 1800, then their livelihoods are: " }, { "code": null, "e": 6481, "s": 6465, "text": "A - 9000, 5400 " }, { "code": null, "e": 6498, "s": 6481, "text": "B - 10000, 6000 " }, { "code": null, "e": 6514, "s": 6498, "text": "C - 6000, 3600 " }, { "code": null, "e": 6530, "s": 6514, "text": "D - 8000, 4800 " }, { "code": null, "e": 6542, "s": 6530, "text": "Explanation" }, { "code": null, "e": 6857, "s": 6542, "text": "Let the income of A and B be Rs 5x and Rs 3x respectively and let their expenditure be Rs. 9y and 5y respectively. Then,\n5x- 9y =2600 ...(i) and 3x-5y =1800 ...(ii)\nOn multiplying (ii) by 9 and (i) by 5 and subtracting, we get\n 2x = 3200 \n=> x = 1600.\n ∴ A income = (5*1600)= 8000, B income = (3*1600)= 4800\n" }, { "code": null, "e": 7058, "s": 6857, "text": "Q 10 - Two equivalent glasses are 1/3 and 1/4 loaded with milk. They are then topped off with the water and the substances are blended in a tumbler. The milk's proportion and water in the tumbler is: " }, { "code": null, "e": 7067, "s": 7058, "text": "A - 7:5 " }, { "code": null, "e": 7077, "s": 7067, "text": "B - 7:17 " }, { "code": null, "e": 7086, "s": 7077, "text": "C - 3:7 " }, { "code": null, "e": 7096, "s": 7086, "text": "D - 11:23" }, { "code": null, "e": 7108, "s": 7096, "text": "Explanation" }, { "code": null, "e": 7300, "s": 7108, "text": "First glass contains milk =1/3, water=2/3.\nSecond contains milk =1/4,water=3/4.\nNew tumbler contains milk=(1/3+1/4)=7/12,water=(2/3+3/4)=17/12.\nRatio of milk and water in it =7/12:7/12=7:17.\n" }, { "code": null, "e": 7336, "s": 7300, "text": "\n 87 Lectures \n 22.5 hours \n" }, { "code": null, "e": 7354, "s": 7336, "text": " Programming Line" }, { "code": null, "e": 7361, "s": 7354, "text": " Print" }, { "code": null, "e": 7372, "s": 7361, "text": " Add Notes" } ]
How to use Boto3 to paginate through all crawlers present in AWS Glue
In this article, we will see how to paginate through all crawlers present in AWS Glue. Paginate through all crawlers from AWS Glue Data Catalog that is created in your account. Problem Statement: Use boto3 library in Python to paginate through all crawlers from AWS Glue Data Catalog that is created in your account Step 1: Import boto3 and botocore exceptions to handle exceptions. Step 1: Import boto3 and botocore exceptions to handle exceptions. Step 2: max_items, page_size and starting_token are the parameters for this function.max_items denote the total number of records to return. If the number of available records > max_items, then a NextToken will be provided in the response to resume pagination.page_size denotes the size of each page.Starting_token helps to paginate, and it uses NextToken from a previous response. Step 2: max_items, page_size and starting_token are the parameters for this function. max_items denote the total number of records to return. If the number of available records > max_items, then a NextToken will be provided in the response to resume pagination. max_items denote the total number of records to return. If the number of available records > max_items, then a NextToken will be provided in the response to resume pagination. page_size denotes the size of each page. page_size denotes the size of each page. Starting_token helps to paginate, and it uses NextToken from a previous response. Starting_token helps to paginate, and it uses NextToken from a previous response. Step 3: Create an AWS session using boto3 lib. Make sure region_name is mentioned in the default profile. If it is not mentioned, then explicitly pass the region_name while creating the session. Step 3: Create an AWS session using boto3 lib. Make sure region_name is mentioned in the default profile. If it is not mentioned, then explicitly pass the region_name while creating the session. Step 4: Create an AWS client for glue. Step 4: Create an AWS client for glue. Step 5: Create a paginator object that contains details of all crawlers using get_crawlers. Step 5: Create a paginator object that contains details of all crawlers using get_crawlers. Step 6: Call the paginate function and pass the max_items, page_size and starting_token as PaginationConfig parameter. Step 6: Call the paginate function and pass the max_items, page_size and starting_token as PaginationConfig parameter. Step 7: It returns the number of records based on max_size and page_size. Step 7: It returns the number of records based on max_size and page_size. Step 8: Handle the generic exception if something went wrong while paginating. Step 8: Handle the generic exception if something went wrong while paginating. Use the following code to paginate through all crawlers created in user account − import boto3 from botocore.exceptions import ClientError def paginate_through_crawlers(max_items=None:int,page_size=None:int, starting_token=None:string): session = boto3.session.Session() glue_client = session.client('glue') try: paginator = glue_client.get_paginator('get_crawlers') response = paginator.paginate(PaginationConfig={ 'MaxItems':max_items, 'PageSize':page_size, 'StartingToken':starting_token} ) return response except ClientError as e: raise Exception("boto3 client error in paginate_through_crawlers: " + e.__str__()) except Exception as e: raise Exception("Unexpected error in paginate_through_crawlers: " + e.__str__()) #1st Run a = paginate_through_crawlers(3,5) print(*a) #2nd Run for items in a: next_token = (items['NextToken']) b = paginate_through_crawlers(3,5,next_token) #1st Run {'Crawlers': [{'Name': 'DailyTest_v1.01', 'Role': 'ds-dev', 'Targets': {'S3Targets': [{'Path': 's3://**************/UIT_Raw/', 'Exclusions': []}], 'JdbcTargets': [], 'DynamoDBTargets': [], 'CatalogTargets': []}, 'DatabaseName': 'default', 'Classifiers': [], 'SchemaChangePolicy': {'UpdateBehavior': 'UPDATE_IN_DATABASE', 'DeleteBehavior': 'DEPRECATE_IN_DATABASE'}, 'State': 'READY', 'TablePrefix': 'test_uit_', 'CrawlElapsedTime': 0, 'CreationTime': datetime.datetime(2020, 11, 23, 17, 50, 20, tzinfo=tzlocal()), 'LastUpdated': datetime.datetime(2020, 12, 11, 18, 22, 34, tzinfo=tzlocal()), 'LastCrawl': {'Status': 'SUCCEEDED', 'LogGroup': '/aws-glue/crawlers', 'LogStream': '01_DailySalesAsOff_v1.01', 'MessagePrefix': '71fc0485-4755-42ca-a208-0654dd84d011', 'StartTime': datetime.datetime(2020, 12, 11, 18, 54, 46, tzinfo=tzlocal())}, 'Version': 10}, {'Name': 'Client_list', 'Role': 'ds-dev', 'Targets': {'S3Targets': [{'Path': 's3://************Client_list_01072021/', 'Exclusions': []}], 'JdbcTargets': [], 'DynamoDBTargets': [], 'CatalogTargets': []}, 'DatabaseName': 'ds_adhoc', 'Classifiers': [], 'SchemaChangePolicy': {'UpdateBehavior': 'UPDATE_IN_DATABASE', 'DeleteBehavior': 'DEPRECATE_IN_DATABASE'}, 'State': 'READY', 'CrawlElapsedTime': 0, 'CreationTime': datetime.datetime(2021, 1, 8, 3, 52, 27, tzinfo=tzlocal()), 'LastUpdated': datetime.datetime(2021, 1, 8, 3, 52, 27, tzinfo=tzlocal()), 'LastCrawl': {'Status': 'SUCCEEDED', 'LogGroup': '/aws-glue/crawlers', 'LogStream': 'Client_list_01072021', 'MessagePrefix': '41733a73-8946-4906-969c-f9581237b833', 'StartTime': datetime.datetime(2021, 1, 8, 3, 52, 45, tzinfo=tzlocal())}, 'Version': 1}, {'Name': 'Data Dimension', 'Role': 'qa-edl-glue-role', 'Targets': {'S3Targets': [{'Path': 's3://**************/data_dimension', 'Exclusions': []}], 'JdbcTargets': [], 'DynamoDBTargets': [], 'CatalogTargets': []}, 'DatabaseName': 'qa_edl_glue_database', 'Classifiers': [], 'SchemaChangePolicy': {'UpdateBehavior': 'UPDATE_IN_DATABASE', 'DeleteBehavior': 'DEPRECATE_IN_DATABASE'}, 'State': 'READY', 'CrawlElapsedTime': 0, 'CreationTime': datetime.datetime(2020, 8, 12, 0, 36, 21, tzinfo=tzlocal()), 'LastUpdated': datetime.datetime(2021, 3, 28, 13, 21, 19, tzinfo=tzlocal()), 'LastCrawl': {'Status': 'SUCCEEDED', 'LogGroup': '/aws-glue/crawlers', 'LogStream': 'Data Dimension', 'MessagePrefix': 'ee09c0ac-b778-467e-a941-c86c37edde47', 'StartTime': datetime.datetime(2021, 3, 28, 14, 1, 50, tzinfo=tzlocal())}, 'Version': 11}], 'NextToken': 'crawlr-wells', 'ResponseMetadata': {'RequestId': '8a6114ec-************d66', 'HTTPStatusCode': 200, 'HTTPHeaders': {'date': 'Fri, 02 Apr 2021 11:00:17 GMT', 'content-type': 'application/x-amz-json-1.1', 'content-length': '86627', 'connection': 'keep-alive', 'x-amzn-requestid': '8a6114ec-*****************66'}, 'RetryAttempts': 0}} #2nd Run {'Crawlers': [ {'Name': 'crwlr-cw-etf', 'Role': 'dev-ds-glue-role', 'Targets': {'S3Targets': [{'Path': 's3://***********CW_2020Q3', 'Exclusions': []}], 'JdbcTargets': [], 'DynamoDBTargets': [], 'CatalogTargets': []}, 'DatabaseName': 'ivz-dev-ds-data-packs', 'Description': 'Data pack crawlers', 'Classifiers': [], 'SchemaChangePolicy': {'UpdateBehavior': 'UPDATE_IN_DATABASE', 'DeleteBehavior': 'DEPRECATE_IN_DATABASE'}, 'State': 'READY', 'CrawlElapsedTime': 0, 'CreationTime': datetime.datetime(2020, 10, 28, 17, 30, 41, tzinfo=tzlocal()), 'LastUpdated': datetime.datetime(2020, 11, 17, 12, 47, 21, tzinfo=tzlocal()), 'LastCrawl': {'Status': 'SUCCEEDED', 'LogGroup': '/aws-glue/crawlers', 'LogStream': crwlr-cw-etf', 'MessagePrefix': '49cb001f-3005-43ef-96f7-a1d45917c808', 'StartTime': datetime.datetime(2020, 11, 17, 17, 41, 16, tzinfo=tzlocal())}, 'Version': 5, 'Configuration': '{"Version":1.0,"Grouping":{"TableGroupingPolicy":"CombineCompatibleSchemas"}}'}, {'Name': 'crwlr-data-packs', 'Role': 'dev-ds-glue-role', 'Targets': {'S3Targets': [{'Path': 's3://*****************raw-parquet', 'Exclusions': []}], 'JdbcTargets': [], 'DynamoDBTargets': [], 'CatalogTargets': []}, 'DatabaseName': 'ivz-dev-ds-data-packs', 'Classifiers': [], 'SchemaChangePolicy': {'UpdateBehavior': 'UPDATE_IN_DATABASE', 'DeleteBehavior': 'DEPRECATE_IN_DATABASE'}, 'State': 'READY', 'CrawlElapsedTime': 0, 'CreationTime': datetime.datetime(2020, 4, 21, 20, 49, 6, tzinfo=tzlocal()), 'LastUpdated': datetime.datetime(2020, 4, 21, 20, 49, 6, tzinfo=tzlocal()), 'LastCrawl': {'Status': 'SUCCEEDED', 'LogGroup': '/aws-glue/crawlers', 'LogStream': 'crwlr-data-packs-mstr', 'MessagePrefix': '26aedfe8-f631-41e3-acd5-35877d71be1b', 'StartTime': datetime.datetime(2020, 4, 21, 20, 49, 10, tzinfo=tzlocal())}, 'Version': 1, 'Configuration': '{"Version":1.0,"Grouping":{"TableGroupingPolicy":"CombineCompatibleSchemas"}}'}, {'Name': 'crwlr-data-packs', 'Role': 'dev-ds-glue-role', 'Targets': {'S3Targets': [{'Path': 's3://******ubs-raw-parquet', 'Exclusions': []}], 'JdbcTargets': [], 'DynamoDBTargets': [], 'CatalogTargets': []}, 'DatabaseName': 'ivz-dev-ds-data-packs', 'Classifiers': [], 'SchemaChangePolicy': {'UpdateBehavior': 'UPDATE_IN_DATABASE', 'DeleteBehavior': 'DEPRECATE_IN_DATABASE'}, 'State': 'READY', 'CrawlElapsedTime': 0, 'CreationTime': datetime.datetime(2020, 4, 14, 2, 31, 25, tzinfo=tzlocal()), 'LastUpdated': datetime.datetime(2020, 5, 28, 21, 52, 4, tzinfo=tzlocal()), 'LastCrawl': {'Status': 'SUCCEEDED', 'LogGroup': '/aws-glue/crawlers', 'LogStream': 'ivz-dev-ds-crwlr-data-packs-ubs', 'MessagePrefix': '6c00dc7b-181e-4eb2-8d6d-d195f97b03ce', 'StartTime': datetime.datetime(2020, 6, 4, 16, 13, 18, tzinfo=tzlocal())}, 'Version': 5, 'Configuration': '{"Version":1.0,"Grouping":{"TableGroupingPolicy":"CombineCompatibleSchemas"}}'}], 'NextToken': 'discovery_rep', 'ResponseMetadata': {'RequestId': '43e0b162-***********, 'HTTPStatusCode': 200, 'HTTPHeaders': {'date': 'Fri, 02 Apr 2021 11:00:18 GMT', 'content-type': 'application/x-amz-json-1.1', 'content-length': '89110', 'connection': 'keep-alive', 'x-amzn-requestid': '43e0b162-********}, 'RetryAttempts': 0}}
[ { "code": null, "e": 1149, "s": 1062, "text": "In this article, we will see how to paginate through all crawlers present in AWS Glue." }, { "code": null, "e": 1239, "s": 1149, "text": "Paginate through all crawlers from AWS Glue Data Catalog that is created in your account." }, { "code": null, "e": 1378, "s": 1239, "text": "Problem Statement: Use boto3 library in Python to paginate through all crawlers from AWS Glue Data Catalog that is created in your account" }, { "code": null, "e": 1445, "s": 1378, "text": "Step 1: Import boto3 and botocore exceptions to handle exceptions." }, { "code": null, "e": 1512, "s": 1445, "text": "Step 1: Import boto3 and botocore exceptions to handle exceptions." }, { "code": null, "e": 1894, "s": 1512, "text": "Step 2:\nmax_items, page_size and starting_token are the parameters for this function.max_items denote the total number of records to return. If the number of available records > max_items, then a NextToken will be provided in the response to resume pagination.page_size denotes the size of each page.Starting_token helps to paginate, and it uses NextToken from a previous response." }, { "code": null, "e": 1980, "s": 1894, "text": "Step 2:\nmax_items, page_size and starting_token are the parameters for this function." }, { "code": null, "e": 2156, "s": 1980, "text": "max_items denote the total number of records to return. If the number of available records > max_items, then a NextToken will be provided in the response to resume pagination." }, { "code": null, "e": 2332, "s": 2156, "text": "max_items denote the total number of records to return. If the number of available records > max_items, then a NextToken will be provided in the response to resume pagination." }, { "code": null, "e": 2373, "s": 2332, "text": "page_size denotes the size of each page." }, { "code": null, "e": 2414, "s": 2373, "text": "page_size denotes the size of each page." }, { "code": null, "e": 2496, "s": 2414, "text": "Starting_token helps to paginate, and it uses NextToken from a previous response." }, { "code": null, "e": 2578, "s": 2496, "text": "Starting_token helps to paginate, and it uses NextToken from a previous response." }, { "code": null, "e": 2773, "s": 2578, "text": "Step 3: Create an AWS session using boto3 lib. Make sure region_name is mentioned in the default profile. If it is not mentioned, then explicitly pass the region_name while creating the session." }, { "code": null, "e": 2968, "s": 2773, "text": "Step 3: Create an AWS session using boto3 lib. Make sure region_name is mentioned in the default profile. If it is not mentioned, then explicitly pass the region_name while creating the session." }, { "code": null, "e": 3007, "s": 2968, "text": "Step 4: Create an AWS client for glue." }, { "code": null, "e": 3046, "s": 3007, "text": "Step 4: Create an AWS client for glue." }, { "code": null, "e": 3138, "s": 3046, "text": "Step 5: Create a paginator object that contains details of all crawlers using get_crawlers." }, { "code": null, "e": 3230, "s": 3138, "text": "Step 5: Create a paginator object that contains details of all crawlers using get_crawlers." }, { "code": null, "e": 3349, "s": 3230, "text": "Step 6: Call the paginate function and pass the max_items, page_size and starting_token as PaginationConfig parameter." }, { "code": null, "e": 3468, "s": 3349, "text": "Step 6: Call the paginate function and pass the max_items, page_size and starting_token as PaginationConfig parameter." }, { "code": null, "e": 3542, "s": 3468, "text": "Step 7: It returns the number of records based on max_size and page_size." }, { "code": null, "e": 3616, "s": 3542, "text": "Step 7: It returns the number of records based on max_size and page_size." }, { "code": null, "e": 3695, "s": 3616, "text": "Step 8: Handle the generic exception if something went wrong while paginating." }, { "code": null, "e": 3774, "s": 3695, "text": "Step 8: Handle the generic exception if something went wrong while paginating." }, { "code": null, "e": 3856, "s": 3774, "text": "Use the following code to paginate through all crawlers created in user account −" }, { "code": null, "e": 4726, "s": 3856, "text": "import boto3\nfrom botocore.exceptions import ClientError\n\ndef paginate_through_crawlers(max_items=None:int,page_size=None:int, starting_token=None:string):\n session = boto3.session.Session()\n glue_client = session.client('glue')\n try:\n paginator = glue_client.get_paginator('get_crawlers')\n response = paginator.paginate(PaginationConfig={\n 'MaxItems':max_items,\n 'PageSize':page_size,\n 'StartingToken':starting_token}\n )\nreturn response\n except ClientError as e:\n raise Exception(\"boto3 client error in paginate_through_crawlers: \" + e.__str__())\n except Exception as e:\n raise Exception(\"Unexpected error in paginate_through_crawlers: \" + e.__str__())\n\n#1st Run\na = paginate_through_crawlers(3,5)\nprint(*a)\n#2nd Run\nfor items in a:\nnext_token = (items['NextToken'])\nb = paginate_through_crawlers(3,5,next_token)" }, { "code": null, "e": 10731, "s": 4726, "text": "#1st Run\n{'Crawlers':\n[{'Name': 'DailyTest_v1.01', 'Role': 'ds-dev', 'Targets': {'S3Targets': [{'Path': 's3://**************/UIT_Raw/', 'Exclusions': []}], 'JdbcTargets': [], 'DynamoDBTargets': [], 'CatalogTargets': []}, 'DatabaseName': 'default', 'Classifiers': [], 'SchemaChangePolicy': {'UpdateBehavior': 'UPDATE_IN_DATABASE', 'DeleteBehavior': 'DEPRECATE_IN_DATABASE'}, 'State': 'READY', 'TablePrefix': 'test_uit_', 'CrawlElapsedTime': 0, 'CreationTime': datetime.datetime(2020, 11, 23, 17, 50, 20, tzinfo=tzlocal()), 'LastUpdated': datetime.datetime(2020, 12, 11, 18, 22, 34, tzinfo=tzlocal()), 'LastCrawl': {'Status': 'SUCCEEDED', 'LogGroup': '/aws-glue/crawlers', 'LogStream': '01_DailySalesAsOff_v1.01', 'MessagePrefix': '71fc0485-4755-42ca-a208-0654dd84d011', 'StartTime': datetime.datetime(2020, 12, 11, 18, 54, 46, tzinfo=tzlocal())}, 'Version': 10},\n{'Name': 'Client_list', 'Role': 'ds-dev', 'Targets': {'S3Targets': [{'Path': 's3://************Client_list_01072021/', 'Exclusions': []}], 'JdbcTargets': [], 'DynamoDBTargets': [], 'CatalogTargets': []}, 'DatabaseName': 'ds_adhoc', 'Classifiers': [], 'SchemaChangePolicy': {'UpdateBehavior': 'UPDATE_IN_DATABASE', 'DeleteBehavior': 'DEPRECATE_IN_DATABASE'}, 'State': 'READY', 'CrawlElapsedTime': 0, 'CreationTime': datetime.datetime(2021, 1, 8, 3, 52, 27, tzinfo=tzlocal()), 'LastUpdated': datetime.datetime(2021, 1, 8, 3, 52, 27, tzinfo=tzlocal()), 'LastCrawl': {'Status': 'SUCCEEDED', 'LogGroup': '/aws-glue/crawlers', 'LogStream': 'Client_list_01072021', 'MessagePrefix': '41733a73-8946-4906-969c-f9581237b833', 'StartTime': datetime.datetime(2021, 1, 8, 3, 52, 45, tzinfo=tzlocal())}, 'Version': 1},\n{'Name': 'Data Dimension', 'Role': 'qa-edl-glue-role', 'Targets': {'S3Targets': [{'Path': 's3://**************/data_dimension', 'Exclusions': []}], 'JdbcTargets': [], 'DynamoDBTargets': [], 'CatalogTargets': []}, 'DatabaseName': 'qa_edl_glue_database', 'Classifiers': [], 'SchemaChangePolicy': {'UpdateBehavior': 'UPDATE_IN_DATABASE', 'DeleteBehavior': 'DEPRECATE_IN_DATABASE'}, 'State': 'READY', 'CrawlElapsedTime': 0, 'CreationTime': datetime.datetime(2020, 8, 12, 0, 36, 21, tzinfo=tzlocal()), 'LastUpdated': datetime.datetime(2021, 3, 28, 13, 21, 19, tzinfo=tzlocal()), 'LastCrawl': {'Status': 'SUCCEEDED', 'LogGroup': '/aws-glue/crawlers', 'LogStream': 'Data Dimension', 'MessagePrefix': 'ee09c0ac-b778-467e-a941-c86c37edde47', 'StartTime': datetime.datetime(2021, 3, 28, 14, 1, 50, tzinfo=tzlocal())}, 'Version': 11}],\n'NextToken': 'crawlr-wells',\n'ResponseMetadata': {'RequestId': '8a6114ec-************d66', 'HTTPStatusCode': 200, 'HTTPHeaders': {'date': 'Fri, 02 Apr 2021 11:00:17 GMT', 'content-type': 'application/x-amz-json-1.1', 'content-length': '86627', 'connection': 'keep-alive', 'x-amzn-requestid': '8a6114ec-*****************66'}, 'RetryAttempts': 0}}\n\n#2nd Run\n{'Crawlers': [\n{'Name': 'crwlr-cw-etf', 'Role': 'dev-ds-glue-role', 'Targets': {'S3Targets': [{'Path': 's3://***********CW_2020Q3', 'Exclusions': []}], 'JdbcTargets': [], 'DynamoDBTargets': [], 'CatalogTargets': []}, 'DatabaseName': 'ivz-dev-ds-data-packs', 'Description': 'Data pack crawlers', 'Classifiers': [], 'SchemaChangePolicy': {'UpdateBehavior': 'UPDATE_IN_DATABASE', 'DeleteBehavior': 'DEPRECATE_IN_DATABASE'}, 'State': 'READY', 'CrawlElapsedTime': 0, 'CreationTime': datetime.datetime(2020, 10, 28, 17, 30, 41, tzinfo=tzlocal()), 'LastUpdated': datetime.datetime(2020, 11, 17, 12, 47, 21, tzinfo=tzlocal()), 'LastCrawl': {'Status': 'SUCCEEDED', 'LogGroup': '/aws-glue/crawlers', 'LogStream': crwlr-cw-etf', 'MessagePrefix': '49cb001f-3005-43ef-96f7-a1d45917c808', 'StartTime': datetime.datetime(2020, 11, 17, 17, 41, 16, tzinfo=tzlocal())}, 'Version': 5, 'Configuration': '{\"Version\":1.0,\"Grouping\":{\"TableGroupingPolicy\":\"CombineCompatibleSchemas\"}}'},\n{'Name': 'crwlr-data-packs', 'Role': 'dev-ds-glue-role', 'Targets': {'S3Targets': [{'Path': 's3://*****************raw-parquet', 'Exclusions': []}], 'JdbcTargets': [], 'DynamoDBTargets': [], 'CatalogTargets': []}, 'DatabaseName': 'ivz-dev-ds-data-packs', 'Classifiers': [], 'SchemaChangePolicy': {'UpdateBehavior': 'UPDATE_IN_DATABASE', 'DeleteBehavior': 'DEPRECATE_IN_DATABASE'}, 'State': 'READY', 'CrawlElapsedTime': 0, 'CreationTime': datetime.datetime(2020, 4, 21, 20, 49, 6, tzinfo=tzlocal()), 'LastUpdated': datetime.datetime(2020, 4, 21, 20, 49, 6, tzinfo=tzlocal()), 'LastCrawl': {'Status': 'SUCCEEDED', 'LogGroup': '/aws-glue/crawlers', 'LogStream': 'crwlr-data-packs-mstr', 'MessagePrefix': '26aedfe8-f631-41e3-acd5-35877d71be1b', 'StartTime': datetime.datetime(2020, 4, 21, 20, 49, 10, tzinfo=tzlocal())}, 'Version': 1, 'Configuration': '{\"Version\":1.0,\"Grouping\":{\"TableGroupingPolicy\":\"CombineCompatibleSchemas\"}}'},\n{'Name': 'crwlr-data-packs', 'Role': 'dev-ds-glue-role', 'Targets': {'S3Targets': [{'Path': 's3://******ubs-raw-parquet', 'Exclusions': []}], 'JdbcTargets': [], 'DynamoDBTargets': [], 'CatalogTargets': []}, 'DatabaseName': 'ivz-dev-ds-data-packs', 'Classifiers': [], 'SchemaChangePolicy': {'UpdateBehavior': 'UPDATE_IN_DATABASE', 'DeleteBehavior': 'DEPRECATE_IN_DATABASE'}, 'State': 'READY', 'CrawlElapsedTime': 0, 'CreationTime': datetime.datetime(2020, 4, 14, 2, 31, 25, tzinfo=tzlocal()), 'LastUpdated': datetime.datetime(2020, 5, 28, 21, 52, 4, tzinfo=tzlocal()), 'LastCrawl': {'Status': 'SUCCEEDED', 'LogGroup': '/aws-glue/crawlers', 'LogStream': 'ivz-dev-ds-crwlr-data-packs-ubs', 'MessagePrefix': '6c00dc7b-181e-4eb2-8d6d-d195f97b03ce', 'StartTime': datetime.datetime(2020, 6, 4, 16, 13, 18, tzinfo=tzlocal())}, 'Version': 5, 'Configuration': '{\"Version\":1.0,\"Grouping\":{\"TableGroupingPolicy\":\"CombineCompatibleSchemas\"}}'}],\n'NextToken': 'discovery_rep',\n'ResponseMetadata': {'RequestId': '43e0b162-***********, 'HTTPStatusCode': 200, 'HTTPHeaders': {'date': 'Fri, 02 Apr 2021 11:00:18 GMT', 'content-type': 'application/x-amz-json-1.1', 'content-length': '89110', 'connection': 'keep-alive', 'x-amzn-requestid': '43e0b162-********}, 'RetryAttempts': 0}}" } ]
How to get the day of the week in JavaScript?
To get the day of the week, use the JavaScript getDay() method. JavaScript date getDay() method returns the day of the week for the specified date according to local time. The value returned by getDay() is an integer corresponding to the day of the week: 0 for Sunday, 1 for Monday, 2 for Tuesday, and so on. You can try to run the following code to get the day of the week in JavaScript − Live Demo <html> <head> <title>JavaScript getDay Method</title> </head> <body> <script> var dt = new Date("December 25, 1995 23:15:00"); document.write("Day of the week: " + dt.getDay() ); </script> </body> </html> Day of the week: 1
[ { "code": null, "e": 1371, "s": 1062, "text": "To get the day of the week, use the JavaScript getDay() method. JavaScript date getDay() method returns the day of the week for the specified date according to local time. The value returned by getDay() is an integer corresponding to the day of the week: 0 for Sunday, 1 for Monday, 2 for Tuesday, and so on." }, { "code": null, "e": 1452, "s": 1371, "text": "You can try to run the following code to get the day of the week in JavaScript −" }, { "code": null, "e": 1462, "s": 1452, "text": "Live Demo" }, { "code": null, "e": 1715, "s": 1462, "text": "<html>\n <head>\n <title>JavaScript getDay Method</title>\n </head>\n <body>\n <script>\n var dt = new Date(\"December 25, 1995 23:15:00\");\n document.write(\"Day of the week: \" + dt.getDay() );\n </script>\n </body>\n</html>" }, { "code": null, "e": 1734, "s": 1715, "text": "Day of the week: 1" } ]
How abstraction is achieved using interfaces in Java?
Abstraction is a process of hiding the implementation details from the user, only the functionality will be provided to the user. In other words, the user will have the information on what the object does instead of how it does it. Since all the methods of the interface are abstract and the user doesn’t know how a method is written except the method signature/prototype. Using interfaces, you can achieve (complete) abstraction. An interface in Java is a specification of method prototypes. Whenever you need to guide the programmer or, make a contract specifying how the methods and fields of a type should be you can define an interface. To create an object of this type you need to implement this interface, provide a body for all the abstract methods of the interface and obtain the object of the implementing class. The user who want to use the methods of the interface, he only knows the classes that implement this interface and their methods, information about the implementation is completely hidden from the user, thus achieving 100% abstraction. Live Demo interface Person{ void dsplay(); } class Student implements Person{ public void dsplay() { System.out.println("This is display method of the Student class"); } } class Lecturer implements Person{ public void dsplay() { System.out.println("This is display method of the Lecturer class"); } } public class AbstractionExample{ public static void main(String args[]) { Person person1 = new Student(); person1.dsplay(); Person person2 = new Lecturer(); person2.dsplay(); } } This is display method of the Student class This is display method of the Lecturer class
[ { "code": null, "e": 1294, "s": 1062, "text": "Abstraction is a process of hiding the implementation details from the user, only the functionality will be provided to the user. In other words, the user will have the information on what the object does instead of how it does it." }, { "code": null, "e": 1493, "s": 1294, "text": "Since all the methods of the interface are abstract and the user doesn’t know how a method is written except the method signature/prototype. Using interfaces, you can achieve (complete) abstraction." }, { "code": null, "e": 1704, "s": 1493, "text": "An interface in Java is a specification of method prototypes. Whenever you need to guide the programmer or, make a contract specifying how the methods and fields of a type should be you can define an interface." }, { "code": null, "e": 1885, "s": 1704, "text": "To create an object of this type you need to implement this interface, provide a body for all the abstract methods of the interface and obtain the object of the implementing class." }, { "code": null, "e": 2121, "s": 1885, "text": "The user who want to use the methods of the interface, he only knows the classes that implement this interface and their methods, information about the implementation is completely hidden from the user, thus achieving 100% abstraction." }, { "code": null, "e": 2132, "s": 2121, "text": " Live Demo" }, { "code": null, "e": 2659, "s": 2132, "text": "interface Person{\n void dsplay();\n}\nclass Student implements Person{\n public void dsplay() {\n System.out.println(\"This is display method of the Student class\");\n }\n}\nclass Lecturer implements Person{\n public void dsplay() {\n System.out.println(\"This is display method of the Lecturer class\");\n }\n}\npublic class AbstractionExample{\n public static void main(String args[]) {\n Person person1 = new Student();\n person1.dsplay();\n Person person2 = new Lecturer();\n person2.dsplay();\n }\n}" }, { "code": null, "e": 2748, "s": 2659, "text": "This is display method of the Student class\nThis is display method of the Lecturer class" } ]
C++ Algorithm Library - fill_n() Function
The C++ function std::algorithm::fill_n() assigns value to the first n elements of the sequence pointed by first. Following is the declaration for std::algorithm::fill_n() function form std::algorithm header. template <class OutputIterator, class Size, class T> OutputIterator fill_n (OutputIterator first, Size n, const T& val); first − Output iterators to the initial positions. first − Output iterators to the initial positions. n − Number of elements to fill. n − Number of elements to fill. val − Value to be used to fill the range. val − Value to be used to fill the range. Returns an iterator pointing to the element that follows the last element filled. Throws an exception if either element assignment or an operation on an iterator throws exception. Please note that invalid parameters cause undefined behavior. Linear. The following example shows the usage of std::algorithm::fill_n() function. #include <iostream> #include <vector> #include <algorithm> using namespace std; int main(void) { vector<int> v(5, 1); fill_n(v.begin() + 2, 3, 4); cout << "Vector contains following elements" << endl; for (auto it = v.begin(); it != v.end(); ++it) cout << *it << endl; return 0; } Let us compile and run the above program, this will produce the following result − Vector contains following elements 1 1 4 4 4 Print Add Notes Bookmark this page
[ { "code": null, "e": 2717, "s": 2603, "text": "The C++ function std::algorithm::fill_n() assigns value to the first n elements of the sequence pointed by first." }, { "code": null, "e": 2812, "s": 2717, "text": "Following is the declaration for std::algorithm::fill_n() function form std::algorithm header." }, { "code": null, "e": 2934, "s": 2812, "text": "template <class OutputIterator, class Size, class T>\nOutputIterator fill_n (OutputIterator first, Size n, const T& val);\n" }, { "code": null, "e": 2985, "s": 2934, "text": "first − Output iterators to the initial positions." }, { "code": null, "e": 3036, "s": 2985, "text": "first − Output iterators to the initial positions." }, { "code": null, "e": 3068, "s": 3036, "text": "n − Number of elements to fill." }, { "code": null, "e": 3100, "s": 3068, "text": "n − Number of elements to fill." }, { "code": null, "e": 3142, "s": 3100, "text": "val − Value to be used to fill the range." }, { "code": null, "e": 3184, "s": 3142, "text": "val − Value to be used to fill the range." }, { "code": null, "e": 3266, "s": 3184, "text": "Returns an iterator pointing to the element that follows the last element filled." }, { "code": null, "e": 3364, "s": 3266, "text": "Throws an exception if either element assignment or an operation on an iterator throws exception." }, { "code": null, "e": 3426, "s": 3364, "text": "Please note that invalid parameters cause undefined behavior." }, { "code": null, "e": 3434, "s": 3426, "text": "Linear." }, { "code": null, "e": 3510, "s": 3434, "text": "The following example shows the usage of std::algorithm::fill_n() function." }, { "code": null, "e": 3818, "s": 3510, "text": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nint main(void) {\n vector<int> v(5, 1);\n\n fill_n(v.begin() + 2, 3, 4);\n\n cout << \"Vector contains following elements\" << endl;\n\n for (auto it = v.begin(); it != v.end(); ++it)\n cout << *it << endl;\n\n return 0;\n}" }, { "code": null, "e": 3901, "s": 3818, "text": "Let us compile and run the above program, this will produce the following result −" }, { "code": null, "e": 3947, "s": 3901, "text": "Vector contains following elements\n1\n1\n4\n4\n4\n" }, { "code": null, "e": 3954, "s": 3947, "text": " Print" }, { "code": null, "e": 3965, "s": 3954, "text": " Add Notes" } ]
Python Data Structure - Quick Guide
Here, we will understand what is data structure with regards to Python programming language. Data structures are fundamental concepts of computer science which helps is writing efficient programs in any language. Python is a high-level, interpreted, interactive and object-oriented scripting language using which we can study the fundamentals of data structure in a simpler way as compared to other programming languages. In this chapter we are going to study a short overview of some frequently used data structures in general and how they are related to some specific python data types. There are also some data structures specific to python which is listed as another category. The various data structures in computer science are divided broadly into two categories shown below. We will discuss about each of the below data structures in detail in subsequent chapters. These are the data structures which store the data elements in a sequential manner. Array − It is a sequential arrangement of data elements paired with the index of the data element. Array − It is a sequential arrangement of data elements paired with the index of the data element. Linked List − Each data element contains a link to another element along with the data present in it. Linked List − Each data element contains a link to another element along with the data present in it. Stack − It is a data structure which follows only to specific order of operation. LIFO(last in First Out) or FILO(First in Last Out). Stack − It is a data structure which follows only to specific order of operation. LIFO(last in First Out) or FILO(First in Last Out). Queue − It is similar to Stack but the order of operation is only FIFO(First In First Out). Queue − It is similar to Stack but the order of operation is only FIFO(First In First Out). Matrix − It is two dimensional data structure in which the data element is referred by a pair of indices. Matrix − It is two dimensional data structure in which the data element is referred by a pair of indices. These are the data structures in which there is no sequential linking of data elements. Any pair or group of data elements can be linked to each other and can be accessed without a strict sequence. Binary Tree − It is a data structure where each data element can be connected to maximum two other data elements and it starts with a root node. Binary Tree − It is a data structure where each data element can be connected to maximum two other data elements and it starts with a root node. Heap − It is a special case of Tree data structure where the data in the parent node is either strictly greater than/ equal to the child nodes or strictly less than it’s child nodes. Heap − It is a special case of Tree data structure where the data in the parent node is either strictly greater than/ equal to the child nodes or strictly less than it’s child nodes. Hash Table − It is a data structure which is made of arrays associated with each other using a hash function. It retrieves values using keys rather than index from a data element. Hash Table − It is a data structure which is made of arrays associated with each other using a hash function. It retrieves values using keys rather than index from a data element. Graph − It is an arrangement of vertices and nodes where some of the nodes are connected to each other through links. Graph − It is an arrangement of vertices and nodes where some of the nodes are connected to each other through links. These data structures are specific to python language and they give greater flexibility in storing different types of data and faster processing in python environment. List − It is similar to array with the exception that the data elements can be of different data types. You can have both numeric and string data in a python list. List − It is similar to array with the exception that the data elements can be of different data types. You can have both numeric and string data in a python list. Tuple − Tuples are similar to lists but they are immutable which means the values in a tuple cannot be modified they can only be read. Tuple − Tuples are similar to lists but they are immutable which means the values in a tuple cannot be modified they can only be read. Dictionary − The dictionary contains Key-value pairs as its data elements. Dictionary − The dictionary contains Key-value pairs as its data elements. In the next chapters we are going to learn the details of how each of these data structures can be implemented using Python. Python is available on a wide variety of platforms including Linux and Mac OS X. Let's understand how to set up our Python environment. Open a terminal window and type "python" to find out if it is already installed and which version is installed. Unix (Solaris, Linux, FreeBSD, AIX, HP/UX, SunOS, IRIX, etc.) Win 9x/NT/2000 Macintosh (Intel, PPC, 68K) OS/2 DOS (multiple versions) PalmOS Nokia mobile phones Windows CE Acorn/RISC OS BeOS Amiga VMS/OpenVMS QNX VxWorks Psion Python has also been ported to the Java and .NET virtual machines The most up-to-date and current source code, binaries, documentation, news, etc., is available on the official website of Python www.python.org You can download Python documentation from this website given herewith,www.python.org/doc. The documentation is available in HTML, PDF, and PostScript formats. Python distribution is available for a wide variety of platforms. You need to download only the binary code applicable for your platform and install Python. If the binary code for your platform is not available, you need a C compiler to compile the source code manually. Compiling the source code offers more flexibility in terms of choice of features that you require in your installation. Here is a quick overview of installing Python on various platforms − Here are the simple steps to install Python on Unix/Linux machine. Open a Web browser and go to www.python.org/downloads. Open a Web browser and go to www.python.org/downloads. Follow the link to download zipped source code available for Unix/Linux. Follow the link to download zipped source code available for Unix/Linux. Download and extract files. Download and extract files. Editing the Modules/Setup file if you want to customize some options. Editing the Modules/Setup file if you want to customize some options. run ./configure script run ./configure script make make make install make install This installs Python at standard location /usr/local/bin and its libraries at /usr/local/lib/pythonXX where XX is the version of Python. Here are the steps to install Python on Windows machine. Open a Web browser and go to www.python.org/downloads. Open a Web browser and go to www.python.org/downloads. Follow the link for the Windows installer python-XYZ.msi file where XYZ is the version you need to install. Follow the link for the Windows installer python-XYZ.msi file where XYZ is the version you need to install. To use this installer python-XYZ.msi, the Windows system must support Microsoft Installer 2.0. Save the installer file to your local machine and then run it to find out if your machine supports MSI. To use this installer python-XYZ.msi, the Windows system must support Microsoft Installer 2.0. Save the installer file to your local machine and then run it to find out if your machine supports MSI. Run the downloaded file. This brings up the Python install wizard, which is really easy to use. Just accept the default settings, wait until the install is finished, and you are done. Run the downloaded file. This brings up the Python install wizard, which is really easy to use. Just accept the default settings, wait until the install is finished, and you are done. Recent Macs come with Python installed, but it may be several years out of date. See www.python.org/download/mac/ for instructions on getting the current version along with extra tools to support development on the Mac. For older Mac OS's before Mac OS X 10.3 (released in 2003), MacPython is available. Jack Jansen maintains it and you can have full access to the entire documentation at his website − http://www.cwi.nl/~jack/macpython.html. You can find complete installation details for Mac OS installation. Programs and other executable files can be in many directories, so operating systems provide a search path that lists the directories that the OS searches for executables. The path is stored in an environment variable, which is a named string maintained by the operating system. This variable contains information available to the command shell and other programs. The path variable is named as PATH in Unix or Path in Windows (Unix is case sensitive; Windows is not). In Mac OS, the installer handles the path details. To invoke the Python interpreter from any particular directory, you must add the Python directory to your path. To add the Python directory to the path for a particular session in Unix − In the csh shell − type setenv PATH "$PATH:/usr/local/bin/python" and press Enter. In the csh shell − type setenv PATH "$PATH:/usr/local/bin/python" and press Enter. In the bash shell (Linux) − type export ATH="$PATH:/usr/local/bin/python" and press Enter. In the bash shell (Linux) − type export ATH="$PATH:/usr/local/bin/python" and press Enter. In the sh or ksh shell − type PATH="$PATH:/usr/local/bin/python" and press Enter. In the sh or ksh shell − type PATH="$PATH:/usr/local/bin/python" and press Enter. Note − /usr/local/bin/python is the path of the Python directory Note − /usr/local/bin/python is the path of the Python directory To add the Python directory to the path for a particular session in Windows − At the command prompt − type path %path%;C:\Python and press Enter. At the command prompt − type path %path%;C:\Python and press Enter. Note − C:\Python is the path of the Python directory Note − C:\Python is the path of the Python directory Here are important environment variables, which can be recognized by Python − PYTHONPATH It has a role similar to PATH. This variable tells the Python interpreter where to locate the module files imported into a program. It should include the Python source library directory and the directories containing Python source code. PYTHONPATH is sometimes preset by the Python installer. PYTHONSTARTUP It contains the path of an initialization file containing Python source code. It is executed every time you start the interpreter. It is named as .pythonrc.py in Unix and it contains commands that load utilities or modify PYTHONPATH. PYTHONCASEOK It is used in Windows to instruct Python to find the first case-insensitive match in an import statement. Set this variable to any value to activate it. PYTHONHOME It is an alternative module search path. It is usually embedded in the PYTHONSTARTUP or PYTHONPATH directories to make switching module libraries easy. There are three different ways to start Python, which are as follows − You can start Python from Unix, DOS, or any other system that provides you a command-line interpreter or shell window. You can start Python from Unix, DOS, or any other system that provides you a command-line interpreter or shell window. Enter python the command line. Enter python the command line. Start coding right away in the interactive interpreter. Start coding right away in the interactive interpreter. $python # Unix/Linux or python% # Unix/Linux or C:> python # Windows/DOS Here is the list of all the available command line options, which is as mentioned below − -d It provides debug output. -O It generates optimized bytecode (resulting in .pyo files). -S Do not run import site to look for Python paths on startup. -v verbose output (detailed trace on import statements). -X disable class-based built-in exceptions (just use strings); obsolete starting with version 1.6. -c cmd run Python script sent in as cmd string file run Python script from given file A Python script can be executed at command line by invoking the interpreter on your application, as in the following − $python script.py # Unix/Linux or python% script.py # Unix/Linux or C: >python script.py # Windows/DOS Note − Be sure the file permission mode allows execution. Note − Be sure the file permission mode allows execution. You can run Python from a Graphical User Interface (GUI) environment as well, if you have a GUI application on your system that supports Python. Unix − IDLE is the very first Unix IDE for Python. Unix − IDLE is the very first Unix IDE for Python. Windows − PythonWin is the first Windows interface for Python and is an IDE with a GUI. Windows − PythonWin is the first Windows interface for Python and is an IDE with a GUI. Macintosh − The Macintosh version of Python along with the IDLE IDE is available from the main website, downloadable as either MacBinary or BinHex'd files. Macintosh − The Macintosh version of Python along with the IDLE IDE is available from the main website, downloadable as either MacBinary or BinHex'd files. If you are not able to set up the environment properly, then you can take help from your system admin. Make sure the Python environment is properly set up and working perfectly fine. Note − All the examples given in subsequent chapters are executed with Python 2.4.3 version available on CentOS flavor of Linux. Note − All the examples given in subsequent chapters are executed with Python 2.4.3 version available on CentOS flavor of Linux. We already have set up Python Programming environment online, so that you can execute all the available examples online at the same time when you are learning theory. Feel free to modify any example and execute it online. Array is a container which can hold a fix number of items and these items should be of the same type. Most of the data structures make use of arrays to implement their algorithms. Following are the important terms to understand the concept of Array are as follows − Element − Each item stored in an array is called an element. Element − Each item stored in an array is called an element. Index − Each location of an element in an array has a numerical index, which is used to identify the element. Index − Each location of an element in an array has a numerical index, which is used to identify the element. Arrays can be declared in various ways in different languages. Below is an illustration. As per the above illustration, following are the important points to be considered − Index starts with 0. Index starts with 0. Array length is 10, which means it can store 10 elements. Array length is 10, which means it can store 10 elements. Each element can be accessed via its index. For example, we can fetch an element at index 6 as 9. Each element can be accessed via its index. For example, we can fetch an element at index 6 as 9. The basic operations supported by an array are as stated below − Traverse − print all the array elements one by one. Traverse − print all the array elements one by one. Insertion − Adds an element at the given index. Insertion − Adds an element at the given index. Deletion − Deletes an element at the given index. Deletion − Deletes an element at the given index. Search − Searches an element using the given index or by the value. Search − Searches an element using the given index or by the value. Update − Updates an element at the given index. Update − Updates an element at the given index. Array is created in Python by importing array module to the python program. Then, the array is declared as shown below − from array import * arrayName = array(typecode, [Initializers]) Typecode are the codes that are used to define the type of value the array will hold. Some common typecodes used are as follows − Before looking at various array operations lets create and print an array using python. The below code creates an array named array1. from array import * array1 = array('i', [10,20,30,40,50]) for x in array1: print(x) When we compile and execute the above program, it produces the following result − 10 20 30 40 50 We can access each element of an array using the index of the element. The below code shows how to access an array element. from array import * array1 = array('i', [10,20,30,40,50]) print (array1[0]) print (array1[2]) When we compile and execute the above program, it produces the following result, which shows the element is inserted at index position 1. 10 30 Insert operation is to insert one or more data elements into an array. Based on the requirement, a new element can be added at the beginning, end, or any given index of array. Here, we add a data element at the middle of the array using the python in-built insert() method. from array import * array1 = array('i', [10,20,30,40,50]) array1.insert(1,60) for x in array1: print(x) When we compile and execute the above program, it produces the following result which shows the element is inserted at index position 1. 10 60 20 30 40 50 Deletion refers to removing an existing element from the array and re-organizing all elements of an array. Here, we remove a data element at the middle of the array using the python in-built remove() method. from array import * array1 = array('i', [10,20,30,40,50]) array1.remove(40) for x in array1: print(x) When we compile and execute the above program, it produces the following result which shows the element is removed form the array. 10 20 30 50 You can perform a search for an array element based on its value or its index. Here, we search a data element using the python in-built index() method. from array import * array1 = array('i', [10,20,30,40,50]) print (array1.index(40)) When we compile and execute the above program, it produces the following result which shows the index of the element. If the value is not present in the array then th eprogram returns an error. 3 Update operation refers to updating an existing element from the array at a given index. Here, we simply reassign a new value to the desired index we want to update. from array import * array1 = array('i', [10,20,30,40,50]) array1[2] = 80 for x in array1: print(x) When we compile and execute the above program, it produces the following result which shows the new value at the index position 2. 10 20 80 40 50 The list is a most versatile datatype available in Python which can be written as a list of comma-separated values (items) between square brackets. Important thing about a list is that items in a list need not be of the same type. Creating a list is as simple as putting different comma-separated values between square brackets. list1 = ['physics', 'chemistry', 1997, 2000] list2 = [1, 2, 3, 4, 5 ] list3 = ["a", "b", "c", "d"] Similar to string indices, list indices start at 0, and lists can be sliced, concatenated and so on. To access values in lists, use the square brackets for slicing along with the index or indices to obtain value available at that index. #!/usr/bin/python list1 = ['physics', 'chemistry', 1997, 2000] list2 = [1, 2, 3, 4, 5, 6, 7 ] print "list1[0]: ", list1[0] print "list2[1:5]: ", list2[1:5] When the above code is executed, it produces the following result − list1[0]: physics list2[1:5]: [2, 3, 4, 5] You can update single or multiple elements of lists by giving the slice on the left-hand side of the assignment operator, and you can add to elements in a list with the append() method. #!/usr/bin/python list = ['physics', 'chemistry', 1997, 2000] print "Value available at index 2 : " print list[2] list[2] = 2001 print "New value available at index 2 : " print list[2] Note − append() method is discussed in subsequent section. Note − append() method is discussed in subsequent section. When the above code is executed, it produces the following result − Value available at index 2 : 1997 New value available at index 2 : 2001 To remove a list element, you can use either the del statement if you know exactly which element(s) you are deleting or the remove() method if you do not know. #!/usr/bin/python list1 = ['physics', 'chemistry', 1997, 2000] print list1 del list1[2] print "After deleting value at index 2 : " print list1 When the above code is executed, it produces following result − ['physics', 'chemistry', 1997, 2000] After deleting value at index 2 : ['physics', 'chemistry', 2000] Note − remove() method is discussed in subsequent section. Note − remove() method is discussed in subsequent section. Lists respond to the + and * operators much like strings; they mean concatenation and repetition here too, except that the result is a new list, not a string. In fact, lists respond to all of the general sequence operations we used on strings in the prior chapter. A tuple is a sequence of immutable Python objects. Tuples are sequences, just like lists. The differences between tuples and lists are, the tuples cannot be changed unlike lists and tuples use parentheses, whereas lists use square brackets. Creating a tuple is as simple as putting different comma-separated values. Optionally you can put these comma-separated values between parentheses also. tup1 = ('physics', 'chemistry', 1997, 2000); tup2 = (1, 2, 3, 4, 5 ); tup3 = "a", "b", "c", "d"; The empty tuple is written as two parentheses containing nothing − tup1 = (); To write a tuple containing a single value you have to include a comma, even though there is only one value − tup1 = (50,); Like string indices, tuple indices start at 0, and they can be sliced, concatenated, and so on. To access values in tuple, use the square brackets for slicing along with the index or indices to obtain value available at that index. #!/usr/bin/python tup1 = ('physics', 'chemistry', 1997, 2000); tup2 = (1, 2, 3, 4, 5, 6, 7 ); print "tup1[0]: ", tup1[0]; print "tup2[1:5]: ", tup2[1:5]; When the above code is executed, it produces the following result − tup1[0]: physics tup2[1:5]: [2, 3, 4, 5] Tuples are immutable which means you cannot update or change the values of tuple elements. You are able to take portions of existing tuples to create new tuples as the following example demonstrates − #!/usr/bin/python tup1 = (12, 34.56); tup2 = ('abc', 'xyz'); # Following action is not valid for tuples # tup1[0] = 100; # So let's create a new tuple as follows tup3 = tup1 + tup2; print tup3; When the above code is executed, it produces the following result − (12, 34.56, 'abc', 'xyz') Removing individual tuple elements is not possible. There is, of course, nothing wrong with putting together another tuple with the undesired elements discarded. To explicitly remove an entire tuple, just use the del statement. #!/usr/bin/python tup = ('physics', 'chemistry', 1997, 2000); print tup; del tup; print "After deleting tup : "; print tup; Note − an exception raised, this is because after del tup tuple does not exist anymore. Note − an exception raised, this is because after del tup tuple does not exist anymore. This produces the following result − ('physics', 'chemistry', 1997, 2000) After deleting tup : Traceback (most recent call last): File "test.py", line 9, in <module> print tup; NameError: name 'tup' is not defined Tuples respond to the + and * operators much like strings; they mean concatenation and repetition here too, except that the result is a new tuple, not a string. In fact, tuples respond to all of the general sequence operations we used on strings in the prior chapter. In Dictionary each key is separated from its value by a colon (:), the items are separated by commas, and the whole thing is enclosed in curly braces. An empty dictionary without any items is written with just two curly braces, like this − {}. Keys are unique within a dictionary while values may not be. The values of a dictionary can be of any type, but the keys must be of an immutable data type such as strings, numbers, or tuples. To access dictionary elements, you can use the familiar square brackets along with the key to obtain its value. A simple example is as follows − #!/usr/bin/python dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'} print "dict['Name']: ", dict['Name'] print "dict['Age']: ", dict['Age'] When the above code is executed, it produces the following result − dict['Name']: Zara dict['Age']: 7 If we attempt to access a data item with a key, which is not part of the dictionary, we get an error as follows − #!/usr/bin/python dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'} print "dict['Alice']: ", dict['Alice'] When the above code is executed, it produces the following result − dict['Alice']: Traceback (most recent call last): File "test.py", line 4, in <module> print "dict['Alice']: ", dict['Alice']; KeyError: 'Alice' You can update a dictionary by adding a new entry or a key-value pair, modifying an existing entry, or deleting an existing entry as shown below in the simple example − #!/usr/bin/python dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'} dict['Age'] = 8; # update existing entry dict['School'] = "DPS School"; # Add new entry print "dict['Age']: ", dict['Age'] print "dict['School']: ", dict['School'] When the above code is executed, it produces the following result − dict['Age']: 8 dict['School']: DPS School You can either remove individual dictionary elements or clear the entire contents of a dictionary. You can also delete entire dictionary in a single operation. To explicitly remove an entire dictionary, just use the del statement. A simple example is as mentioned below − #!/usr/bin/python dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'} del dict['Name']; # remove entry with key 'Name' dict.clear(); # remove all entries in dict del dict ; # delete entire dictionary print "dict['Age']: ", dict['Age'] print "dict['School']: ", dict['School'] Note −that an exception is raised because after del dict dictionary does not exist any more − Note −that an exception is raised because after del dict dictionary does not exist any more − This produces the following result − dict['Age']: Traceback (most recent call last): File "test.py", line 8, in <module> print "dict['Age']: ", dict['Age']; TypeError: 'type' object is unsubscriptable Note − del() method is discussed in subsequent section. Note − del() method is discussed in subsequent section. Dictionary values have no restrictions. They can be any arbitrary Python object, either standard objects or user-defined objects. However, same is not true for the keys. There are two important points to remember about dictionary keys − More than one entry per key not allowed. Which means no duplicate key is allowed. When duplicate keys encountered during assignment, the last assignment wins. More than one entry per key not allowed. Which means no duplicate key is allowed. When duplicate keys encountered during assignment, the last assignment wins. #!/usr/bin/python dict = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'} print "dict['Name']: ", dict['Name'] When the above code is executed, it produces the following result − dict['Name']: Manni Keys must be immutable. Which means you can use strings, numbers or tuples as dictionary keys but something like ['key'] is not allowed. An example is as follows − #!/usr/bin/python dict = {['Name']: 'Zara', 'Age': 7} print "dict['Name']: ", dict['Name'] When the above code is executed, it produces the following result − Traceback (most recent call last): File "test.py", line 3, in <module> dict = {['Name']: 'Zara', 'Age': 7}; TypeError: list objects are unhashable Two dimensional array is an array within an array. It is an array of arrays. In this type of array the position of an data element is referred by two indices instead of one. So it represents a table with rows an dcolumns of data. In the below example of a two dimensional array, observer that each array element itself is also an array. Consider the example of recording temperatures 4 times a day, every day. Some times the recording instrument may be faulty and we fail to record data. Such data for 4 days can be presented as a two dimensional array as below. Day 1 - 11 12 5 2 Day 2 - 15 6 10 Day 3 - 10 8 12 5 Day 4 - 12 15 8 6 The above data can be represented as a two dimensional array as below. T = [[11, 12, 5, 2], [15, 6,10], [10, 8, 12, 5], [12,15,8,6]] The data elements in two dimesnional arrays can be accessed using two indices. One index referring to the main or parent array and another index referring to the position of the data element in the inner array.If we mention only one index then the entire inner array is printed for that index position. The example below illustrates how it works. from array import * T = [[11, 12, 5, 2], [15, 6,10], [10, 8, 12, 5], [12,15,8,6]] print(T[0]) print(T[1][2]) When the above code is executed, it produces the following result − [11, 12, 5, 2] 10 To print out the entire two dimensional array we can use python for loop as shown below. We use end of line to print out the values in different rows. from array import * T = [[11, 12, 5, 2], [15, 6,10], [10, 8, 12, 5], [12,15,8,6]] for r in T: for c in r: print(c,end = " ") print() When the above code is executed, it produces the following result − 11 12 5 2 15 6 10 10 8 12 5 12 15 8 6 We can insert new data elements at specific position by using the insert() method and specifying the index. In the below example a new data element is inserted at index position 2. from array import * T = [[11, 12, 5, 2], [15, 6,10], [10, 8, 12, 5], [12,15,8,6]] T.insert(2, [0,5,11,13,6]) for r in T: for c in r: print(c,end = " ") print() When the above code is executed, it produces the following result − 11 12 5 2 15 6 10 0 5 11 13 6 10 8 12 5 12 15 8 6 We can update the entire inner array or some specific data elements of the inner array by reassigning the values using the array index. from array import * T = [[11, 12, 5, 2], [15, 6,10], [10, 8, 12, 5], [12,15,8,6]] T[2] = [11,9] T[0][3] = 7 for r in T: for c in r: print(c,end = " ") print() When the above code is executed, it produces the following result − 11 12 5 7 15 6 10 11 9 12 15 8 6 We can delete the entire inner array or some specific data elements of the inner array by reassigning the values using the del() method with index. But in case you need to remove specific data elements in one of the inner arrays, then use the update process described above. from array import * T = [[11, 12, 5, 2], [15, 6,10], [10, 8, 12, 5], [12,15,8,6]] del T[3] for r in T: for c in r: print(c,end = " ") print() When the above code is executed, it produces the following result − 11 12 5 2 15 6 10 10 8 12 5 Matrix is a special case of two dimensional array where each data element is of strictly same size. So every matrix is also a two dimensional array but not vice versa. Matrices are very important data structures for many mathematical and scientific calculations. As we have already discussed two dimnsional array data structure in the previous chapter we will be focusing on data structure operations specific to matrices in this chapter. We also be using the numpy package for matrix data manipulation. Consider the case of recording temprature for 1 week measured in the morning, mid-day, evening and mid-night. It can be presented as a 7X5 matrix using an array and the reshape method available in numpy. from numpy import * a = array([['Mon',18,20,22,17],['Tue',11,18,21,18], ['Wed',15,21,20,19],['Thu',11,20,22,21], ['Fri',18,17,23,22],['Sat',12,22,20,18], ['Sun',13,15,19,16]]) m = reshape(a,(7,5)) print(m) The above data can be represented as a two dimensional array as below − [ ['Mon' '18' '20' '22' '17'] ['Tue' '11' '18' '21' '18'] ['Wed' '15' '21' '20' '19'] ['Thu' '11' '20' '22' '21'] ['Fri' '18' '17' '23' '22'] ['Sat' '12' '22' '20' '18'] ['Sun' '13' '15' '19' '16'] ] The data elements in a matrix can be accessed by using the indexes. The access method is same as the way data is accessed in Two dimensional array. from numpy import * m = array([['Mon',18,20,22,17],['Tue',11,18,21,18], ['Wed',15,21,20,19],['Thu',11,20,22,21], ['Fri',18,17,23,22],['Sat',12,22,20,18], ['Sun',13,15,19,16]]) # Print data for Wednesday print(m[2]) # Print data for friday evening print(m[4][3]) When the above code is executed, it produces the following result − ['Wed', 15, 21, 20, 19] 23 Use the below mentioned code to add a row in a matrix. from numpy import * m = array([['Mon',18,20,22,17],['Tue',11,18,21,18], ['Wed',15,21,20,19],['Thu',11,20,22,21], ['Fri',18,17,23,22],['Sat',12,22,20,18], ['Sun',13,15,19,16]]) m_r = append(m,[['Avg',12,15,13,11]],0) print(m_r) When the above code is executed, it produces the following result − [ ['Mon' '18' '20' '22' '17'] ['Tue' '11' '18' '21' '18'] ['Wed' '15' '21' '20' '19'] ['Thu' '11' '20' '22' '21'] ['Fri' '18' '17' '23' '22'] ['Sat' '12' '22' '20' '18'] ['Sun' '13' '15' '19' '16'] ['Avg' '12' '15' '13' '11'] ] We can add column to a matrix using the insert() method. here we have to mention the index where we want to add the column and a array containing the new values of the columns added.In the below example we add t a new column at the fifth position from the beginning. from numpy import * m = array([['Mon',18,20,22,17],['Tue',11,18,21,18], ['Wed',15,21,20,19],['Thu',11,20,22,21], ['Fri',18,17,23,22],['Sat',12,22,20,18], ['Sun',13,15,19,16]]) m_c = insert(m,[5],[[1],[2],[3],[4],[5],[6],[7]],1) print(m_c) When the above code is executed, it produces the following result − [ ['Mon' '18' '20' '22' '17' '1'] ['Tue' '11' '18' '21' '18' '2'] ['Wed' '15' '21' '20' '19' '3'] ['Thu' '11' '20' '22' '21' '4'] ['Fri' '18' '17' '23' '22' '5'] ['Sat' '12' '22' '20' '18' '6'] ['Sun' '13' '15' '19' '16' '7'] ] We can delete a row from a matrix using the delete() method. We have to specify the index of the row and also the axis value which is 0 for a row and 1 for a column. from numpy import * m = array([['Mon',18,20,22,17],['Tue',11,18,21,18], ['Wed',15,21,20,19],['Thu',11,20,22,21], ['Fri',18,17,23,22],['Sat',12,22,20,18], ['Sun',13,15,19,16]]) m = delete(m,[2],0) print(m) When the above code is executed, it produces the following result − [ ['Mon' '18' '20' '22' '17'] ['Tue' '11' '18' '21' '18'] ['Thu' '11' '20' '22' '21'] ['Fri' '18' '17' '23' '22'] ['Sat' '12' '22' '20' '18'] ['Sun' '13' '15' '19' '16'] ] We can delete a column from a matrix using the delete() method. We have to specify the index of the column and also the axis value which is 0 for a row and 1 for a column. from numpy import * m = array([['Mon',18,20,22,17],['Tue',11,18,21,18], ['Wed',15,21,20,19],['Thu',11,20,22,21], ['Fri',18,17,23,22],['Sat',12,22,20,18], ['Sun',13,15,19,16]]) m = delete(m,s_[2],1) print(m) When the above code is executed, it produces the following result − [ ['Mon' '18' '22' '17'] ['Tue' '11' '21' '18'] ['Wed' '15' '20' '19'] ['Thu' '11' '22' '21'] ['Fri' '18' '23' '22'] ['Sat' '12' '20' '18'] ['Sun' '13' '19' '16'] ] To update the values in the row of a matrix we simply re-assign the values at the index of the row. In the below example all the values for thrusday's data is marked as zero. The index for this row is 3. from numpy import * m = array([['Mon',18,20,22,17],['Tue',11,18,21,18], ['Wed',15,21,20,19],['Thu',11,20,22,21], ['Fri',18,17,23,22],['Sat',12,22,20,18], ['Sun',13,15,19,16]]) m[3] = ['Thu',0,0,0,0] print(m) When the above code is executed, it produces the following result − [ ['Mon' '18' '20' '22' '17'] ['Tue' '11' '18' '21' '18'] ['Wed' '15' '21' '20' '19'] ['Thu' '0' '0' '0' '0'] ['Fri' '18' '17' '23' '22'] ['Sat' '12' '22' '20' '18'] ['Sun' '13' '15' '19' '16'] ] Mathematically a set is a collection of items not in any particular order. A Python set is similar to this mathematical definition with below additional conditions. The elements in the set cannot be duplicates. The elements in the set cannot be duplicates. The elements in the set are immutable(cannot be modified) but the set as a whole is mutable. The elements in the set are immutable(cannot be modified) but the set as a whole is mutable. There is no index attached to any element in a python set. So they do not support any indexing or slicing operation. There is no index attached to any element in a python set. So they do not support any indexing or slicing operation. The sets in python are typically used for mathematical operations like union, intersection, difference and complement etc. We can create a set, access it’s elements and carry out these mathematical operations as shown below. A set is created by using the set() function or placing all the elements within a pair of curly braces. Days=set(["Mon","Tue","Wed","Thu","Fri","Sat","Sun"]) Months={"Jan","Feb","Mar"} Dates={21,22,17} print(Days) print(Months) print(Dates) When the above code is executed, it produces the following result. Please note how the order of the elements has changed in the result. set(['Wed', 'Sun', 'Fri', 'Tue', 'Mon', 'Thu', 'Sat']) set(['Jan', 'Mar', 'Feb']) set([17, 21, 22]) We cannot access individual values in a set. We can only access all the elements together as shown above. But we can also get a list of individual elements by looping through the set. Days=set(["Mon","Tue","Wed","Thu","Fri","Sat","Sun"]) for d in Days: print(d) When the above code is executed, it produces the following result − Wed Sun Fri Tue Mon Thu Sat We can add elements to a set by using add() method. Again as discussed there is no specific index attached to the newly added element. Days=set(["Mon","Tue","Wed","Thu","Fri","Sat"]) Days.add("Sun") print(Days) When the above code is executed, it produces the following result − set(['Wed', 'Sun', 'Fri', 'Tue', 'Mon', 'Thu', 'Sat']) We can remove elements from a set by using discard() method. Again as discussed there is no specific index attached to the newly added element. Days=set(["Mon","Tue","Wed","Thu","Fri","Sat"]) Days.discard("Sun") print(Days) When the above code is executed, it produces the following result. set(['Wed', 'Fri', 'Tue', 'Mon', 'Thu', 'Sat']) The union operation on two sets produces a new set containing all the distinct elements from both the sets. In the below example the element “Wed” is present in both the sets. DaysA = set(["Mon","Tue","Wed"]) DaysB = set(["Wed","Thu","Fri","Sat","Sun"]) AllDays = DaysA|DaysB print(AllDays) When the above code is executed, it produces the following result. Please note the result has only one “wed”. set(['Wed', 'Fri', 'Tue', 'Mon', 'Thu', 'Sat']) The intersection operation on two sets produces a new set containing only the common elements from both the sets. In the below example the element “Wed” is present in both the sets. DaysA = set(["Mon","Tue","Wed"]) DaysB = set(["Wed","Thu","Fri","Sat","Sun"]) AllDays = DaysA & DaysB print(AllDays) When the above code is executed, it produces the following result. Please note the result has only one “wed”. set(['Wed']) The difference operation on two sets produces a new set containing only the elements from the first set and none from the second set. In the below example the element “Wed” is present in both the sets so it will not be found in the result set. DaysA = set(["Mon","Tue","Wed"]) DaysB = set(["Wed","Thu","Fri","Sat","Sun"]) AllDays = DaysA - DaysB print(AllDays) When the above code is executed, it produces the following result. Please note the result has only one “wed”. set(['Mon', 'Tue']) We can check if a given set is a subset or superset of another set. The result is True or False depending on the elements present in the sets. DaysA = set(["Mon","Tue","Wed"]) DaysB = set(["Mon","Tue","Wed","Thu","Fri","Sat","Sun"]) SubsetRes = DaysA <= DaysB SupersetRes = DaysB >= DaysA print(SubsetRes) print(SupersetRes) When the above code is executed, it produces the following result − True True Python Maps also called ChainMap is a type of data structure to manage multiple dictionaries together as one unit. The combined dictionary contains the key and value pairs in a specific sequence eliminating any duplicate keys. The best use of ChainMap is to search through multiple dictionaries at a time and get the proper key-value pair mapping. We also see that these ChainMaps behave as stack data structure. We create two dictionaries and club them using the ChainMap method from the collections library. Then we print the keys and values of the result of the combination of the dictionaries. If there are duplicate keys, then only the value from the first key is preserved. import collections dict1 = {'day1': 'Mon', 'day2': 'Tue'} dict2 = {'day3': 'Wed', 'day1': 'Thu'} res = collections.ChainMap(dict1, dict2) # Creating a single dictionary print(res.maps,'\n') print('Keys = {}'.format(list(res.keys()))) print('Values = {}'.format(list(res.values()))) print() # Print all the elements from the result print('elements:') for key, val in res.items(): print('{} = {}'.format(key, val)) print() # Find a specific value in the result print('day3 in res: {}'.format(('day1' in res))) print('day4 in res: {}'.format(('day4' in res))) When the above code is executed, it produces the following result − [{'day1': 'Mon', 'day2': 'Tue'}, {'day1': 'Thu', 'day3': 'Wed'}] Keys = ['day1', 'day3', 'day2'] Values = ['Mon', 'Wed', 'Tue'] elements: day1 = Mon day3 = Wed day2 = Tue day3 in res: True day4 in res: False If we change the order the dictionaries while clubbing them in the above example we see that the position of the elements get interchanged as if they are in a continuous chain. This again shows the behavior of Maps as stacks. import collections dict1 = {'day1': 'Mon', 'day2': 'Tue'} dict2 = {'day3': 'Wed', 'day4': 'Thu'} res1 = collections.ChainMap(dict1, dict2) print(res1.maps,'\n') res2 = collections.ChainMap(dict2, dict1) print(res2.maps,'\n') When the above code is executed, it produces the following result − [{'day1': 'Mon', 'day2': 'Tue'}, {'day3': 'Wed', 'day4': 'Thu'}] [{'day3': 'Wed', 'day4': 'Thu'}, {'day1': 'Mon', 'day2': 'Tue'}] When the element of the dictionary is updated, the result is instantly updated in the result of the ChainMap. In the below example we see that the new updated value reflects in the result without explicitly applying the ChainMap method again. import collections dict1 = {'day1': 'Mon', 'day2': 'Tue'} dict2 = {'day3': 'Wed', 'day4': 'Thu'} res = collections.ChainMap(dict1, dict2) print(res.maps,'\n') dict2['day4'] = 'Fri' print(res.maps,'\n') When the above code is executed, it produces the following result − [{'day1': 'Mon', 'day2': 'Tue'}, {'day3': 'Wed', 'day4': 'Thu'}] [{'day1': 'Mon', 'day2': 'Tue'}, {'day3': 'Wed', 'day4': 'Fri'}] A linked list is a sequence of data elements, which are connected together via links. Each data element contains a connection to another data element in form of a pointer. Python does not have linked lists in its standard library. We implement the concept of linked lists using the concept of nodes as discussed in the previous chapter. We have already seen how we create a node class and how to traverse the elements of a node.In this chapter we are going to study the types of linked lists known as singly linked lists. In this type of data structure there is only one link between any two data elements. We create such a list and create additional methods to insert, update and remove elements from the list. A linked list is created by using the node class we studied in the last chapter. We create a Node object and create another class to use this ode object. We pass the appropriate values through the node object to point the to the next data elements. The below program creates the linked list with three data elements. In the next section we will see how to traverse the linked list. class Node: def __init__(self, dataval=None): self.dataval = dataval self.nextval = None class SLinkedList: def __init__(self): self.headval = None list1 = SLinkedList() list1.headval = Node("Mon") e2 = Node("Tue") e3 = Node("Wed") # Link first Node to second node list1.headval.nextval = e2 # Link second Node to third node e2.nextval = e3 Singly linked lists can be traversed in only forward direction starting form the first data element. We simply print the value of the next data element by assigning the pointer of the next node to the current data element. class Node: def __init__(self, dataval=None): self.dataval = dataval self.nextval = None class SLinkedList: def __init__(self): self.headval = None def listprint(self): printval = self.headval while printval is not None: print (printval.dataval) printval = printval.nextval list = SLinkedList() list.headval = Node("Mon") e2 = Node("Tue") e3 = Node("Wed") # Link first Node to second node list.headval.nextval = e2 # Link second Node to third node e2.nextval = e3 list.listprint() When the above code is executed, it produces the following result − Mon Tue Wed Inserting element in the linked list involves reassigning the pointers from the existing nodes to the newly inserted node. Depending on whether the new data element is getting inserted at the beginning or at the middle or at the end of the linked list, we have the below scenarios. This involves pointing the next pointer of the new data node to the current head of the linked list. So the current head of the linked list becomes the second data element and the new node becomes the head of the linked list. class Node: def __init__(self, dataval=None): self.dataval = dataval self.nextval = None class SLinkedList: def __init__(self): self.headval = None # Print the linked list def listprint(self): printval = self.headval while printval is not None: print (printval.dataval) printval = printval.nextval def AtBegining(self,newdata): NewNode = Node(newdata) # Update the new nodes next val to existing node NewNode.nextval = self.headval self.headval = NewNode list = SLinkedList() list.headval = Node("Mon") e2 = Node("Tue") e3 = Node("Wed") list.headval.nextval = e2 e2.nextval = e3 list.AtBegining("Sun") list.listprint() When the above code is executed, it produces the following result − Sun Mon Tue Wed This involves pointing the next pointer of the the current last node of the linked list to the new data node. So the current last node of the linked list becomes the second last data node and the new node becomes the last node of the linked list. class Node: def __init__(self, dataval=None): self.dataval = dataval self.nextval = None class SLinkedList: def __init__(self): self.headval = None # Function to add newnode def AtEnd(self, newdata): NewNode = Node(newdata) if self.headval is None: self.headval = NewNode return laste = self.headval while(laste.nextval): laste = laste.nextval laste.nextval=NewNode # Print the linked list def listprint(self): printval = self.headval while printval is not None: print (printval.dataval) printval = printval.nextval list = SLinkedList() list.headval = Node("Mon") e2 = Node("Tue") e3 = Node("Wed") list.headval.nextval = e2 e2.nextval = e3 list.AtEnd("Thu") list.listprint() When the above code is executed, it produces the following result − Mon Tue Wed Thu This involves changing the pointer of a specific node to point to the new node. That is possible by passing in both the new node and the existing node after which the new node will be inserted. So we define an additional class which will change the next pointer of the new node to the next pointer of middle node. Then assign the new node to next pointer of the middle node. class Node: def __init__(self, dataval=None): self.dataval = dataval self.nextval = None class SLinkedList: def __init__(self): self.headval = None # Function to add node def Inbetween(self,middle_node,newdata): if middle_node is None: print("The mentioned node is absent") return NewNode = Node(newdata) NewNode.nextval = middle_node.nextval middle_node.nextval = NewNode # Print the linked list def listprint(self): printval = self.headval while printval is not None: print (printval.dataval) printval = printval.nextval list = SLinkedList() list.headval = Node("Mon") e2 = Node("Tue") e3 = Node("Thu") list.headval.nextval = e2 e2.nextval = e3 list.Inbetween(list.headval.nextval,"Fri") list.listprint() When the above code is executed, it produces the following result − Mon Tue Fri Thu We can remove an existing node using the key for that node. In the below program we locate the previous node of the node which is to be deleted.Then, point the next pointer of this node to the next node of the node to be deleted. class Node: def __init__(self, data=None): self.data = data self.next = None class SLinkedList: def __init__(self): self.head = None def Atbegining(self, data_in): NewNode = Node(data_in) NewNode.next = self.head self.head = NewNode # Function to remove node def RemoveNode(self, Removekey): HeadVal = self.head if (HeadVal is not None): if (HeadVal.data == Removekey): self.head = HeadVal.next HeadVal = None return while (HeadVal is not None): if HeadVal.data == Removekey: break prev = HeadVal HeadVal = HeadVal.next if (HeadVal == None): return prev.next = HeadVal.next HeadVal = None def LListprint(self): printval = self.head while (printval): print(printval.data), printval = printval.next llist = SLinkedList() llist.Atbegining("Mon") llist.Atbegining("Tue") llist.Atbegining("Wed") llist.Atbegining("Thu") llist.RemoveNode("Tue") llist.LListprint() When the above code is executed, it produces the following result − Thu Wed Mon In the english dictionary the word stack means arranging objects on over another. It is the same way memory is allocated in this data structure. It stores the data elements in a similar fashion as a bunch of plates are stored one above another in the kitchen. So stack data strcuture allows operations at one end wich can be called top of the stack.We can add elements or remove elements only form this en dof the stack. In a stack the element insreted last in sequence will come out first as we can remove only from the top of the stack. Such feature is known as Last in First Out(LIFO) feature. The operations of adding and removing the elements is known as PUSH and POP. In the following program we implement it as add and and remove functions. We declare an empty list and use the append() and pop() methods to add and remove the data elements. Let us understand, how to use PUSH in Stack. Refer the program mentioned program below − class Stack: def __init__(self): self.stack = [] def add(self, dataval): # Use list append method to add element if dataval not in self.stack: self.stack.append(dataval) return True else: return False # Use peek to look at the top of the stack def peek(self): return self.stack[-1] AStack = Stack() AStack.add("Mon") AStack.add("Tue") AStack.peek() print(AStack.peek()) AStack.add("Wed") AStack.add("Thu") print(AStack.peek()) When the above code is executed, it produces the following result − Tue Thu As we know we can remove only the top most data element from the stack, we implement a python program which does that. The remove function in the following program returns the top most element. we check the top element by calculating the size of the stack first and then use the in-built pop() method to find out the top most element. class Stack: def __init__(self): self.stack = [] def add(self, dataval): # Use list append method to add element if dataval not in self.stack: self.stack.append(dataval) return True else: return False # Use list pop method to remove element def remove(self): if len(self.stack) <= 0: return ("No element in the Stack") else: return self.stack.pop() AStack = Stack() AStack.add("Mon") AStack.add("Tue") AStack.add("Wed") AStack.add("Thu") print(AStack.remove()) print(AStack.remove()) When the above code is executed, it produces the following result − Thu Wed We are familiar with queue in our day to day life as we wait for a service. The queue data structure aslo means the same where the data elements are arranged in a queue. The uniqueness of queue lies in the way items are added and removed. The items are allowed at on end but removed form the other end. So it is a First-in-First out method. A queue can be implemented using python list where we can use the insert() and pop() methods to add and remove elements. Their is no insertion as data elements are always added at the end of the queue. In the below example we create a queue class where we implement the First-in-First-Out method. We use the in-built insert method for adding data elements. class Queue: def __init__(self): self.queue = list() def addtoq(self,dataval): # Insert method to add element if dataval not in self.queue: self.queue.insert(0,dataval) return True return False def size(self): return len(self.queue) TheQueue = Queue() TheQueue.addtoq("Mon") TheQueue.addtoq("Tue") TheQueue.addtoq("Wed") print(TheQueue.size()) When the above code is executed, it produces the following result − 3 In the below example we create a queue class where we insert the data and then remove the data using the in-built pop method. class Queue: def __init__(self): self.queue = list() def addtoq(self,dataval): # Insert method to add element if dataval not in self.queue: self.queue.insert(0,dataval) return True return False # Pop method to remove element def removefromq(self): if len(self.queue)>0: return self.queue.pop() return ("No elements in Queue!") TheQueue = Queue() TheQueue.addtoq("Mon") TheQueue.addtoq("Tue") TheQueue.addtoq("Wed") print(TheQueue.removefromq()) print(TheQueue.removefromq()) When the above code is executed, it produces the following result − Mon Tue A double-ended queue, or deque, supports adding and removing elements from either end. The more commonly used stacks and queues are degenerate forms of deques, where the inputs and outputs are restricted to a single end. import collections DoubleEnded = collections.deque(["Mon","Tue","Wed"]) DoubleEnded.append("Thu") print ("Appended at right - ") print (DoubleEnded) DoubleEnded.appendleft("Sun") print ("Appended at right at left is - ") print (DoubleEnded) DoubleEnded.pop() print ("Deleting from right - ") print (DoubleEnded) DoubleEnded.popleft() print ("Deleting from left - ") print (DoubleEnded) When the above code is executed, it produces the following result − Appended at right - deque(['Mon', 'Tue', 'Wed', 'Thu']) Appended at right at left is - deque(['Sun', 'Mon', 'Tue', 'Wed', 'Thu']) Deleting from right - deque(['Sun', 'Mon', 'Tue', 'Wed']) Deleting from left - deque(['Mon', 'Tue', 'Wed']) We have already seen Linked List in earlier chapter in which it is possible only to travel forward. In this chapter we see another type of linked list in which it is possible to travel both forward and backward. Such a linked list is called Doubly Linked List. Following is the features of doubly linked list. Doubly Linked List contains a link element called first and last. Doubly Linked List contains a link element called first and last. Each link carries a data field(s) and two link fields called next and prev. Each link carries a data field(s) and two link fields called next and prev. Each link is linked with its next link using its next link. Each link is linked with its next link using its next link. Each link is linked with its previous link using its previous link. Each link is linked with its previous link using its previous link. The last link carries a link as null to mark the end of the list. The last link carries a link as null to mark the end of the list. We create a Doubly Linked list by using the Node class. Now we use the same approach as used in the Singly Linked List but the head and next pointers will be used for proper assignation to create two links in each of the nodes in addition to the data present in the node. class Node: def __init__(self, data): self.data = data self.next = None self.prev = None class doubly_linked_list: def __init__(self): self.head = None # Adding data elements def push(self, NewVal): NewNode = Node(NewVal) NewNode.next = self.head if self.head is not None: self.head.prev = NewNode self.head = NewNode # Print the Doubly Linked list def listprint(self, node): while (node is not None): print(node.data), last = node node = node.next dllist = doubly_linked_list() dllist.push(12) dllist.push(8) dllist.push(62) dllist.listprint(dllist.head) When the above code is executed, it produces the following result − 62 8 12 Here, we are going to see how to insert a node to the Doubly Link List using the following program. The program uses a method named insert which inserts the new node at the third position from the head of the doubly linked list. # Create the Node class class Node: def __init__(self, data): self.data = data self.next = None self.prev = None # Create the doubly linked list class doubly_linked_list: def __init__(self): self.head = None # Define the push method to add elements def push(self, NewVal): NewNode = Node(NewVal) NewNode.next = self.head if self.head is not None: self.head.prev = NewNode self.head = NewNode # Define the insert method to insert the element def insert(self, prev_node, NewVal): if prev_node is None: return NewNode = Node(NewVal) NewNode.next = prev_node.next prev_node.next = NewNode NewNode.prev = prev_node if NewNode.next is not None: NewNode.next.prev = NewNode # Define the method to print the linked list def listprint(self, node): while (node is not None): print(node.data), last = node node = node.next dllist = doubly_linked_list() dllist.push(12) dllist.push(8) dllist.push(62) dllist.insert(dllist.head.next, 13) dllist.listprint(dllist.head) When the above code is executed, it produces the following result − 62 8 13 12 Appending to a doubly linked list will add the element at the end. # Create the node class class Node: def __init__(self, data): self.data = data self.next = None self.prev = None # Create the doubly linked list class class doubly_linked_list: def __init__(self): self.head = None # Define the push method to add elements at the begining def push(self, NewVal): NewNode = Node(NewVal) NewNode.next = self.head if self.head is not None: self.head.prev = NewNode self.head = NewNode # Define the append method to add elements at the end def append(self, NewVal): NewNode = Node(NewVal) NewNode.next = None if self.head is None: NewNode.prev = None self.head = NewNode return last = self.head while (last.next is not None): last = last.next last.next = NewNode NewNode.prev = last return # Define the method to print def listprint(self, node): while (node is not None): print(node.data), last = node node = node.next dllist = doubly_linked_list() dllist.push(12) dllist.append(9) dllist.push(8) dllist.push(62) dllist.append(45) dllist.listprint(dllist.head) When the above code is executed, it produces the following result − 62 8 12 9 45 Please note the position of the elements 9 and 45 for the append operation. Hash tables are a type of data structure in which the address or the index value of the data element is generated from a hash function. That makes accessing the data faster as the index value behaves as a key for the data value. In other words Hash table stores key-value pairs but the key is generated through a hashing function. So the search and insertion function of a data element becomes much faster as the key values themselves become the index of the array which stores the data. In Python, the Dictionary data types represent the implementation of hash tables. The Keys in the dictionary satisfy the following requirements. The keys of the dictionary are hashable i.e. the are generated by hashing function which generates unique result for each unique value supplied to the hash function. The keys of the dictionary are hashable i.e. the are generated by hashing function which generates unique result for each unique value supplied to the hash function. The order of data elements in a dictionary is not fixed. The order of data elements in a dictionary is not fixed. So we see the implementation of hash table by using the dictionary data types as below. To access dictionary elements, you can use the familiar square brackets along with the key to obtain its value. # Declare a dictionary dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'} # Accessing the dictionary with its key print "dict['Name']: ", dict['Name'] print "dict['Age']: ", dict['Age'] When the above code is executed, it produces the following result − dict['Name']: Zara dict['Age']: 7 You can update a dictionary by adding a new entry or a key-value pair, modifying an existing entry, or deleting an existing entry as shown below in the simple example − # Declare a dictionary dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'} dict['Age'] = 8; # update existing entry dict['School'] = "DPS School"; # Add new entry print "dict['Age']: ", dict['Age'] print "dict['School']: ", dict['School'] When the above code is executed, it produces the following result − dict['Age']: 8 dict['School']: DPS School You can either remove individual dictionary elements or clear the entire contents of a dictionary. You can also delete entire dictionary in a single operation.To explicitly remove an entire dictionary, just use the del statement. dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'} del dict['Name']; # remove entry with key 'Name' dict.clear(); # remove all entries in dict del dict ; # delete entire dictionary print "dict['Age']: ", dict['Age'] print "dict['School']: ", dict['School'] This produces the following result. Note that an exception is raised because after del dict dictionary does not exist anymore. dict['Age']: Traceback (most recent call last): File "test.py", line 8, in <module> print "dict['Age']: ", dict['Age']; TypeError: 'type' object is unsubscriptable Tree represents the nodes connected by edges. It is a non-linear data structure. It has the following properties − One node is marked as Root node. One node is marked as Root node. Every node other than the root is associated with one parent node. Every node other than the root is associated with one parent node. Each node can have an arbiatry number of chid node. Each node can have an arbiatry number of chid node. We create a tree data structure in python by using the concept os node discussed earlier. We designate one node as root node and then add more nodes as child nodes. Below is program to create the root node. We just create a Node class and add assign a value to the node. This becomes tree with only a root node. class Node: def __init__(self, data): self.left = None self.right = None self.data = data def PrintTree(self): print(self.data) root = Node(10) root.PrintTree() When the above code is executed, it produces the following result − 10 To insert into a tree we use the same node class created above and add a insert class to it. The insert class compares the value of the node to the parent node and decides to add it as a left node or a right node. Finally the PrintTree class is used to print the tree. class Node: def __init__(self, data): self.left = None self.right = None self.data = data def insert(self, data): # Compare the new value with the parent node if self.data: if data < self.data: if self.left is None: self.left = Node(data) else: self.left.insert(data) elif data > self.data: if self.right is None: self.right = Node(data) else: self.right.insert(data) else: self.data = data # Print the tree def PrintTree(self): if self.left: self.left.PrintTree() print( self.data), if self.right: self.right.PrintTree() # Use the insert method to add nodes root = Node(12) root.insert(6) root.insert(14) root.insert(3) root.PrintTree() When the above code is executed, it produces the following result − 3 6 12 14 The tree can be traversed by deciding on a sequence to visit each node. As we can clearly see we can start at a node then visit the left sub-tree first and right sub-tree next. Or we can also visit the right sub-tree first and left sub-tree next. Accordingly there are different names for these tree traversal methods. Traversal is a process to visit all the nodes of a tree and may print their values too. Because, all nodes are connected via edges (links) we always start from the root (head) node. That is, we cannot randomly access a node in a tree. There are three ways which we use to traverse a tree. In-order Traversal In-order Traversal Pre-order Traversal Pre-order Traversal Post-order Traversal Post-order Traversal In this traversal method, the left subtree is visited first, then the root and later the right sub-tree. We should always remember that every node may represent a subtree itself. In the below python program, we use the Node class to create place holders for the root node as well as the left and right nodes. Then, we create an insert function to add data to the tree. Finally, the In-order traversal logic is implemented by creating an empty list and adding the left node first followed by the root or parent node. At last the left node is added to complete the In-order traversal. Please note that this process is repeated for each sub-tree until all the nodes are traversed. class Node: def __init__(self, data): self.left = None self.right = None self.data = data # Insert Node def insert(self, data): if self.data: if data < self.data: if self.left is None: self.left = Node(data) else: self.left.insert(data) else data > self.data: if self.right is None: self.right = Node(data) else: self.right.insert(data) else: self.data = data # Print the Tree def PrintTree(self): if self.left: self.left.PrintTree() print( self.data), if self.right: self.right.PrintTree() # Inorder traversal # Left -> Root -> Right def inorderTraversal(self, root): res = [] if root: res = self.inorderTraversal(root.left) res.append(root.data) res = res + self.inorderTraversal(root.right) return res root = Node(27) root.insert(14) root.insert(35) root.insert(10) root.insert(19) root.insert(31) root.insert(42) print(root.inorderTraversal(root)) When the above code is executed, it produces the following result − [10, 14, 19, 27, 31, 35, 42] In this traversal method, the root node is visited first, then the left subtree and finally the right subtree. In the below python program, we use the Node class to create place holders for the root node as well as the left and right nodes. Then, we create an insert function to add data to the tree. Finally, the Pre-order traversal logic is implemented by creating an empty list and adding the root node first followed by the left node. At last, the right node is added to complete the Pre-order traversal. Please note that, this process is repeated for each sub-tree until all the nodes are traversed. class Node: def __init__(self, data): self.left = None self.right = None self.data = data # Insert Node def insert(self, data): if self.data: if data < self.data: if self.left is None: self.left = Node(data) else: self.left.insert(data) elif data > self.data: if self.right is None: self.right = Node(data) else: self.right.insert(data) else: self.data = data # Print the Tree def PrintTree(self): if self.left: self.left.PrintTree() print( self.data), if self.right: self.right.PrintTree() # Preorder traversal # Root -> Left ->Right def PreorderTraversal(self, root): res = [] if root: res.append(root.data) res = res + self.PreorderTraversal(root.left) res = res + self.PreorderTraversal(root.right) return res root = Node(27) root.insert(14) root.insert(35) root.insert(10) root.insert(19) root.insert(31) root.insert(42) print(root.PreorderTraversal(root)) When the above code is executed, it produces the following result − [27, 14, 10, 19, 35, 31, 42] In this traversal method, the root node is visited last, hence the name. First, we traverse the left subtree, then the right subtree and finally the root node. In the below python program, we use the Node class to create place holders for the root node as well as the left and right nodes. Then, we create an insert function to add data to the tree. Finally, the Post-order traversal logic is implemented by creating an empty list and adding the left node first followed by the right node. At last the root or parent node is added to complete the Post-order traversal. Please note that, this process is repeated for each sub-tree until all the nodes are traversed. class Node: def __init__(self, data): self.left = None self.right = None self.data = data # Insert Node def insert(self, data): if self.data: if data < self.data: if self.left is None: self.left = Node(data) else: self.left.insert(data) else if data > self.data: if self.right is None: self.right = Node(data) else: self.right.insert(data) else: self.data = data # Print the Tree def PrintTree(self): if self.left: self.left.PrintTree() print( self.data), if self.right: self.right.PrintTree() # Postorder traversal # Left ->Right -> Root def PostorderTraversal(self, root): res = [] if root: res = self.PostorderTraversal(root.left) res = res + self.PostorderTraversal(root.right) res.append(root.data) return res root = Node(27) root.insert(14) root.insert(35) root.insert(10) root.insert(19) root.insert(31) root.insert(42) print(root.PostorderTraversal(root)) When the above code is executed, it produces the following result − [10, 19, 14, 31, 42, 35, 27] A Binary Search Tree (BST) is a tree in which all the nodes follow the below-mentioned properties.The left sub-tree of a node has a key less than or equal to its parent node's key.The right sub-tree of a node has a key greater than to its parent node's key.Thus, BST divides all its sub-trees into two segments; the left sub-tree and the right sub-tree left_subtree (keys) ≤ node (key) ≤ right_subtree (keys) Searching for a value in a tree involves comparing the incoming value with the value exiting nodes. Here also we traverse the nodes from left to right and then finally with the parent. If the searched for value does not match any of the exiting value, then we return not found message, or else the found message is returned. class Node: def __init__(self, data): self.left = None self.right = None self.data = data # Insert method to create nodes def insert(self, data): if self.data: if data < self.data: if self.left is None: self.left = Node(data) else: self.left.insert(data) else data > self.data: if self.right is None: self.right = Node(data) else: self.right.insert(data) else: self.data = data # findval method to compare the value with nodes def findval(self, lkpval): if lkpval < self.data: if self.left is None: return str(lkpval)+" Not Found" return self.left.findval(lkpval) else if lkpval > self.data: if self.right is None: return str(lkpval)+" Not Found" return self.right.findval(lkpval) else: print(str(self.data) + ' is found') # Print the tree def PrintTree(self): if self.left: self.left.PrintTree() print( self.data), if self.right: self.right.PrintTree() root = Node(12) root.insert(6) root.insert(14) root.insert(3) print(root.findval(7)) print(root.findval(14)) When the above code is executed, it produces the following result − 7 Not Found 14 is found Heap is a special tree structure in which each parent node is less than or equal to its child node. Then it is called a Min Heap. If each parent node is greater than or equal to its child node then it is called a max heap. It is very useful is implementing priority queues where the queue item with higher weightage is given more priority in processing. A detailed discussion on heaps is available in our website here. Please study it first if you are new to heap data structure. In this chapter we will see the implementation of heap data structure using python. A heap is created by using python’s inbuilt library named heapq. This library has the relevant functions to carry out various operations on heap data structure. Below is a list of these functions. heapify − This function converts a regular list to a heap. In the resulting heap the smallest element gets pushed to the index position 0. But rest of the data elements are not necessarily sorted. heapify − This function converts a regular list to a heap. In the resulting heap the smallest element gets pushed to the index position 0. But rest of the data elements are not necessarily sorted. heappush − This function adds an element to the heap without altering the current heap. heappush − This function adds an element to the heap without altering the current heap. heappop − This function returns the smallest data element from the heap. heappop − This function returns the smallest data element from the heap. heapreplace − This function replaces the smallest data element with a new value supplied in the function. heapreplace − This function replaces the smallest data element with a new value supplied in the function. A heap is created by simply using a list of elements with the heapify function. In the below example we supply a list of elements and the heapify function rearranges the elements bringing the smallest element to the first position. import heapq H = [21,1,45,78,3,5] # Use heapify to rearrange the elements heapq.heapify(H) print(H) When the above code is executed, it produces the following result − [1, 3, 5, 78, 21, 45] Inserting a data element to a heap always adds the element at the last index. But you can apply heapify function again to bring the newly added element to the first index only if it smallest in value. In the below example we insert the number 8. import heapq H = [21,1,45,78,3,5] # Covert to a heap heapq.heapify(H) print(H) # Add element heapq.heappush(H,8) print(H) When the above code is executed, it produces the following result − [1, 3, 5, 78, 21, 45] [1, 3, 5, 78, 21, 45, 8] You can remove the element at first index by using this function. In the below example the function will always remove the element at the index position 1. import heapq H = [21,1,45,78,3,5] # Create the heap heapq.heapify(H) print(H) # Remove element from the heap heapq.heappop(H) print(H) When the above code is executed, it produces the following result − [1, 3, 5, 78, 21, 45] [3, 21, 5, 78, 45] The heap replace function always removes the smallest element of the heap and inserts the new incoming element at some place not fixed by any order. import heapq H = [21,1,45,78,3,5] # Create the heap heapq.heapify(H) print(H) # Replace an element heapq.heapreplace(H,6) print(H) When the above code is executed, it produces the following result − [1, 3, 5, 78, 21, 45] [3, 6, 5, 78, 21, 45] A graph is a pictorial representation of a set of objects where some pairs of objects are connected by links. The interconnected objects are represented by points termed as vertices, and the links that connect the vertices are called edges. The various terms and functionalities associated with a graph is described in great detail in our tutorial here. In this chapter we are going to see how to create a graph and add various data elements to it using a python program. Following are the basic operations we perform on graphs. Display graph vertices Display graph edges Add a vertex Add an edge Creating a graph A graph can be easily presented using the python dictionary data types. We represent the vertices as the keys of the dictionary and the connection between the vertices also called edges as the values in the dictionary. Take a look at the following graph − In the above graph, V = {a, b, c, d, e} E = {ab, ac, bd, cd, de} We can present this graph in a python program as below − # Create the dictionary with graph elements graph = { "a" : ["b","c"], "b" : ["a", "d"], "c" : ["a", "d"], "d" : ["e"], "e" : ["d"] } # Print the graph print(graph) When the above code is executed, it produces the following result − {'c': ['a', 'd'], 'a': ['b', 'c'], 'e': ['d'], 'd': ['e'], 'b': ['a', 'd']} To display the graph vertices we simple find the keys of the graph dictionary. We use the keys() method. class graph: def __init__(self,gdict=None): if gdict is None: gdict = [] self.gdict = gdict # Get the keys of the dictionary def getVertices(self): return list(self.gdict.keys()) # Create the dictionary with graph elements graph_elements = { "a" : ["b","c"], "b" : ["a", "d"], "c" : ["a", "d"], "d" : ["e"], "e" : ["d"] } g = graph(graph_elements) print(g.getVertices()) When the above code is executed, it produces the following result − ['d', 'b', 'e', 'c', 'a'] Finding the graph edges is little tricker than the vertices as we have to find each of the pairs of vertices which have an edge in between them. So we create an empty list of edges then iterate through the edge values associated with each of the vertices. A list is formed containing the distinct group of edges found from the vertices. class graph: def __init__(self,gdict=None): if gdict is None: gdict = {} self.gdict = gdict def edges(self): return self.findedges() # Find the distinct list of edges def findedges(self): edgename = [] for vrtx in self.gdict: for nxtvrtx in self.gdict[vrtx]: if {nxtvrtx, vrtx} not in edgename: edgename.append({vrtx, nxtvrtx}) return edgename # Create the dictionary with graph elements graph_elements = { "a" : ["b","c"], "b" : ["a", "d"], "c" : ["a", "d"], "d" : ["e"], "e" : ["d"] } g = graph(graph_elements) print(g.edges()) When the above code is executed, it produces the following result − [{'b', 'a'}, {'b', 'd'}, {'e', 'd'}, {'a', 'c'}, {'c', 'd'}] Adding a vertex is straight forward where we add another additional key to the graph dictionary. class graph: def __init__(self,gdict=None): if gdict is None: gdict = {} self.gdict = gdict def getVertices(self): return list(self.gdict.keys()) # Add the vertex as a key def addVertex(self, vrtx): if vrtx not in self.gdict: self.gdict[vrtx] = [] # Create the dictionary with graph elements graph_elements = { "a" : ["b","c"], "b" : ["a", "d"], "c" : ["a", "d"], "d" : ["e"], "e" : ["d"] } g = graph(graph_elements) g.addVertex("f") print(g.getVertices()) When the above code is executed, it produces the following result − ['f', 'e', 'b', 'a', 'c','d'] Adding an edge to an existing graph involves treating the new vertex as a tuple and validating if the edge is already present. If not then the edge is added. class graph: def __init__(self,gdict=None): if gdict is None: gdict = {} self.gdict = gdict def edges(self): return self.findedges() # Add the new edge def AddEdge(self, edge): edge = set(edge) (vrtx1, vrtx2) = tuple(edge) if vrtx1 in self.gdict: self.gdict[vrtx1].append(vrtx2) else: self.gdict[vrtx1] = [vrtx2] # List the edge names def findedges(self): edgename = [] for vrtx in self.gdict: for nxtvrtx in self.gdict[vrtx]: if {nxtvrtx, vrtx} not in edgename: edgename.append({vrtx, nxtvrtx}) return edgename # Create the dictionary with graph elements graph_elements = { "a" : ["b","c"], "b" : ["a", "d"], "c" : ["a", "d"], "d" : ["e"], "e" : ["d"] } g = graph(graph_elements) g.AddEdge({'a','e'}) g.AddEdge({'a','c'}) print(g.edges()) When the above code is executed, it produces the following result − [{'e', 'd'}, {'b', 'a'}, {'b', 'd'}, {'a', 'c'}, {'a', 'e'}, {'c', 'd'}] Algorithm is a step-by-step procedure, which defines a set of instructions to be executed in a certain order to get the desired output. Algorithms are generally created independent of underlying languages, i.e. an algorithm can be implemented in more than one programming language. From the data structure point of view, following are some important categories of algorithms − Search − Algorithm to search an item in a data structure. Search − Algorithm to search an item in a data structure. Sort − Algorithm to sort items in a certain order. Sort − Algorithm to sort items in a certain order. Insert − Algorithm to insert item in a data structure. Insert − Algorithm to insert item in a data structure. Update − Algorithm to update an existing item in a data structure. Update − Algorithm to update an existing item in a data structure. Delete − Algorithm to delete an existing item from a data structure. Delete − Algorithm to delete an existing item from a data structure. Not all procedures can be called an algorithm. An algorithm should have the following characteristics − Unambiguous − Algorithm should be clear and unambiguous. Each of its steps (or phases), and their inputs/outputs should be clear and must lead to only one meaning. Unambiguous − Algorithm should be clear and unambiguous. Each of its steps (or phases), and their inputs/outputs should be clear and must lead to only one meaning. Input − An algorithm should have 0 or more well-defined inputs. Input − An algorithm should have 0 or more well-defined inputs. Output − An algorithm should have 1 or more well-defined outputs, and should match the desired output. Output − An algorithm should have 1 or more well-defined outputs, and should match the desired output. Finiteness − Algorithms must terminate after a finite number of steps. Finiteness − Algorithms must terminate after a finite number of steps. Feasibility − Should be feasible with the available resources. Feasibility − Should be feasible with the available resources. Independent − An algorithm should have step-by-step directions, which should be independent of any programming code. Independent − An algorithm should have step-by-step directions, which should be independent of any programming code. There are no well-defined standards for writing algorithms. Rather, it is problem and resource dependent. Algorithms are never written to support a particular programming code. As we know that all programming languages share basic code constructs like loops (do, for, while), flow-control (if-else), etc. These common constructs can be used to write an algorithm. We write algorithms in a step-by-step manner, but it is not always the case. Algorithm writing is a process and is executed after the problem domain is well-defined. That is, we should know the problem domain, for which we are designing a solution. Let's try to learn algorithm-writing by using an example. Problem − Design an algorithm to add two numbers and display the result. Problem − Design an algorithm to add two numbers and display the result. step 1 − START step 2 − declare three integers a, b & c step 3 − define values of a & b step 4 − add values of a & b step 5 − store output of step 4 to c step 6 − print c step 7 − STOP Algorithms tell the programmers how to code the program. Alternatively, the algorithm can be written as − step 1 − START ADD step 2 − get values of a & b step 3 − c ← a + b step 4 − display c step 5 − STOP In design and analysis of algorithms, usually the second method is used to describe an algorithm. It makes it easy for the analyst to analyze the algorithm ignoring all unwanted definitions. He can observe what operations are being used and how the process is flowing. Writing step numbers, is optional. We design an algorithm to get a solution of a given problem. A problem can be solved in more than one ways. Hence, many solution algorithms can be derived for a given problem. The next step is to analyze those proposed solution algorithms and implement the best suitable solution. In divide and conquer approach, the problem in hand, is divided into smaller sub-problems and then each problem is solved independently. When we keep on dividing the subproblems into even smaller sub-problems, we may eventually reach a stage where no more division is possible. Those "atomic" smallest possible sub-problem (fractions) are solved. The solution of all sub-problems is finally merged in order to obtain the solution of an original problem. Broadly, we can understand divide-and-conquer approach in a three-step process. This step involves breaking the problem into smaller sub-problems. Sub-problems should represent a part of the original problem. This step generally takes a recursive approach to divide the problem until no sub-problem is further divisible. At this stage, sub-problems become atomic in nature but still represent some part of the actual problem. This step receives a lot of smaller sub-problems to be solved. Generally, at this level, the problems are considered 'solved' on their own. When the smaller sub-problems are solved, this stage recursively combines them until they formulate a solution of the original problem. This algorithmic approach works recursively and conquer &s; merge steps works so close that they appear as one. The following program is an example of divide-and-conquer programming approach where the binary search is implemented using python. In binary search we take a sorted list of elements and start looking for an element at the middle of the list. If the search value matches with the middle value in the list we complete the search. Otherwise we eleminate half of the list of elements by choosing whether to procees with the right or left half of the list depending on the value of the item searched. This is possible as the list is sorted and it is much quicker than linear search.Here we divide the given list and conquer by choosing the proper half of the list. We repeat this approcah till we find the element or conclude about it's absence in the list. def bsearch(list, val): list_size = len(list) - 1 idx0 = 0 idxn = list_size # Find the middle most value while idx0 <= idxn: midval = (idx0 + idxn)// 2 if list[midval] == val: return midval # Compare the value the middle most value if val > list[midval]: idx0 = midval + 1 else: idxn = midval - 1 if idx0 > idxn: return None # Initialize the sorted list list = [2,7,19,34,53,72] # Print the search result print(bsearch(list,72)) print(bsearch(list,11)) When the above code is executed, it produces the following result − 5 None Recursion allows a function to call itself. Fixed steps of code get executed again and again for new values. We also have to set criteria for deciding when the recursive call ends. In the below example we see a recursive approach to the binary search. We take a sorted list and give its index range as input to the recursive function. We implement the algorithm of binary search using python as shown below. We use an ordered list of items and design a recursive function to take in the list along with starting and ending index as input. Then, the binary search function calls itself till find the searched item or concludes about its absence in the list. def bsearch(list, idx0, idxn, val): if (idxn < idx0): return None else: midval = idx0 + ((idxn - idx0) // 2) # Compare the search item with middle most value if list[midval] > val: return bsearch(list, idx0, midval-1,val) else if list[midval] < val: return bsearch(list, midval+1, idxn, val) else: return midval list = [8,11,24,56,88,131] print(bsearch(list, 0, 5, 24)) print(bsearch(list, 0, 5, 51)) When the above code is executed, it produces the following result − 2 None Backtracking is a form of recursion. But it involves choosing only option out of any possibilities. We begin by choosing an option and backtrack from it, if we reach a state where we conclude that this specific option does not give the required solution. We repeat these steps by going across each available option until we get the desired solution. Below is an example of finding all possible order of arrangements of a given set of letters. When we choose a pair we apply backtracking to verify if that exact pair has already been created or not. If not already created, the pair is added to the answer list else it is ignored. def permute(list, s): if list == 1: return s else: return [ y + x for y in permute(1, s) for x in permute(list - 1, s) ] print(permute(1, ["a","b","c"])) print(permute(2, ["a","b","c"])) When the above code is executed, it produces the following result − ['a', 'b', 'c'] ['aa', 'ab', 'ac', 'ba', 'bb', 'bc', 'ca', 'cb', 'cc'] Sorting refers to arranging data in a particular format. Sorting algorithm specifies the way to arrange data in a particular order. Most common orders are in numerical or lexicographical order. The importance of sorting lies in the fact that data searching can be optimized to a very high level, if data is stored in a sorted manner. Sorting is also used to represent data in more readable formats. Below we see five such implementations of sorting in python. Bubble Sort Bubble Sort Merge Sort Merge Sort Insertion Sort Insertion Sort Shell Sort Shell Sort Selection Sort Selection Sort It is a comparison-based algorithm in which each pair of adjacent elements is compared and the elements are swapped if they are not in order. def bubblesort(list): # Swap the elements to arrange in order for iter_num in range(len(list)-1,0,-1): for idx in range(iter_num): if list[idx]>list[idx+1]: temp = list[idx] list[idx] = list[idx+1] list[idx+1] = temp list = [19,2,31,45,6,11,121,27] bubblesort(list) print(list) When the above code is executed, it produces the following result − [2, 6, 11, 19, 27, 31, 45, 121] Merge sort first divides the array into equal halves and then combines them in a sorted manner. def merge_sort(unsorted_list): if len(unsorted_list) <= 1: return unsorted_list # Find the middle point and devide it middle = len(unsorted_list) // 2 left_list = unsorted_list[:middle] right_list = unsorted_list[middle:] left_list = merge_sort(left_list) right_list = merge_sort(right_list) return list(merge(left_list, right_list)) # Merge the sorted halves def merge(left_half,right_half): res = [] while len(left_half) != 0 and len(right_half) != 0: if left_half[0] < right_half[0]: res.append(left_half[0]) left_half.remove(left_half[0]) else: res.append(right_half[0]) right_half.remove(right_half[0]) if len(left_half) == 0: res = res + right_half else: res = res + left_half return res unsorted_list = [64, 34, 25, 12, 22, 11, 90] print(merge_sort(unsorted_list)) When the above code is executed, it produces the following result − [11, 12, 22, 25, 34, 64, 90] Insertion sort involves finding the right place for a given element in a sorted list. So in beginning we compare the first two elements and sort them by comparing them. Then we pick the third element and find its proper position among the previous two sorted elements. This way we gradually go on adding more elements to the already sorted list by putting them in their proper position. def insertion_sort(InputList): for i in range(1, len(InputList)): j = i-1 nxt_element = InputList[i] # Compare the current element with next one while (InputList[j] > nxt_element) and (j >= 0): InputList[j+1] = InputList[j] j=j-1 InputList[j+1] = nxt_element list = [19,2,31,45,30,11,121,27] insertion_sort(list) print(list) When the above code is executed, it produces the following result − [2, 11, 19, 27, 30, 31, 45, 121] Shell Sort involves sorting elements which are away from each other. We sort a large sublist of a given list and go on reducing the size of the list until all elements are sorted. The below program finds the gap by equating it to half of the length of the list size and then starts sorting all elements in it. Then we keep resetting the gap until the entire list is sorted. def shellSort(input_list): gap = len(input_list) // 2 while gap > 0: for i in range(gap, len(input_list)): temp = input_list[i] j = i # Sort the sub list for this gap while j >= gap and input_list[j - gap] > temp: input_list[j] = input_list[j - gap] j = j-gap input_list[j] = temp # Reduce the gap for the next element gap = gap//2 list = [19,2,31,45,30,11,121,27] shellSort(list) print(list) When the above code is executed, it produces the following result − [2, 11, 19, 27, 30, 31, 45, 121] In selection sort we start by finding the minimum value in a given list and move it to a sorted list. Then we repeat the process for each of the remaining elements in the unsorted list. The next element entering the sorted list is compared with the existing elements and placed at its correct position.So, at the end all the elements from the unsorted list are sorted. def selection_sort(input_list): for idx in range(len(input_list)): min_idx = idx for j in range( idx +1, len(input_list)): if input_list[min_idx] > input_list[j]: min_idx = j # Swap the minimum value with the compared value input_list[idx], input_list[min_idx] = input_list[min_idx], input_list[idx] l = [19,2,31,45,30,11,121,27] selection_sort(l) print(l) When the above code is executed, it produces the following result − [2, 11, 19, 27, 30, 31, 45, 121] Searching is a very basic necessity when you store data in different data structures. The simplest approach is to go across every element in the data structure and match it with the value you are searching for.This is known as Linear search. It is inefficient and rarely used, but creating a program for it gives an idea about how we can implement some advanced search algorithms. In this type of search, a sequential search is made over all items one by one. Every item is checked and if a match is found then that particular item is returned, otherwise the search continues till the end of the data structure. def linear_search(values, search_for): search_at = 0 search_res = False # Match the value with each data element while search_at < len(values) and search_res is False: if values[search_at] == search_for: search_res = True else: search_at = search_at + 1 return search_res l = [64, 34, 25, 12, 22, 11, 90] print(linear_search(l, 12)) print(linear_search(l, 91)) When the above code is executed, it produces the following result − True False This search algorithm works on the probing position of the required value. For this algorithm to work properly, the data collection should be in a sorted form and equally distributed.Initially, the probe position is the position of the middle most item of the collection.If a match occurs, then the index of the item is returned.If the middle item is greater than the item, then the probe position is again calculated in the sub-array to the right of the middle item. Otherwise, the item is searched in the subarray to the left of the middle item. This process continues on the sub-array as well until the size of subarray reduces to zero. There is a specific formula to calculate the middle position which is indicated in the program below − def intpolsearch(values,x ): idx0 = 0 idxn = (len(values) - 1) while idx0 <= idxn and x >= values[idx0] and x <= values[idxn]: # Find the mid point mid = idx0 +\ int(((float(idxn - idx0)/( values[idxn] - values[idx0])) * ( x - values[idx0]))) # Compare the value at mid point with search value if values[mid] == x: return "Found "+str(x)+" at index "+str(mid) if values[mid] < x: idx0 = mid + 1 return "Searched element not in the list" l = [2, 6, 11, 19, 27, 31, 45, 121] print(intpolsearch(l, 2)) When the above code is executed, it produces the following result − Found 2 at index 0 Graphs are very useful data structures in solving many important mathematical challenges. For example computer network topology or analysing molecular structures of chemical compounds. They are also used in city traffic or route planning and even in human languages and their grammar. All these applications have a common challenge of traversing the graph using their edges and ensuring that all nodes of the graphs are visited. There are two common established methods to do this traversal which is described below. Also called depth first search (DFS),this algorithm traverses a graph in a depth ward motion and uses a stack to remember to get the next vertex to start a search, when a dead end occurs in any iteration. We implement DFS for a graph in python using the set data types as they provide the required functionalities to keep track of visited and unvisited nodes. class graph: def __init__(self,gdict=None): if gdict is None: gdict = {} self.gdict = gdict # Check for the visisted and unvisited nodes def dfs(graph, start, visited = None): if visited is None: visited = set() visited.add(start) print(start) for next in graph[start] - visited: dfs(graph, next, visited) return visited gdict = { "a" : set(["b","c"]), "b" : set(["a", "d"]), "c" : set(["a", "d"]), "d" : set(["e"]), "e" : set(["a"]) } dfs(gdict, 'a') When the above code is executed, it produces the following result − a b d e c Also called breadth first search (BFS),this algorithm traverses a graph breadth ward motion and uses a queue to remember to get the next vertex to start a search, when a dead end occurs in any iteration. Please visit this link in our website to understand the details of BFS steps for a graph. We implement BFS for a graph in python using queue data structure discussed earlier. When we keep visiting the adjacent unvisited nodes and keep adding it to the queue. Then we start dequeue only the node which is left with no unvisited nodes. We stop the program when there is no next adjacent node to be visited. import collections class graph: def __init__(self,gdict=None): if gdict is None: gdict = {} self.gdict = gdict def bfs(graph, startnode): # Track the visited and unvisited nodes using queue seen, queue = set([startnode]), collections.deque([startnode]) while queue: vertex = queue.popleft() marked(vertex) for node in graph[vertex]: if node not in seen: seen.add(node) queue.append(node) def marked(n): print(n) # The graph dictionary gdict = { "a" : set(["b","c"]), "b" : set(["a", "d"]), "c" : set(["a", "d"]), "d" : set(["e"]), "e" : set(["a"]) } bfs(gdict, "a") When the above code is executed, it produces the following result − a c b d e Efficiency of an algorithm can be analyzed at two different stages, before implementation and after implementation. They are the following − A Priori Analysis − This is a theoretical analysis of an algorithm. Efficiency of an algorithm is measured by assuming that all other factors, for example, processor speed, are constant and have no effect on the implementation. A Priori Analysis − This is a theoretical analysis of an algorithm. Efficiency of an algorithm is measured by assuming that all other factors, for example, processor speed, are constant and have no effect on the implementation. A Posterior Analysis − This is an empirical analysis of an algorithm. The selected algorithm is implemented using programming language. This is then executed on target computer machine. In this analysis, actual statistics like running time and space required, are collected. A Posterior Analysis − This is an empirical analysis of an algorithm. The selected algorithm is implemented using programming language. This is then executed on target computer machine. In this analysis, actual statistics like running time and space required, are collected. Suppose X is an algorithm and n is the size of input data, the time and space used by the algorithm X are the two main factors, which decide the efficiency of X. Time Factor − Time is measured by counting the number of key operations such as comparisons in the sorting algorithm. Time Factor − Time is measured by counting the number of key operations such as comparisons in the sorting algorithm. Space Factor − Space is measured by counting the maximum memory space required by the algorithm. Space Factor − Space is measured by counting the maximum memory space required by the algorithm. The complexity of an algorithm f(n) gives the running time and/or the storage space required by the algorithm in terms of n as the size of input data. Space complexity of an algorithm represents the amount of memory space required by the algorithm in its life cycle. The space required by an algorithm is equal to the sum of the following two components − A fixed part that is a space required to store certain data and variables, that are independent of the size of the problem. For example, simple variables and constants used, program size, etc. A fixed part that is a space required to store certain data and variables, that are independent of the size of the problem. For example, simple variables and constants used, program size, etc. A variable part is a space required by variables, whose size depends on the size of the problem. For example, dynamic memory allocation, recursion stack space, etc. A variable part is a space required by variables, whose size depends on the size of the problem. For example, dynamic memory allocation, recursion stack space, etc. Space complexity S(P) of any algorithm P is S(P) = C + SP(I), where C is the fixed part and S(I) is the variable part of the algorithm, which depends on instance characteristic I. Following is a simple example that tries to explain the concept − Algorithm: SUM(A, B) Step 1 − START Step 2 − C ← A + B + 10 Step 3 − Stop Here we have three variables A, B, and C and one constant. Hence S(P) = 1 + 3. Now, space depends on data types of given variables and constant types and it will be multiplied accordingly. Time complexity of an algorithm represents the amount of time required by the algorithm to run to completion. Time requirements can be defined as a numerical function T(n), where T(n) can be measured as the number of steps, provided each step consumes constant time. For example, addition of two n-bit integers takes n steps. Consequently, the total computational time is T(n) = c ∗ n, where c is the time taken for the addition of two bits. Here, we observe that T(n) grows linearly as the input size increases. The efficiency and accuracy of algorithms have to be analysed to compare them and choose a specific algorithm for certain scenarios. The process of making this analysis is called Asymptotic analysis. It refers to computing the running time of any operation in mathematical units of computation. For example, the running time of one operation is computed as f(n) and may be for another operation it is computed as g(n2). This means the first operation running time will increase linearly with the increase in n and the running time of the second operation will increase exponentially when n increases. Similarly, the running time of both operations will be nearly the same if n is significantly small. Usually, the time required by an algorithm falls under three types − Best Case − Minimum time required for program execution. Best Case − Minimum time required for program execution. Average Case − Average time required for program execution. Average Case − Average time required for program execution. Worst Case − Maximum time required for program execution. Worst Case − Maximum time required for program execution. The commonly used asymptotic notations to calculate the running time complexity of an algorithm. Ο Notation Ο Notation Ω Notation Ω Notation θ Notation θ Notation The notation Ο(n) is the formal way to express the upper bound of an algorithm's running time. It measures the worst case time complexity or the longest amount of time an algorithm can possibly take to complete. For example, for a function f(n) Ο(f(n)) = { g(n) : there exists c > 0 and n0 such that f(n) ≤ c.g(n) for all n > n0. } The notation Ω(n) is the formal way to express the lower bound of an algorithm's running time. It measures the best case time complexity or the best amount of time an algorithm can possibly take to complete. For example, for a function f(n) Ω(f(n)) ≥ { g(n) : there exists c > 0 and n0 such that g(n) ≤ c.f(n) for all n > n0. } The notation θ(n) is the formal way to express both the lower bound and the upper bound of an algorithm's running time. It is represented as follows − θ(f(n)) = { g(n) if and only if g(n) = Ο(f(n)) and g(n) = Ω(f(n)) for all n > n0. } A list of some common asymptotic notations is mentioned below − Algorithms are unambiguous steps which should give us a well-defined output by processing zero or more inputs. This leads to many approaches in designing and writing the algorithms. It has been observed that most of the algorithms can be classified into the following categories. Greedy algorithms try to find a localized optimum solution, which may eventually lead to globally optimized solutions. However, generally greedy algorithms do not provide globally optimized solutions. So greedy algorithms look for a easy solution at that point in time without considering how it impacts the future steps. It is similar to how humans solve problems without going through the complete details of the inputs provided. Most networking algorithms use the greedy approach. Here is a list of few of them − Travelling Salesman Problem Travelling Salesman Problem Prim's Minimal Spanning Tree Algorithm Prim's Minimal Spanning Tree Algorithm Kruskal's Minimal Spanning Tree Algorithm Kruskal's Minimal Spanning Tree Algorithm Dijkstra's Minimal Spanning Tree Algorithm Dijkstra's Minimal Spanning Tree Algorithm This class of algorithms involve dividing the given problem into smaller sub-problems and then solving each of the sub-problem independently. When the problem can not be further sub divided, we start merging the solution to each of the sub-problem to arrive at the solution for the bigger problem. The important examples of divide and conquer algorithms are − Merge Sort Merge Sort Quick Sort Quick Sort Kruskal's Minimal Spanning Tree Algorithm Kruskal's Minimal Spanning Tree Algorithm Binary Search Binary Search Dynamic programming involves dividing the bigger problem into smaller ones but unlike divide and conquer it does not involve solving each sub-problem independently. Rather the results of smaller sub-problems are remembered and used for similar or overlapping sub-problems. Mostly, these algorithms are used for optimization. Before solving the in-hand sub-problem, dynamic algorithm will try to examine the results of the previously solved sub-problems.Dynamic algorithms are motivated for an overall optimization of the problem and not the local optimization. The important examples of Dynamic programming algorithms are − Fibonacci number series Fibonacci number series Knapsack problem Knapsack problem Tower of Hanoi Tower of Hanoi Amortized analysis involves estimating the run time for the sequence of operations in a program without taking into consideration the span of the data distribution in the input values. A simple example is finding a value in a sorted list is quicker than in an unsorted list. If the list is already sorted, it does not matter how distributed the data is. But of course the length of the list has an impact as it decides the number of steps the algorithm has to go through to get the final result. So we see that if the initial cost of a single step of obtaining a sorted list is high, then the cost of subsequent steps of finding an element becomes considerably low. So Amortized analysis helps us find a bound on the worst-case running time for a sequence of operations. There are three approaches to amortized analysis. Accounting Method − This involves assigning a cost to each operation performed. If the actual operation finishes quicker than the assigned time then some positive credit is accumulated in the analysis. Accounting Method − This involves assigning a cost to each operation performed. If the actual operation finishes quicker than the assigned time then some positive credit is accumulated in the analysis. In the reverse scenario it will be negative credit. To keep track of these accumulated credits, we use a stack or tree data structure. The operations which are carried out early ( like sorting the list) have high amortized cost but the operations that are late in sequence have lower amortized cost as the accumulated credit is utilized. So the amortized cost is an upper bound of actual cost. Potential Method − In this method the saved credit is utilized for future operations as mathematical function of the state of the data structure. The evaluation of the mathematical function and the amortized cost should be equal. So when the actual cost is greater than amortized cost there is a decrease in potential and it is used utilized for future operations which are expensive. Potential Method − In this method the saved credit is utilized for future operations as mathematical function of the state of the data structure. The evaluation of the mathematical function and the amortized cost should be equal. So when the actual cost is greater than amortized cost there is a decrease in potential and it is used utilized for future operations which are expensive. Aggregate analysis − In this method we estimate the upper bound on the total cost of n steps. The amortized cost is a simple division of total cost and the number of steps (n).. Aggregate analysis − In this method we estimate the upper bound on the total cost of n steps. The amortized cost is a simple division of total cost and the number of steps (n).. In order to make claims about an Algorithm being efficient we need some mathematical tools as proof. These tools help us on providing a mathematically satisfying explanation on the performance and accuracy of the algorithms. Below is a list of some of those mathematical tools which can be used for justifying one algorithm over another. Direct Proof − It is direct verification of the statement by using the direct calculations. For example sum of two even numbers is always an even number. In this case just add the two numbers you are investigating and verify the result as even. Direct Proof − It is direct verification of the statement by using the direct calculations. For example sum of two even numbers is always an even number. In this case just add the two numbers you are investigating and verify the result as even. Proof by induction − Here we start with a specific instance of a truth and then generalize it to all possible values which are part of the truth. The approach is to take a case of verified truth, then prove it is also true for the next case for the same given condition. For example all positive numbers of the form 2n-1 are odd. We prove it for a certain value of n, then prove it for the next value of n. This establishes the statement as generally true by proof of induction. Proof by induction − Here we start with a specific instance of a truth and then generalize it to all possible values which are part of the truth. The approach is to take a case of verified truth, then prove it is also true for the next case for the same given condition. For example all positive numbers of the form 2n-1 are odd. We prove it for a certain value of n, then prove it for the next value of n. This establishes the statement as generally true by proof of induction. Proof by contraposition − This proof is based on the condition If Not A implies Not B then A implies B. A simple example is if square of n is even then n must be even. Because if square on n is not even then n is not even. Proof by contraposition − This proof is based on the condition If Not A implies Not B then A implies B. A simple example is if square of n is even then n must be even. Because if square on n is not even then n is not even. Proof by exhaustion − This is similar to direct proof but it is established by visiting each case separately and proving each of them. An example of such proof is the four color theorem. Proof by exhaustion − This is similar to direct proof but it is established by visiting each case separately and proving each of them. An example of such proof is the four color theorem. 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": 2420, "s": 2327, "text": "Here, we will understand what is data structure with regards to Python programming language." }, { "code": null, "e": 2749, "s": 2420, "text": "Data structures are fundamental concepts of computer science which helps is writing efficient programs in any language. Python is a high-level, interpreted, interactive and object-oriented scripting language using which we can study the fundamentals of data structure in a simpler way as compared to other programming languages." }, { "code": null, "e": 3008, "s": 2749, "text": "In this chapter we are going to study a short overview of some frequently used data structures in general and how they are related to some specific python data types. There are also some data structures specific to python which is listed as another category." }, { "code": null, "e": 3199, "s": 3008, "text": "The various data structures in computer science are divided broadly into two categories shown below. We will discuss about each of the below data structures in detail in subsequent chapters." }, { "code": null, "e": 3283, "s": 3199, "text": "These are the data structures which store the data elements in a sequential manner." }, { "code": null, "e": 3382, "s": 3283, "text": "Array − It is a sequential arrangement of data elements paired with the index of the data element." }, { "code": null, "e": 3481, "s": 3382, "text": "Array − It is a sequential arrangement of data elements paired with the index of the data element." }, { "code": null, "e": 3583, "s": 3481, "text": "Linked List − Each data element contains a link to another element along with the data present in it." }, { "code": null, "e": 3685, "s": 3583, "text": "Linked List − Each data element contains a link to another element along with the data present in it." }, { "code": null, "e": 3819, "s": 3685, "text": "Stack − It is a data structure which follows only to specific order of operation. LIFO(last in First Out) or FILO(First in Last Out)." }, { "code": null, "e": 3953, "s": 3819, "text": "Stack − It is a data structure which follows only to specific order of operation. LIFO(last in First Out) or FILO(First in Last Out)." }, { "code": null, "e": 4045, "s": 3953, "text": "Queue − It is similar to Stack but the order of operation is only FIFO(First In First Out)." }, { "code": null, "e": 4137, "s": 4045, "text": "Queue − It is similar to Stack but the order of operation is only FIFO(First In First Out)." }, { "code": null, "e": 4243, "s": 4137, "text": "Matrix − It is two dimensional data structure in which the data element is referred by a pair of indices." }, { "code": null, "e": 4349, "s": 4243, "text": "Matrix − It is two dimensional data structure in which the data element is referred by a pair of indices." }, { "code": null, "e": 4547, "s": 4349, "text": "These are the data structures in which there is no sequential linking of data elements. Any pair or group of data elements can be linked to each other and can be accessed without a strict sequence." }, { "code": null, "e": 4692, "s": 4547, "text": "Binary Tree − It is a data structure where each data element can be connected to maximum two other data elements and it starts with a root node." }, { "code": null, "e": 4837, "s": 4692, "text": "Binary Tree − It is a data structure where each data element can be connected to maximum two other data elements and it starts with a root node." }, { "code": null, "e": 5020, "s": 4837, "text": "Heap − It is a special case of Tree data structure where the data in the parent node is either strictly greater than/ equal to the child nodes or strictly less than it’s child nodes." }, { "code": null, "e": 5203, "s": 5020, "text": "Heap − It is a special case of Tree data structure where the data in the parent node is either strictly greater than/ equal to the child nodes or strictly less than it’s child nodes." }, { "code": null, "e": 5383, "s": 5203, "text": "Hash Table − It is a data structure which is made of arrays associated with each other using a hash function. It retrieves values using keys rather than index from a data element." }, { "code": null, "e": 5563, "s": 5383, "text": "Hash Table − It is a data structure which is made of arrays associated with each other using a hash function. It retrieves values using keys rather than index from a data element." }, { "code": null, "e": 5681, "s": 5563, "text": "Graph − It is an arrangement of vertices and nodes where some of the nodes are connected to each other through links." }, { "code": null, "e": 5799, "s": 5681, "text": "Graph − It is an arrangement of vertices and nodes where some of the nodes are connected to each other through links." }, { "code": null, "e": 5967, "s": 5799, "text": "These data structures are specific to python language and they give greater flexibility in storing different types of data and faster processing in python environment." }, { "code": null, "e": 6131, "s": 5967, "text": "List − It is similar to array with the exception that the data elements can be of different data types. You can have both numeric and string data in a python list." }, { "code": null, "e": 6295, "s": 6131, "text": "List − It is similar to array with the exception that the data elements can be of different data types. You can have both numeric and string data in a python list." }, { "code": null, "e": 6430, "s": 6295, "text": "Tuple − Tuples are similar to lists but they are immutable which means the values in a tuple cannot be modified they can only be read." }, { "code": null, "e": 6565, "s": 6430, "text": "Tuple − Tuples are similar to lists but they are immutable which means the values in a tuple cannot be modified they can only be read." }, { "code": null, "e": 6640, "s": 6565, "text": "Dictionary − The dictionary contains Key-value pairs as its data elements." }, { "code": null, "e": 6715, "s": 6640, "text": "Dictionary − The dictionary contains Key-value pairs as its data elements." }, { "code": null, "e": 6840, "s": 6715, "text": "In the next chapters we are going to learn the details of how each of these data structures can be implemented using Python." }, { "code": null, "e": 6976, "s": 6840, "text": "Python is available on a wide variety of platforms including Linux and Mac OS X. Let's understand how to set up our Python environment." }, { "code": null, "e": 7088, "s": 6976, "text": "Open a terminal window and type \"python\" to find out if it is already installed and which version is installed." }, { "code": null, "e": 7150, "s": 7088, "text": "Unix (Solaris, Linux, FreeBSD, AIX, HP/UX, SunOS, IRIX, etc.)" }, { "code": null, "e": 7165, "s": 7150, "text": "Win 9x/NT/2000" }, { "code": null, "e": 7193, "s": 7165, "text": "Macintosh (Intel, PPC, 68K)" }, { "code": null, "e": 7198, "s": 7193, "text": "OS/2" }, { "code": null, "e": 7222, "s": 7198, "text": "DOS (multiple versions)" }, { "code": null, "e": 7229, "s": 7222, "text": "PalmOS" }, { "code": null, "e": 7249, "s": 7229, "text": "Nokia mobile phones" }, { "code": null, "e": 7260, "s": 7249, "text": "Windows CE" }, { "code": null, "e": 7274, "s": 7260, "text": "Acorn/RISC OS" }, { "code": null, "e": 7279, "s": 7274, "text": "BeOS" }, { "code": null, "e": 7285, "s": 7279, "text": "Amiga" }, { "code": null, "e": 7297, "s": 7285, "text": "VMS/OpenVMS" }, { "code": null, "e": 7301, "s": 7297, "text": "QNX" }, { "code": null, "e": 7309, "s": 7301, "text": "VxWorks" }, { "code": null, "e": 7315, "s": 7309, "text": "Psion" }, { "code": null, "e": 7381, "s": 7315, "text": "Python has also been ported to the Java and .NET virtual machines" }, { "code": null, "e": 7525, "s": 7381, "text": "The most up-to-date and current source code, binaries, documentation, news, etc., is available on the official website of Python www.python.org" }, { "code": null, "e": 7685, "s": 7525, "text": "You can download Python documentation from this website given herewith,www.python.org/doc. The documentation is available in HTML, PDF, and PostScript formats." }, { "code": null, "e": 7842, "s": 7685, "text": "Python distribution is available for a wide variety of platforms. You need to download only the binary code applicable for your platform and install Python." }, { "code": null, "e": 8076, "s": 7842, "text": "If the binary code for your platform is not available, you need a C compiler to compile the source code manually. Compiling the source code offers more flexibility in terms of choice of features that you require in your installation." }, { "code": null, "e": 8145, "s": 8076, "text": "Here is a quick overview of installing Python on various platforms −" }, { "code": null, "e": 8212, "s": 8145, "text": "Here are the simple steps to install Python on Unix/Linux machine." }, { "code": null, "e": 8267, "s": 8212, "text": "Open a Web browser and go to www.python.org/downloads." }, { "code": null, "e": 8322, "s": 8267, "text": "Open a Web browser and go to www.python.org/downloads." }, { "code": null, "e": 8395, "s": 8322, "text": "Follow the link to download zipped source code available for Unix/Linux." }, { "code": null, "e": 8468, "s": 8395, "text": "Follow the link to download zipped source code available for Unix/Linux." }, { "code": null, "e": 8496, "s": 8468, "text": "Download and extract files." }, { "code": null, "e": 8524, "s": 8496, "text": "Download and extract files." }, { "code": null, "e": 8594, "s": 8524, "text": "Editing the Modules/Setup file if you want to customize some options." }, { "code": null, "e": 8664, "s": 8594, "text": "Editing the Modules/Setup file if you want to customize some options." }, { "code": null, "e": 8687, "s": 8664, "text": "run ./configure script" }, { "code": null, "e": 8710, "s": 8687, "text": "run ./configure script" }, { "code": null, "e": 8715, "s": 8710, "text": "make" }, { "code": null, "e": 8720, "s": 8715, "text": "make" }, { "code": null, "e": 8733, "s": 8720, "text": "make install" }, { "code": null, "e": 8746, "s": 8733, "text": "make install" }, { "code": null, "e": 8883, "s": 8746, "text": "This installs Python at standard location /usr/local/bin and its libraries at /usr/local/lib/pythonXX where XX is the version of Python." }, { "code": null, "e": 8940, "s": 8883, "text": "Here are the steps to install Python on Windows machine." }, { "code": null, "e": 8995, "s": 8940, "text": "Open a Web browser and go to www.python.org/downloads." }, { "code": null, "e": 9050, "s": 8995, "text": "Open a Web browser and go to www.python.org/downloads." }, { "code": null, "e": 9158, "s": 9050, "text": "Follow the link for the Windows installer python-XYZ.msi file where XYZ is the version you need to install." }, { "code": null, "e": 9266, "s": 9158, "text": "Follow the link for the Windows installer python-XYZ.msi file where XYZ is the version you need to install." }, { "code": null, "e": 9465, "s": 9266, "text": "To use this installer python-XYZ.msi, the Windows system must support Microsoft Installer 2.0. Save the installer file to your local machine and then run it to find out if your machine supports MSI." }, { "code": null, "e": 9664, "s": 9465, "text": "To use this installer python-XYZ.msi, the Windows system must support Microsoft Installer 2.0. Save the installer file to your local machine and then run it to find out if your machine supports MSI." }, { "code": null, "e": 9848, "s": 9664, "text": "Run the downloaded file. This brings up the Python install wizard, which is really easy to use. Just accept the default settings, wait until the install is finished, and you are done." }, { "code": null, "e": 10032, "s": 9848, "text": "Run the downloaded file. This brings up the Python install wizard, which is really easy to use. Just accept the default settings, wait until the install is finished, and you are done." }, { "code": null, "e": 10336, "s": 10032, "text": "Recent Macs come with Python installed, but it may be several years out of date. See www.python.org/download/mac/ for instructions on getting the current version along with extra tools to support development on the Mac. For older Mac OS's before Mac OS X 10.3 (released in 2003), MacPython is available." }, { "code": null, "e": 10543, "s": 10336, "text": "Jack Jansen maintains it and you can have full access to the entire documentation at his website − http://www.cwi.nl/~jack/macpython.html. You can find complete installation details for Mac OS installation." }, { "code": null, "e": 10715, "s": 10543, "text": "Programs and other executable files can be in many directories, so operating systems provide a search path that lists the directories that the OS searches for executables." }, { "code": null, "e": 10908, "s": 10715, "text": "The path is stored in an environment variable, which is a named string maintained by the operating system. This variable contains information available to the command shell and other programs." }, { "code": null, "e": 11012, "s": 10908, "text": "The path variable is named as PATH in Unix or Path in Windows (Unix is case sensitive; Windows is not)." }, { "code": null, "e": 11175, "s": 11012, "text": "In Mac OS, the installer handles the path details. To invoke the Python interpreter from any particular directory, you must add the Python directory to your path." }, { "code": null, "e": 11250, "s": 11175, "text": "To add the Python directory to the path for a particular session in Unix −" }, { "code": null, "e": 11333, "s": 11250, "text": "In the csh shell − type setenv PATH \"$PATH:/usr/local/bin/python\" and press Enter." }, { "code": null, "e": 11416, "s": 11333, "text": "In the csh shell − type setenv PATH \"$PATH:/usr/local/bin/python\" and press Enter." }, { "code": null, "e": 11507, "s": 11416, "text": "In the bash shell (Linux) − type export ATH=\"$PATH:/usr/local/bin/python\" and press Enter." }, { "code": null, "e": 11598, "s": 11507, "text": "In the bash shell (Linux) − type export ATH=\"$PATH:/usr/local/bin/python\" and press Enter." }, { "code": null, "e": 11680, "s": 11598, "text": "In the sh or ksh shell − type PATH=\"$PATH:/usr/local/bin/python\" and press Enter." }, { "code": null, "e": 11762, "s": 11680, "text": "In the sh or ksh shell − type PATH=\"$PATH:/usr/local/bin/python\" and press Enter." }, { "code": null, "e": 11827, "s": 11762, "text": "Note − /usr/local/bin/python is the path of the Python directory" }, { "code": null, "e": 11892, "s": 11827, "text": "Note − /usr/local/bin/python is the path of the Python directory" }, { "code": null, "e": 11970, "s": 11892, "text": "To add the Python directory to the path for a particular session in Windows −" }, { "code": null, "e": 12038, "s": 11970, "text": "At the command prompt − type path %path%;C:\\Python and press Enter." }, { "code": null, "e": 12106, "s": 12038, "text": "At the command prompt − type path %path%;C:\\Python and press Enter." }, { "code": null, "e": 12159, "s": 12106, "text": "Note − C:\\Python is the path of the Python directory" }, { "code": null, "e": 12212, "s": 12159, "text": "Note − C:\\Python is the path of the Python directory" }, { "code": null, "e": 12290, "s": 12212, "text": "Here are important environment variables, which can be recognized by Python −" }, { "code": null, "e": 12301, "s": 12290, "text": "PYTHONPATH" }, { "code": null, "e": 12594, "s": 12301, "text": "It has a role similar to PATH. This variable tells the Python interpreter where to locate the module files imported into a program. It should include the Python source library directory and the directories containing Python source code. PYTHONPATH is sometimes preset by the Python installer." }, { "code": null, "e": 12608, "s": 12594, "text": "PYTHONSTARTUP" }, { "code": null, "e": 12842, "s": 12608, "text": "It contains the path of an initialization file containing Python source code. It is executed every time you start the interpreter. It is named as .pythonrc.py in Unix and it contains commands that load utilities or modify PYTHONPATH." }, { "code": null, "e": 12855, "s": 12842, "text": "PYTHONCASEOK" }, { "code": null, "e": 13008, "s": 12855, "text": "It is used in Windows to instruct Python to find the first case-insensitive match in an import statement. Set this variable to any value to activate it." }, { "code": null, "e": 13019, "s": 13008, "text": "PYTHONHOME" }, { "code": null, "e": 13171, "s": 13019, "text": "It is an alternative module search path. It is usually embedded in the PYTHONSTARTUP or PYTHONPATH directories to make switching module libraries easy." }, { "code": null, "e": 13242, "s": 13171, "text": "There are three different ways to start Python, which are as follows −" }, { "code": null, "e": 13361, "s": 13242, "text": "You can start Python from Unix, DOS, or any other system that provides you a command-line interpreter or shell window." }, { "code": null, "e": 13480, "s": 13361, "text": "You can start Python from Unix, DOS, or any other system that provides you a command-line interpreter or shell window." }, { "code": null, "e": 13511, "s": 13480, "text": "Enter python the command line." }, { "code": null, "e": 13542, "s": 13511, "text": "Enter python the command line." }, { "code": null, "e": 13598, "s": 13542, "text": "Start coding right away in the interactive interpreter." }, { "code": null, "e": 13654, "s": 13598, "text": "Start coding right away in the interactive interpreter." }, { "code": null, "e": 13728, "s": 13654, "text": "$python # Unix/Linux\nor\npython% # Unix/Linux\nor\nC:> python # Windows/DOS\n" }, { "code": null, "e": 13818, "s": 13728, "text": "Here is the list of all the available command line options, which is as mentioned below −" }, { "code": null, "e": 13821, "s": 13818, "text": "-d" }, { "code": null, "e": 13847, "s": 13821, "text": "It provides debug output." }, { "code": null, "e": 13850, "s": 13847, "text": "-O" }, { "code": null, "e": 13909, "s": 13850, "text": "It generates optimized bytecode (resulting in .pyo files)." }, { "code": null, "e": 13912, "s": 13909, "text": "-S" }, { "code": null, "e": 13972, "s": 13912, "text": "Do not run import site to look for Python paths on startup." }, { "code": null, "e": 13975, "s": 13972, "text": "-v" }, { "code": null, "e": 14029, "s": 13975, "text": "verbose output (detailed trace on import statements)." }, { "code": null, "e": 14032, "s": 14029, "text": "-X" }, { "code": null, "e": 14128, "s": 14032, "text": "disable class-based built-in exceptions (just use strings); obsolete starting with version 1.6." }, { "code": null, "e": 14135, "s": 14128, "text": "-c cmd" }, { "code": null, "e": 14175, "s": 14135, "text": "run Python script sent in as cmd string" }, { "code": null, "e": 14180, "s": 14175, "text": "file" }, { "code": null, "e": 14214, "s": 14180, "text": "run Python script from given file" }, { "code": null, "e": 14333, "s": 14214, "text": "A Python script can be executed at command line by invoking the interpreter on your application, as in the following −" }, { "code": null, "e": 14442, "s": 14333, "text": "$python script.py # Unix/Linux\n\nor\n\npython% script.py # Unix/Linux\n\nor \n\nC: >python script.py # Windows/DOS\n" }, { "code": null, "e": 14500, "s": 14442, "text": "Note − Be sure the file permission mode allows execution." }, { "code": null, "e": 14558, "s": 14500, "text": "Note − Be sure the file permission mode allows execution." }, { "code": null, "e": 14703, "s": 14558, "text": "You can run Python from a Graphical User Interface (GUI) environment as well, if you have a GUI application on your system that supports Python." }, { "code": null, "e": 14754, "s": 14703, "text": "Unix − IDLE is the very first Unix IDE for Python." }, { "code": null, "e": 14805, "s": 14754, "text": "Unix − IDLE is the very first Unix IDE for Python." }, { "code": null, "e": 14893, "s": 14805, "text": "Windows − PythonWin is the first Windows interface for Python and is an IDE with a GUI." }, { "code": null, "e": 14981, "s": 14893, "text": "Windows − PythonWin is the first Windows interface for Python and is an IDE with a GUI." }, { "code": null, "e": 15138, "s": 14981, "text": "Macintosh − The Macintosh version of Python along with the IDLE IDE is available from the main website, downloadable as either MacBinary or BinHex'd files." }, { "code": null, "e": 15295, "s": 15138, "text": "Macintosh − The Macintosh version of Python along with the IDLE IDE is available from the main website, downloadable as either MacBinary or BinHex'd files." }, { "code": null, "e": 15478, "s": 15295, "text": "If you are not able to set up the environment properly, then you can take help from your system admin. Make sure the Python environment is properly set up and working perfectly fine." }, { "code": null, "e": 15608, "s": 15478, "text": "Note − All the examples given in subsequent chapters are executed with Python 2.4.3 version available on CentOS flavor of Linux.\n" }, { "code": null, "e": 15737, "s": 15608, "text": "Note − All the examples given in subsequent chapters are executed with Python 2.4.3 version available on CentOS flavor of Linux." }, { "code": null, "e": 15959, "s": 15737, "text": "We already have set up Python Programming environment online, so that you can execute all the available examples online at the same time when you are learning theory. Feel free to modify any example and execute it online." }, { "code": null, "e": 16225, "s": 15959, "text": "Array is a container which can hold a fix number of items and these items should be of the same type. Most of the data structures make use of arrays to implement their algorithms. Following are the important terms to understand the concept of Array are as follows −" }, { "code": null, "e": 16286, "s": 16225, "text": "Element − Each item stored in an array is called an element." }, { "code": null, "e": 16347, "s": 16286, "text": "Element − Each item stored in an array is called an element." }, { "code": null, "e": 16457, "s": 16347, "text": "Index − Each location of an element in an array has a numerical index, which is used to identify the element." }, { "code": null, "e": 16567, "s": 16457, "text": "Index − Each location of an element in an array has a numerical index, which is used to identify the element." }, { "code": null, "e": 16656, "s": 16567, "text": "Arrays can be declared in various ways in different languages. Below is an illustration." }, { "code": null, "e": 16741, "s": 16656, "text": "As per the above illustration, following are the important points to be considered −" }, { "code": null, "e": 16762, "s": 16741, "text": "Index starts with 0." }, { "code": null, "e": 16783, "s": 16762, "text": "Index starts with 0." }, { "code": null, "e": 16841, "s": 16783, "text": "Array length is 10, which means it can store 10 elements." }, { "code": null, "e": 16899, "s": 16841, "text": "Array length is 10, which means it can store 10 elements." }, { "code": null, "e": 16997, "s": 16899, "text": "Each element can be accessed via its index. For example, we can fetch an element at index 6 as 9." }, { "code": null, "e": 17095, "s": 16997, "text": "Each element can be accessed via its index. For example, we can fetch an element at index 6 as 9." }, { "code": null, "e": 17160, "s": 17095, "text": "The basic operations supported by an array are as stated below −" }, { "code": null, "e": 17212, "s": 17160, "text": "Traverse − print all the array elements one by one." }, { "code": null, "e": 17264, "s": 17212, "text": "Traverse − print all the array elements one by one." }, { "code": null, "e": 17312, "s": 17264, "text": "Insertion − Adds an element at the given index." }, { "code": null, "e": 17360, "s": 17312, "text": "Insertion − Adds an element at the given index." }, { "code": null, "e": 17410, "s": 17360, "text": "Deletion − Deletes an element at the given index." }, { "code": null, "e": 17460, "s": 17410, "text": "Deletion − Deletes an element at the given index." }, { "code": null, "e": 17528, "s": 17460, "text": "Search − Searches an element using the given index or by the value." }, { "code": null, "e": 17596, "s": 17528, "text": "Search − Searches an element using the given index or by the value." }, { "code": null, "e": 17644, "s": 17596, "text": "Update − Updates an element at the given index." }, { "code": null, "e": 17692, "s": 17644, "text": "Update − Updates an element at the given index." }, { "code": null, "e": 17813, "s": 17692, "text": "Array is created in Python by importing array module to the python program. Then, the array is declared as shown below −" }, { "code": null, "e": 17879, "s": 17813, "text": "from array import *\n\narrayName = array(typecode, [Initializers])\n" }, { "code": null, "e": 18009, "s": 17879, "text": "Typecode are the codes that are used to define the type of value the array will hold. Some common typecodes used are as follows −" }, { "code": null, "e": 18097, "s": 18009, "text": "Before looking at various array operations lets create and print an array using python." }, { "code": null, "e": 18143, "s": 18097, "text": "The below code creates an array named array1." }, { "code": null, "e": 18232, "s": 18143, "text": "from array import *\n\narray1 = array('i', [10,20,30,40,50])\n\nfor x in array1:\n print(x)" }, { "code": null, "e": 18314, "s": 18232, "text": "When we compile and execute the above program, it produces the following result −" }, { "code": null, "e": 18330, "s": 18314, "text": "10\n20\n30\n40\n50\n" }, { "code": null, "e": 18454, "s": 18330, "text": "We can access each element of an array using the index of the element. The below code shows how to access an array element." }, { "code": null, "e": 18551, "s": 18454, "text": "from array import *\n\narray1 = array('i', [10,20,30,40,50])\n\nprint (array1[0])\n\nprint (array1[2])" }, { "code": null, "e": 18689, "s": 18551, "text": "When we compile and execute the above program, it produces the following result, which shows the element is inserted at index position 1." }, { "code": null, "e": 18696, "s": 18689, "text": "10\n30\n" }, { "code": null, "e": 18872, "s": 18696, "text": "Insert operation is to insert one or more data elements into an array. Based on the requirement, a new element can be added at the beginning, end, or any given index of array." }, { "code": null, "e": 18970, "s": 18872, "text": "Here, we add a data element at the middle of the array using the python in-built insert() method." }, { "code": null, "e": 19080, "s": 18970, "text": "from array import *\n\narray1 = array('i', [10,20,30,40,50])\n\narray1.insert(1,60)\n\nfor x in array1:\n print(x)" }, { "code": null, "e": 19217, "s": 19080, "text": "When we compile and execute the above program, it produces the following result which shows the element is inserted at index position 1." }, { "code": null, "e": 19236, "s": 19217, "text": "10\n60\n20\n30\n40\n50\n" }, { "code": null, "e": 19343, "s": 19236, "text": "Deletion refers to removing an existing element from the array and re-organizing all elements of an array." }, { "code": null, "e": 19444, "s": 19343, "text": "Here, we remove a data element at the middle of the array using the python in-built remove() method." }, { "code": null, "e": 19552, "s": 19444, "text": "from array import *\n\narray1 = array('i', [10,20,30,40,50])\n\narray1.remove(40)\n\nfor x in array1:\n print(x)" }, { "code": null, "e": 19683, "s": 19552, "text": "When we compile and execute the above program, it produces the following result which shows the element is removed form the array." }, { "code": null, "e": 19696, "s": 19683, "text": "10\n20\n30\n50\n" }, { "code": null, "e": 19775, "s": 19696, "text": "You can perform a search for an array element based on its value or its index." }, { "code": null, "e": 19848, "s": 19775, "text": "Here, we search a data element using the python in-built index() method." }, { "code": null, "e": 19933, "s": 19848, "text": "from array import *\n\narray1 = array('i', [10,20,30,40,50])\n\nprint (array1.index(40))" }, { "code": null, "e": 20127, "s": 19933, "text": "When we compile and execute the above program, it produces the following result which shows the index of the element. If the value is not present in the array then th eprogram returns an error." }, { "code": null, "e": 20130, "s": 20127, "text": "3\n" }, { "code": null, "e": 20219, "s": 20130, "text": "Update operation refers to updating an existing element from the array at a given index." }, { "code": null, "e": 20296, "s": 20219, "text": "Here, we simply reassign a new value to the desired index we want to update." }, { "code": null, "e": 20401, "s": 20296, "text": "from array import *\n\narray1 = array('i', [10,20,30,40,50])\n\narray1[2] = 80\n\nfor x in array1:\n print(x)" }, { "code": null, "e": 20532, "s": 20401, "text": "When we compile and execute the above program, it produces the following result which shows the new value at the index position 2." }, { "code": null, "e": 20548, "s": 20532, "text": "10\n20\n80\n40\n50\n" }, { "code": null, "e": 20779, "s": 20548, "text": "The list is a most versatile datatype available in Python which can be written as a list of comma-separated values (items) between square brackets. Important thing about a list is that items in a list need not be of the same type." }, { "code": null, "e": 20877, "s": 20779, "text": "Creating a list is as simple as putting different comma-separated values between square brackets." }, { "code": null, "e": 20977, "s": 20877, "text": "list1 = ['physics', 'chemistry', 1997, 2000]\nlist2 = [1, 2, 3, 4, 5 ]\nlist3 = [\"a\", \"b\", \"c\", \"d\"]\n" }, { "code": null, "e": 21078, "s": 20977, "text": "Similar to string indices, list indices start at 0, and lists can be sliced, concatenated and so on." }, { "code": null, "e": 21214, "s": 21078, "text": "To access values in lists, use the square brackets for slicing along with the index or indices to obtain value available at that index." }, { "code": null, "e": 21371, "s": 21214, "text": "#!/usr/bin/python\n\nlist1 = ['physics', 'chemistry', 1997, 2000]\nlist2 = [1, 2, 3, 4, 5, 6, 7 ]\nprint \"list1[0]: \", list1[0]\nprint \"list2[1:5]: \", list2[1:5]" }, { "code": null, "e": 21439, "s": 21371, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 21485, "s": 21439, "text": "list1[0]: physics\nlist2[1:5]: [2, 3, 4, 5]\n" }, { "code": null, "e": 21671, "s": 21485, "text": "You can update single or multiple elements of lists by giving the slice on the left-hand side of the assignment operator, and you can add to elements in a list with the append() method." }, { "code": null, "e": 21857, "s": 21671, "text": "#!/usr/bin/python\n\nlist = ['physics', 'chemistry', 1997, 2000]\nprint \"Value available at index 2 : \"\nprint list[2]\nlist[2] = 2001\nprint \"New value available at index 2 : \"\nprint list[2]" }, { "code": null, "e": 21916, "s": 21857, "text": "Note − append() method is discussed in subsequent section." }, { "code": null, "e": 21975, "s": 21916, "text": "Note − append() method is discussed in subsequent section." }, { "code": null, "e": 22043, "s": 21975, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 22116, "s": 22043, "text": "Value available at index 2 :\n1997\nNew value available at index 2 :\n2001\n" }, { "code": null, "e": 22276, "s": 22116, "text": "To remove a list element, you can use either the del statement if you know exactly which element(s) you are deleting or the remove() method if you do not know." }, { "code": null, "e": 22420, "s": 22276, "text": "#!/usr/bin/python\n\nlist1 = ['physics', 'chemistry', 1997, 2000]\nprint list1\ndel list1[2]\nprint \"After deleting value at index 2 : \"\nprint list1" }, { "code": null, "e": 22484, "s": 22420, "text": "When the above code is executed, it produces following result −" }, { "code": null, "e": 22587, "s": 22484, "text": "['physics', 'chemistry', 1997, 2000]\nAfter deleting value at index 2 :\n['physics', 'chemistry', 2000]\n" }, { "code": null, "e": 22646, "s": 22587, "text": "Note − remove() method is discussed in subsequent section." }, { "code": null, "e": 22705, "s": 22646, "text": "Note − remove() method is discussed in subsequent section." }, { "code": null, "e": 22864, "s": 22705, "text": "Lists respond to the + and * operators much like strings; they mean concatenation and repetition here too, except that the result is a new list, not a string." }, { "code": null, "e": 22970, "s": 22864, "text": "In fact, lists respond to all of the general sequence operations we used on strings in the prior chapter." }, { "code": null, "e": 23211, "s": 22970, "text": "A tuple is a sequence of immutable Python objects. Tuples are sequences, just like lists. The differences between tuples and lists are, the tuples cannot be changed unlike lists and tuples use parentheses, whereas lists use square brackets." }, { "code": null, "e": 23364, "s": 23211, "text": "Creating a tuple is as simple as putting different comma-separated values. Optionally you can put these comma-separated values between parentheses also." }, { "code": null, "e": 23462, "s": 23364, "text": "tup1 = ('physics', 'chemistry', 1997, 2000);\ntup2 = (1, 2, 3, 4, 5 );\ntup3 = \"a\", \"b\", \"c\", \"d\";\n" }, { "code": null, "e": 23529, "s": 23462, "text": "The empty tuple is written as two parentheses containing nothing −" }, { "code": null, "e": 23541, "s": 23529, "text": "tup1 = ();\n" }, { "code": null, "e": 23651, "s": 23541, "text": "To write a tuple containing a single value you have to include a comma, even though there is only one value −" }, { "code": null, "e": 23666, "s": 23651, "text": "tup1 = (50,);\n" }, { "code": null, "e": 23762, "s": 23666, "text": "Like string indices, tuple indices start at 0, and they can be sliced, concatenated, and so on." }, { "code": null, "e": 23898, "s": 23762, "text": "To access values in tuple, use the square brackets for slicing along with the index or indices to obtain value available at that index." }, { "code": null, "e": 24053, "s": 23898, "text": "#!/usr/bin/python\n\ntup1 = ('physics', 'chemistry', 1997, 2000);\ntup2 = (1, 2, 3, 4, 5, 6, 7 );\nprint \"tup1[0]: \", tup1[0];\nprint \"tup2[1:5]: \", tup2[1:5];" }, { "code": null, "e": 24122, "s": 24053, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 24166, "s": 24122, "text": "tup1[0]: physics\ntup2[1:5]: [2, 3, 4, 5]\n" }, { "code": null, "e": 24367, "s": 24166, "text": "Tuples are immutable which means you cannot update or change the values of tuple elements. You are able to take portions of existing tuples to create new tuples as the following example demonstrates −" }, { "code": null, "e": 24564, "s": 24367, "text": "#!/usr/bin/python\n\ntup1 = (12, 34.56);\ntup2 = ('abc', 'xyz');\n\n# Following action is not valid for tuples\n# tup1[0] = 100;\n\n# So let's create a new tuple as follows\ntup3 = tup1 + tup2;\nprint tup3;" }, { "code": null, "e": 24632, "s": 24564, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 24659, "s": 24632, "text": "(12, 34.56, 'abc', 'xyz')\n" }, { "code": null, "e": 24821, "s": 24659, "text": "Removing individual tuple elements is not possible. There is, of course, nothing wrong with putting together another tuple with the undesired elements discarded." }, { "code": null, "e": 24887, "s": 24821, "text": "To explicitly remove an entire tuple, just use the del statement." }, { "code": null, "e": 25012, "s": 24887, "text": "#!/usr/bin/python\n\ntup = ('physics', 'chemistry', 1997, 2000);\nprint tup;\ndel tup;\nprint \"After deleting tup : \";\nprint tup;" }, { "code": null, "e": 25100, "s": 25012, "text": "Note − an exception raised, this is because after del tup tuple does not exist anymore." }, { "code": null, "e": 25188, "s": 25100, "text": "Note − an exception raised, this is because after del tup tuple does not exist anymore." }, { "code": null, "e": 25225, "s": 25188, "text": "This produces the following result −" }, { "code": null, "e": 25412, "s": 25225, "text": "('physics', 'chemistry', 1997, 2000)\nAfter deleting tup :\nTraceback (most recent call last):\n File \"test.py\", line 9, in <module>\n print tup;\nNameError: name 'tup' is not defined\n" }, { "code": null, "e": 25573, "s": 25412, "text": "Tuples respond to the + and * operators much like strings; they mean concatenation and repetition here too, except that the result is a new tuple, not a string." }, { "code": null, "e": 25680, "s": 25573, "text": "In fact, tuples respond to all of the general sequence operations we used on strings in the prior chapter." }, { "code": null, "e": 25924, "s": 25680, "text": "In Dictionary each key is separated from its value by a colon (:), the items are separated by commas, and the whole thing is enclosed in curly braces. An empty dictionary without any items is written with just two curly braces, like this − {}." }, { "code": null, "e": 26116, "s": 25924, "text": "Keys are unique within a dictionary while values may not be. The values of a dictionary can be of any type, but the keys must be of an immutable data type such as strings, numbers, or tuples." }, { "code": null, "e": 26228, "s": 26116, "text": "To access dictionary elements, you can use the familiar square brackets along with the key to obtain its value." }, { "code": null, "e": 26261, "s": 26228, "text": "A simple example is as follows −" }, { "code": null, "e": 26404, "s": 26261, "text": "#!/usr/bin/python\n\ndict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}\nprint \"dict['Name']: \", dict['Name']\nprint \"dict['Age']: \", dict['Age']" }, { "code": null, "e": 26473, "s": 26404, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 26510, "s": 26473, "text": "dict['Name']: Zara\ndict['Age']: 7\n" }, { "code": null, "e": 26624, "s": 26510, "text": "If we attempt to access a data item with a key, which is not part of the dictionary, we get an error as follows −" }, { "code": null, "e": 26734, "s": 26624, "text": "#!/usr/bin/python\n\ndict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}\nprint \"dict['Alice']: \", dict['Alice']" }, { "code": null, "e": 26803, "s": 26734, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 26957, "s": 26803, "text": "dict['Alice']:\nTraceback (most recent call last):\n File \"test.py\", line 4, in <module>\n print \"dict['Alice']: \", dict['Alice'];\nKeyError: 'Alice'\n" }, { "code": null, "e": 27126, "s": 26957, "text": "You can update a dictionary by adding a new entry or a key-value pair, modifying an existing entry, or deleting an existing entry as shown below in the simple example −" }, { "code": null, "e": 27362, "s": 27126, "text": "#!/usr/bin/python\n\ndict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}\ndict['Age'] = 8; # update existing entry\ndict['School'] = \"DPS School\"; # Add new entry\n\nprint \"dict['Age']: \", dict['Age']\nprint \"dict['School']: \", dict['School']" }, { "code": null, "e": 27430, "s": 27362, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 27475, "s": 27430, "text": "dict['Age']: 8\ndict['School']: DPS School\n" }, { "code": null, "e": 27635, "s": 27475, "text": "You can either remove individual dictionary elements or clear the entire contents of a dictionary. You can also delete entire dictionary in a single operation." }, { "code": null, "e": 27747, "s": 27635, "text": "To explicitly remove an entire dictionary, just use the del statement. A simple example is as mentioned below −" }, { "code": null, "e": 28036, "s": 27747, "text": "#!/usr/bin/python\n\ndict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}\ndel dict['Name']; # remove entry with key 'Name'\ndict.clear(); # remove all entries in dict\ndel dict ; # delete entire dictionary\n\nprint \"dict['Age']: \", dict['Age']\nprint \"dict['School']: \", dict['School']" }, { "code": null, "e": 28130, "s": 28036, "text": "Note −that an exception is raised because after del dict dictionary does not exist any more −" }, { "code": null, "e": 28224, "s": 28130, "text": "Note −that an exception is raised because after del dict dictionary does not exist any more −" }, { "code": null, "e": 28261, "s": 28224, "text": "This produces the following result −" }, { "code": null, "e": 28435, "s": 28261, "text": "dict['Age']:\nTraceback (most recent call last):\n File \"test.py\", line 8, in <module>\n print \"dict['Age']: \", dict['Age'];\nTypeError: 'type' object is unsubscriptable\n" }, { "code": null, "e": 28491, "s": 28435, "text": "Note − del() method is discussed in subsequent section." }, { "code": null, "e": 28547, "s": 28491, "text": "Note − del() method is discussed in subsequent section." }, { "code": null, "e": 28717, "s": 28547, "text": "Dictionary values have no restrictions. They can be any arbitrary Python object, either standard objects or user-defined objects. However, same is not true for the keys." }, { "code": null, "e": 28784, "s": 28717, "text": "There are two important points to remember about dictionary keys −" }, { "code": null, "e": 28943, "s": 28784, "text": "More than one entry per key not allowed. Which means no duplicate key is allowed. When duplicate keys encountered during assignment, the last assignment wins." }, { "code": null, "e": 29102, "s": 28943, "text": "More than one entry per key not allowed. Which means no duplicate key is allowed. When duplicate keys encountered during assignment, the last assignment wins." }, { "code": null, "e": 29209, "s": 29102, "text": "#!/usr/bin/python\n\ndict = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'}\nprint \"dict['Name']: \", dict['Name']" }, { "code": null, "e": 29278, "s": 29209, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 29300, "s": 29278, "text": "dict['Name']: Manni\n" }, { "code": null, "e": 29437, "s": 29300, "text": "Keys must be immutable. Which means you can use strings, numbers or tuples as dictionary keys but something like ['key'] is not allowed." }, { "code": null, "e": 29464, "s": 29437, "text": "An example is as follows −" }, { "code": null, "e": 29556, "s": 29464, "text": "#!/usr/bin/python\n\ndict = {['Name']: 'Zara', 'Age': 7}\nprint \"dict['Name']: \", dict['Name']" }, { "code": null, "e": 29624, "s": 29556, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 29781, "s": 29624, "text": "Traceback (most recent call last):\n File \"test.py\", line 3, in <module>\n dict = {['Name']: 'Zara', 'Age': 7};\nTypeError: list objects are unhashable\n" }, { "code": null, "e": 30011, "s": 29781, "text": "Two dimensional array is an array within an array. It is an array of arrays. In this type of array the position of an data element is referred by two indices instead of one. So it represents a table with rows an dcolumns of data." }, { "code": null, "e": 30118, "s": 30011, "text": "In the below example of a two dimensional array, observer that each array element itself is also an array." }, { "code": null, "e": 30344, "s": 30118, "text": "Consider the example of recording temperatures 4 times a day, every day. Some times the recording instrument may be faulty and we fail to record data. Such data for 4 days can be presented as a two dimensional array as below." }, { "code": null, "e": 30419, "s": 30344, "text": "Day 1 - 11 12 5 2 \nDay 2 - 15 6 10 \nDay 3 - 10 8 12 5 \nDay 4 - 12 15 8 6 \n" }, { "code": null, "e": 30490, "s": 30419, "text": "The above data can be represented as a two dimensional array as below." }, { "code": null, "e": 30552, "s": 30490, "text": "T = [[11, 12, 5, 2], [15, 6,10], [10, 8, 12, 5], [12,15,8,6]]" }, { "code": null, "e": 30855, "s": 30552, "text": "The data elements in two dimesnional arrays can be accessed using two indices. One index referring to the main or parent array and another index referring to the position of the data element in the inner array.If we mention only one index then the entire inner array is printed for that index position." }, { "code": null, "e": 30899, "s": 30855, "text": "The example below illustrates how it works." }, { "code": null, "e": 31011, "s": 30899, "text": "from array import *\n\nT = [[11, 12, 5, 2], [15, 6,10], [10, 8, 12, 5], [12,15,8,6]]\n\nprint(T[0])\n\nprint(T[1][2])" }, { "code": null, "e": 31079, "s": 31011, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 31098, "s": 31079, "text": "[11, 12, 5, 2]\n10\n" }, { "code": null, "e": 31249, "s": 31098, "text": "To print out the entire two dimensional array we can use python for loop as shown below. We use end of line to print out the values in different rows." }, { "code": null, "e": 31395, "s": 31249, "text": "from array import *\n\nT = [[11, 12, 5, 2], [15, 6,10], [10, 8, 12, 5], [12,15,8,6]]\nfor r in T:\n for c in r:\n print(c,end = \" \")\n print()" }, { "code": null, "e": 31463, "s": 31395, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 31510, "s": 31463, "text": "11 12 5 2 \n15 6 10 \n10 8 12 5 \n12 15 8 6 \n" }, { "code": null, "e": 31618, "s": 31510, "text": "We can insert new data elements at specific position by using the insert() method and specifying the index." }, { "code": null, "e": 31691, "s": 31618, "text": "In the below example a new data element is inserted at index position 2." }, { "code": null, "e": 31865, "s": 31691, "text": "from array import *\nT = [[11, 12, 5, 2], [15, 6,10], [10, 8, 12, 5], [12,15,8,6]]\n\nT.insert(2, [0,5,11,13,6])\n\nfor r in T:\n for c in r:\n print(c,end = \" \")\n print()" }, { "code": null, "e": 31933, "s": 31865, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 31998, "s": 31933, "text": "11 12 5 2 \n15 6 10 \n 0 5 11 13 6 \n10 8 12 5 \n12 15 8 6 \n" }, { "code": null, "e": 32134, "s": 31998, "text": "We can update the entire inner array or some specific data elements of the inner array by reassigning the values using the array index." }, { "code": null, "e": 32307, "s": 32134, "text": "from array import *\n\nT = [[11, 12, 5, 2], [15, 6,10], [10, 8, 12, 5], [12,15,8,6]]\n\nT[2] = [11,9]\nT[0][3] = 7\nfor r in T:\n for c in r:\n print(c,end = \" \")\n print()" }, { "code": null, "e": 32375, "s": 32307, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 32417, "s": 32375, "text": "11 12 5 7 \n15 6 10 \n11 9 \n12 15 8 6 \n" }, { "code": null, "e": 32692, "s": 32417, "text": "We can delete the entire inner array or some specific data elements of the inner array by reassigning the values using the del() method with index. But in case you need to remove specific data elements in one of the inner arrays, then use the update process described above." }, { "code": null, "e": 32848, "s": 32692, "text": "from array import *\nT = [[11, 12, 5, 2], [15, 6,10], [10, 8, 12, 5], [12,15,8,6]]\n\ndel T[3]\n\nfor r in T:\n for c in r:\n print(c,end = \" \")\n print()" }, { "code": null, "e": 32916, "s": 32848, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 32948, "s": 32916, "text": "11 12 5 2 \n15 6 10 \n10 8 12 5 \n" }, { "code": null, "e": 33116, "s": 32948, "text": "Matrix is a special case of two dimensional array where each data element is of strictly same size. So every matrix is also a two dimensional array but not vice versa." }, { "code": null, "e": 33387, "s": 33116, "text": "Matrices are very important data structures for many mathematical and scientific calculations. As we have already discussed two dimnsional array data structure in the previous chapter we will be focusing on data structure operations specific to matrices in this chapter." }, { "code": null, "e": 33452, "s": 33387, "text": "We also be using the numpy package for matrix data manipulation." }, { "code": null, "e": 33656, "s": 33452, "text": "Consider the case of recording temprature for 1 week measured in the morning, mid-day, evening and mid-night. It can be presented as a 7X5 matrix using an array and the reshape method available in numpy." }, { "code": null, "e": 33872, "s": 33656, "text": "from numpy import * \na = array([['Mon',18,20,22,17],['Tue',11,18,21,18],\n ['Wed',15,21,20,19],['Thu',11,20,22,21],\n ['Fri',18,17,23,22],['Sat',12,22,20,18],\n ['Sun',13,15,19,16]])\nm = reshape(a,(7,5))\nprint(m)" }, { "code": null, "e": 33944, "s": 33872, "text": "The above data can be represented as a two dimensional array as below −" }, { "code": null, "e": 34165, "s": 33944, "text": "[\n ['Mon' '18' '20' '22' '17']\n ['Tue' '11' '18' '21' '18']\n ['Wed' '15' '21' '20' '19']\n ['Thu' '11' '20' '22' '21']\n ['Fri' '18' '17' '23' '22']\n ['Sat' '12' '22' '20' '18']\n ['Sun' '13' '15' '19' '16']\n]" }, { "code": null, "e": 34313, "s": 34165, "text": "The data elements in a matrix can be accessed by using the indexes. The access method is same as the way data is accessed in Two dimensional array." }, { "code": null, "e": 34591, "s": 34313, "text": "from numpy import * \nm = array([['Mon',18,20,22,17],['Tue',11,18,21,18],\n ['Wed',15,21,20,19],['Thu',11,20,22,21],\n ['Fri',18,17,23,22],['Sat',12,22,20,18],\n ['Sun',13,15,19,16]])\n \n# Print data for Wednesday\nprint(m[2])\n\n# Print data for friday evening\nprint(m[4][3])" }, { "code": null, "e": 34659, "s": 34591, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 34687, "s": 34659, "text": "['Wed', 15, 21, 20, 19]\n23\n" }, { "code": null, "e": 34742, "s": 34687, "text": "Use the below mentioned code to add a row in a matrix." }, { "code": null, "e": 34980, "s": 34742, "text": "from numpy import * \nm = array([['Mon',18,20,22,17],['Tue',11,18,21,18],\n ['Wed',15,21,20,19],['Thu',11,20,22,21],\n ['Fri',18,17,23,22],['Sat',12,22,20,18],\n ['Sun',13,15,19,16]])\nm_r = append(m,[['Avg',12,15,13,11]],0)\n\nprint(m_r)" }, { "code": null, "e": 35048, "s": 34980, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 35301, "s": 35048, "text": "[\n ['Mon' '18' '20' '22' '17']\n ['Tue' '11' '18' '21' '18']\n ['Wed' '15' '21' '20' '19']\n ['Thu' '11' '20' '22' '21']\n ['Fri' '18' '17' '23' '22']\n ['Sat' '12' '22' '20' '18']\n ['Sun' '13' '15' '19' '16']\n ['Avg' '12' '15' '13' '11']\n]\n" }, { "code": null, "e": 35568, "s": 35301, "text": "We can add column to a matrix using the insert() method. here we have to mention the index where we want to add the column and a array containing the new values of the columns added.In the below example we add t a new column at the fifth position from the beginning." }, { "code": null, "e": 35818, "s": 35568, "text": "from numpy import * \nm = array([['Mon',18,20,22,17],['Tue',11,18,21,18],\n ['Wed',15,21,20,19],['Thu',11,20,22,21],\n ['Fri',18,17,23,22],['Sat',12,22,20,18],\n ['Sun',13,15,19,16]])\nm_c = insert(m,[5],[[1],[2],[3],[4],[5],[6],[7]],1)\n\nprint(m_c)" }, { "code": null, "e": 35886, "s": 35818, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 36136, "s": 35886, "text": "[\n ['Mon' '18' '20' '22' '17' '1']\n ['Tue' '11' '18' '21' '18' '2']\n ['Wed' '15' '21' '20' '19' '3']\n ['Thu' '11' '20' '22' '21' '4']\n ['Fri' '18' '17' '23' '22' '5']\n ['Sat' '12' '22' '20' '18' '6']\n ['Sun' '13' '15' '19' '16' '7']\n]\n" }, { "code": null, "e": 36302, "s": 36136, "text": "We can delete a row from a matrix using the delete() method. We have to specify the index of the row and also the axis value which is 0 for a row and 1 for a column." }, { "code": null, "e": 36518, "s": 36302, "text": "from numpy import * \nm = array([['Mon',18,20,22,17],['Tue',11,18,21,18],\n ['Wed',15,21,20,19],['Thu',11,20,22,21],\n ['Fri',18,17,23,22],['Sat',12,22,20,18],\n ['Sun',13,15,19,16]])\nm = delete(m,[2],0)\n\nprint(m)" }, { "code": null, "e": 36586, "s": 36518, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 36777, "s": 36586, "text": "[\n ['Mon' '18' '20' '22' '17']\n ['Tue' '11' '18' '21' '18']\n ['Thu' '11' '20' '22' '21']\n ['Fri' '18' '17' '23' '22']\n ['Sat' '12' '22' '20' '18']\n ['Sun' '13' '15' '19' '16']\n]\n" }, { "code": null, "e": 36949, "s": 36777, "text": "We can delete a column from a matrix using the delete() method. We have to specify the index of the column and also the axis value which is 0 for a row and 1 for a column." }, { "code": null, "e": 37167, "s": 36949, "text": "from numpy import * \nm = array([['Mon',18,20,22,17],['Tue',11,18,21,18],\n ['Wed',15,21,20,19],['Thu',11,20,22,21],\n ['Fri',18,17,23,22],['Sat',12,22,20,18],\n ['Sun',13,15,19,16]])\nm = delete(m,s_[2],1)\n\nprint(m)" }, { "code": null, "e": 37235, "s": 37167, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 37422, "s": 37235, "text": "[\n ['Mon' '18' '22' '17']\n ['Tue' '11' '21' '18']\n ['Wed' '15' '20' '19']\n ['Thu' '11' '22' '21']\n ['Fri' '18' '23' '22']\n ['Sat' '12' '20' '18']\n ['Sun' '13' '19' '16']\n]\n" }, { "code": null, "e": 37626, "s": 37422, "text": "To update the values in the row of a matrix we simply re-assign the values at the index of the row. In the below example all the values for thrusday's data is marked as zero. The index for this row is 3." }, { "code": null, "e": 37845, "s": 37626, "text": "from numpy import * \nm = array([['Mon',18,20,22,17],['Tue',11,18,21,18],\n ['Wed',15,21,20,19],['Thu',11,20,22,21],\n ['Fri',18,17,23,22],['Sat',12,22,20,18],\n ['Sun',13,15,19,16]])\nm[3] = ['Thu',0,0,0,0]\n\nprint(m)" }, { "code": null, "e": 37913, "s": 37845, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 38131, "s": 37913, "text": "[\n ['Mon' '18' '20' '22' '17']\n ['Tue' '11' '18' '21' '18']\n ['Wed' '15' '21' '20' '19']\n ['Thu' '0' '0' '0' '0']\n ['Fri' '18' '17' '23' '22']\n ['Sat' '12' '22' '20' '18']\n ['Sun' '13' '15' '19' '16']\n]\n" }, { "code": null, "e": 38296, "s": 38131, "text": "Mathematically a set is a collection of items not in any particular order. A Python set is similar to this mathematical definition with below additional conditions." }, { "code": null, "e": 38342, "s": 38296, "text": "The elements in the set cannot be duplicates." }, { "code": null, "e": 38388, "s": 38342, "text": "The elements in the set cannot be duplicates." }, { "code": null, "e": 38481, "s": 38388, "text": "The elements in the set are immutable(cannot be modified) but the set as a whole is mutable." }, { "code": null, "e": 38574, "s": 38481, "text": "The elements in the set are immutable(cannot be modified) but the set as a whole is mutable." }, { "code": null, "e": 38691, "s": 38574, "text": "There is no index attached to any element in a python set. So they do not support any indexing or slicing operation." }, { "code": null, "e": 38808, "s": 38691, "text": "There is no index attached to any element in a python set. So they do not support any indexing or slicing operation." }, { "code": null, "e": 39033, "s": 38808, "text": "The sets in python are typically used for mathematical operations like union, intersection, difference and complement etc. We can create a set, access it’s elements and carry out these mathematical operations as shown below." }, { "code": null, "e": 39137, "s": 39033, "text": "A set is created by using the set() function or placing all the elements within a pair of curly braces." }, { "code": null, "e": 39274, "s": 39137, "text": "Days=set([\"Mon\",\"Tue\",\"Wed\",\"Thu\",\"Fri\",\"Sat\",\"Sun\"])\nMonths={\"Jan\",\"Feb\",\"Mar\"}\nDates={21,22,17}\nprint(Days)\nprint(Months)\nprint(Dates)" }, { "code": null, "e": 39410, "s": 39274, "text": "When the above code is executed, it produces the following result. Please note how the order of the elements has changed in the result." }, { "code": null, "e": 39511, "s": 39410, "text": "set(['Wed', 'Sun', 'Fri', 'Tue', 'Mon', 'Thu', 'Sat'])\nset(['Jan', 'Mar', 'Feb'])\nset([17, 21, 22])\n" }, { "code": null, "e": 39695, "s": 39511, "text": "We cannot access individual values in a set. We can only access all the elements together as shown above. But we can also get a list of individual elements by looping through the set." }, { "code": null, "e": 39778, "s": 39695, "text": "Days=set([\"Mon\",\"Tue\",\"Wed\",\"Thu\",\"Fri\",\"Sat\",\"Sun\"])\n \nfor d in Days:\n print(d)" }, { "code": null, "e": 39846, "s": 39778, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 39875, "s": 39846, "text": "Wed\nSun\nFri\nTue\nMon\nThu\nSat\n" }, { "code": null, "e": 40010, "s": 39875, "text": "We can add elements to a set by using add() method. Again as discussed there is no specific index attached to the newly added element." }, { "code": null, "e": 40088, "s": 40010, "text": "Days=set([\"Mon\",\"Tue\",\"Wed\",\"Thu\",\"Fri\",\"Sat\"])\n \nDays.add(\"Sun\")\nprint(Days)" }, { "code": null, "e": 40156, "s": 40088, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 40212, "s": 40156, "text": "set(['Wed', 'Sun', 'Fri', 'Tue', 'Mon', 'Thu', 'Sat'])\n" }, { "code": null, "e": 40356, "s": 40212, "text": "We can remove elements from a set by using discard() method. Again as discussed there is no specific index attached to the newly added element." }, { "code": null, "e": 40438, "s": 40356, "text": "Days=set([\"Mon\",\"Tue\",\"Wed\",\"Thu\",\"Fri\",\"Sat\"])\n \nDays.discard(\"Sun\")\nprint(Days)" }, { "code": null, "e": 40505, "s": 40438, "text": "When the above code is executed, it produces the following result." }, { "code": null, "e": 40554, "s": 40505, "text": "set(['Wed', 'Fri', 'Tue', 'Mon', 'Thu', 'Sat'])\n" }, { "code": null, "e": 40730, "s": 40554, "text": "The union operation on two sets produces a new set containing all the distinct elements from both the sets. In the below example the element “Wed” is present in both the sets." }, { "code": null, "e": 40845, "s": 40730, "text": "DaysA = set([\"Mon\",\"Tue\",\"Wed\"])\nDaysB = set([\"Wed\",\"Thu\",\"Fri\",\"Sat\",\"Sun\"])\nAllDays = DaysA|DaysB\nprint(AllDays)" }, { "code": null, "e": 40955, "s": 40845, "text": "When the above code is executed, it produces the following result. Please note the result has only one “wed”." }, { "code": null, "e": 41004, "s": 40955, "text": "set(['Wed', 'Fri', 'Tue', 'Mon', 'Thu', 'Sat'])\n" }, { "code": null, "e": 41186, "s": 41004, "text": "The intersection operation on two sets produces a new set containing only the common elements from both the sets. In the below example the element “Wed” is present in both the sets." }, { "code": null, "e": 41303, "s": 41186, "text": "DaysA = set([\"Mon\",\"Tue\",\"Wed\"])\nDaysB = set([\"Wed\",\"Thu\",\"Fri\",\"Sat\",\"Sun\"])\nAllDays = DaysA & DaysB\nprint(AllDays)" }, { "code": null, "e": 41413, "s": 41303, "text": "When the above code is executed, it produces the following result. Please note the result has only one “wed”." }, { "code": null, "e": 41427, "s": 41413, "text": "set(['Wed'])\n" }, { "code": null, "e": 41671, "s": 41427, "text": "The difference operation on two sets produces a new set containing only the elements from the first set and none from the second set. In the below example the element “Wed” is present in both the sets so it will not be found in the result set." }, { "code": null, "e": 41788, "s": 41671, "text": "DaysA = set([\"Mon\",\"Tue\",\"Wed\"])\nDaysB = set([\"Wed\",\"Thu\",\"Fri\",\"Sat\",\"Sun\"])\nAllDays = DaysA - DaysB\nprint(AllDays)" }, { "code": null, "e": 41898, "s": 41788, "text": "When the above code is executed, it produces the following result. Please note the result has only one “wed”." }, { "code": null, "e": 41919, "s": 41898, "text": "set(['Mon', 'Tue'])\n" }, { "code": null, "e": 42062, "s": 41919, "text": "We can check if a given set is a subset or superset of another set. The result is True or False depending on the elements present in the sets." }, { "code": null, "e": 42244, "s": 42062, "text": "DaysA = set([\"Mon\",\"Tue\",\"Wed\"])\nDaysB = set([\"Mon\",\"Tue\",\"Wed\",\"Thu\",\"Fri\",\"Sat\",\"Sun\"])\nSubsetRes = DaysA <= DaysB\nSupersetRes = DaysB >= DaysA\nprint(SubsetRes)\nprint(SupersetRes)" }, { "code": null, "e": 42312, "s": 42244, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 42323, "s": 42312, "text": "True\nTrue\n" }, { "code": null, "e": 42736, "s": 42323, "text": "Python Maps also called ChainMap is a type of data structure to manage multiple dictionaries together as one unit. The combined dictionary contains the key and value pairs in a specific sequence eliminating any duplicate keys. The best use of ChainMap is to search through multiple dictionaries at a time and get the proper key-value pair mapping. We also see that these ChainMaps behave as stack data structure." }, { "code": null, "e": 43003, "s": 42736, "text": "We create two dictionaries and club them using the ChainMap method from the collections library. Then we print the keys and values of the result of the combination of the dictionaries. If there are duplicate keys, then only the value from the first key is preserved." }, { "code": null, "e": 43569, "s": 43003, "text": "import collections\n\ndict1 = {'day1': 'Mon', 'day2': 'Tue'}\ndict2 = {'day3': 'Wed', 'day1': 'Thu'}\n\nres = collections.ChainMap(dict1, dict2)\n\n# Creating a single dictionary\nprint(res.maps,'\\n')\n\nprint('Keys = {}'.format(list(res.keys())))\nprint('Values = {}'.format(list(res.values())))\nprint()\n\n# Print all the elements from the result\nprint('elements:')\nfor key, val in res.items():\n print('{} = {}'.format(key, val))\nprint()\n\n# Find a specific value in the result\nprint('day3 in res: {}'.format(('day1' in res)))\nprint('day4 in res: {}'.format(('day4' in res)))" }, { "code": null, "e": 43637, "s": 43569, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 43850, "s": 43637, "text": "[{'day1': 'Mon', 'day2': 'Tue'}, {'day1': 'Thu', 'day3': 'Wed'}] \n\nKeys = ['day1', 'day3', 'day2']\nValues = ['Mon', 'Wed', 'Tue']\n\nelements:\nday1 = Mon\nday3 = Wed\nday2 = Tue\n\nday3 in res: True\nday4 in res: False\n" }, { "code": null, "e": 44076, "s": 43850, "text": "If we change the order the dictionaries while clubbing them in the above example we see that the position of the elements get interchanged as if they are in a continuous chain. This again shows the behavior of Maps as stacks." }, { "code": null, "e": 44304, "s": 44076, "text": "import collections\n\ndict1 = {'day1': 'Mon', 'day2': 'Tue'}\ndict2 = {'day3': 'Wed', 'day4': 'Thu'}\n\nres1 = collections.ChainMap(dict1, dict2)\nprint(res1.maps,'\\n')\n\nres2 = collections.ChainMap(dict2, dict1)\nprint(res2.maps,'\\n')" }, { "code": null, "e": 44372, "s": 44304, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 44506, "s": 44372, "text": "[{'day1': 'Mon', 'day2': 'Tue'}, {'day3': 'Wed', 'day4': 'Thu'}] \n\n[{'day3': 'Wed', 'day4': 'Thu'}, {'day1': 'Mon', 'day2': 'Tue'}] \n" }, { "code": null, "e": 44749, "s": 44506, "text": "When the element of the dictionary is updated, the result is instantly updated in the result of the ChainMap. In the below example we see that the new updated value reflects in the result without explicitly applying the ChainMap method again." }, { "code": null, "e": 44954, "s": 44749, "text": "import collections\n\ndict1 = {'day1': 'Mon', 'day2': 'Tue'}\ndict2 = {'day3': 'Wed', 'day4': 'Thu'}\n\nres = collections.ChainMap(dict1, dict2)\nprint(res.maps,'\\n')\n\ndict2['day4'] = 'Fri'\nprint(res.maps,'\\n')" }, { "code": null, "e": 45022, "s": 44954, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 45156, "s": 45022, "text": "[{'day1': 'Mon', 'day2': 'Tue'}, {'day3': 'Wed', 'day4': 'Thu'}] \n\n[{'day1': 'Mon', 'day2': 'Tue'}, {'day3': 'Wed', 'day4': 'Fri'}] \n" }, { "code": null, "e": 45493, "s": 45156, "text": "A linked list is a sequence of data elements, which are connected together via links. Each data element contains a connection to another data element in form of a pointer. Python does not have linked lists in its standard library. We implement the concept of linked lists using the concept of nodes as discussed in the previous chapter." }, { "code": null, "e": 45868, "s": 45493, "text": "We have already seen how we create a node class and how to traverse the elements of a node.In this chapter we are going to study the types of linked lists known as singly linked lists. In this type of data structure there is only one link between any two data elements. We create such a list and create additional methods to insert, update and remove elements from the list." }, { "code": null, "e": 46250, "s": 45868, "text": "A linked list is created by using the node class we studied in the last chapter. We create a Node object and create another class to use this ode object. We pass the appropriate values through the node object to point the to the next data elements. The below program creates the linked list with three data elements. In the next section we will see how to traverse the linked list." }, { "code": null, "e": 46618, "s": 46250, "text": "class Node:\n def __init__(self, dataval=None):\n self.dataval = dataval\n self.nextval = None\n\nclass SLinkedList:\n def __init__(self):\n self.headval = None\n\nlist1 = SLinkedList()\nlist1.headval = Node(\"Mon\")\ne2 = Node(\"Tue\")\ne3 = Node(\"Wed\")\n# Link first Node to second node\nlist1.headval.nextval = e2\n\n# Link second Node to third node\ne2.nextval = e3" }, { "code": null, "e": 46841, "s": 46618, "text": "Singly linked lists can be traversed in only forward direction starting form the first data element. We simply print the value of the next data element by assigning the pointer of the next node to the current data element." }, { "code": null, "e": 47385, "s": 46841, "text": "class Node:\n def __init__(self, dataval=None):\n self.dataval = dataval\n self.nextval = None\n\nclass SLinkedList:\n def __init__(self):\n self.headval = None\n\n def listprint(self):\n printval = self.headval\n while printval is not None:\n print (printval.dataval)\n printval = printval.nextval\n\nlist = SLinkedList()\nlist.headval = Node(\"Mon\")\ne2 = Node(\"Tue\")\ne3 = Node(\"Wed\")\n\n# Link first Node to second node\nlist.headval.nextval = e2\n\n# Link second Node to third node\ne2.nextval = e3\n\nlist.listprint()" }, { "code": null, "e": 47453, "s": 47385, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 47466, "s": 47453, "text": "Mon\nTue\nWed\n" }, { "code": null, "e": 47748, "s": 47466, "text": "Inserting element in the linked list involves reassigning the pointers from the existing nodes to the newly inserted node. Depending on whether the new data element is getting inserted at the beginning or at the middle or at the end of the linked list, we have the below scenarios." }, { "code": null, "e": 47974, "s": 47748, "text": "This involves pointing the next pointer of the new data node to the current head of the linked list. So the current head of the linked list becomes the second data element and the new node becomes the head of the linked list." }, { "code": null, "e": 48670, "s": 47974, "text": "class Node:\n def __init__(self, dataval=None):\n self.dataval = dataval\n self.nextval = None\n\nclass SLinkedList:\n def __init__(self):\n self.headval = None\n# Print the linked list\n def listprint(self):\n printval = self.headval\n while printval is not None:\n print (printval.dataval)\n printval = printval.nextval\n def AtBegining(self,newdata):\n NewNode = Node(newdata)\n\n# Update the new nodes next val to existing node\n NewNode.nextval = self.headval\n self.headval = NewNode\n\nlist = SLinkedList()\nlist.headval = Node(\"Mon\")\ne2 = Node(\"Tue\")\ne3 = Node(\"Wed\")\n\nlist.headval.nextval = e2\ne2.nextval = e3\n\nlist.AtBegining(\"Sun\")\nlist.listprint()" }, { "code": null, "e": 48738, "s": 48670, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 48755, "s": 48738, "text": "Sun\nMon\nTue\nWed\n" }, { "code": null, "e": 49002, "s": 48755, "text": "This involves pointing the next pointer of the the current last node of the linked list to the new data node. So the current last node of the linked list becomes the second last data node and the new node becomes the last node of the linked list." }, { "code": null, "e": 49798, "s": 49002, "text": "class Node:\n def __init__(self, dataval=None):\n self.dataval = dataval\n self.nextval = None\nclass SLinkedList:\n def __init__(self):\n self.headval = None\n# Function to add newnode\n def AtEnd(self, newdata):\n NewNode = Node(newdata)\n if self.headval is None:\n self.headval = NewNode\n return\n laste = self.headval\n while(laste.nextval):\n laste = laste.nextval\n laste.nextval=NewNode\n# Print the linked list\n def listprint(self):\n printval = self.headval\n while printval is not None:\n print (printval.dataval)\n printval = printval.nextval\n\nlist = SLinkedList()\nlist.headval = Node(\"Mon\")\ne2 = Node(\"Tue\")\ne3 = Node(\"Wed\")\n\nlist.headval.nextval = e2\ne2.nextval = e3\n\nlist.AtEnd(\"Thu\")\n\nlist.listprint()" }, { "code": null, "e": 49866, "s": 49798, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 49883, "s": 49866, "text": "Mon\nTue\nWed\nThu\n" }, { "code": null, "e": 50258, "s": 49883, "text": "This involves changing the pointer of a specific node to point to the new node. That is possible by passing in both the new node and the existing node after which the new node will be inserted. So we define an additional class which will change the next pointer of the new node to the next pointer of middle node. Then assign the new node to next pointer of the middle node." }, { "code": null, "e": 51074, "s": 50258, "text": "class Node:\n def __init__(self, dataval=None):\n self.dataval = dataval\n self.nextval = None\nclass SLinkedList:\n def __init__(self):\n self.headval = None\n\n# Function to add node\n def Inbetween(self,middle_node,newdata):\n if middle_node is None:\n print(\"The mentioned node is absent\")\n return\n\n NewNode = Node(newdata)\n NewNode.nextval = middle_node.nextval\n middle_node.nextval = NewNode\n\n# Print the linked list\n def listprint(self):\n printval = self.headval\n while printval is not None:\n print (printval.dataval)\n printval = printval.nextval\n\nlist = SLinkedList()\nlist.headval = Node(\"Mon\")\ne2 = Node(\"Tue\")\ne3 = Node(\"Thu\")\n\nlist.headval.nextval = e2\ne2.nextval = e3\n\nlist.Inbetween(list.headval.nextval,\"Fri\")\n\nlist.listprint()" }, { "code": null, "e": 51142, "s": 51074, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 51159, "s": 51142, "text": "Mon\nTue\nFri\nThu\n" }, { "code": null, "e": 51389, "s": 51159, "text": "We can remove an existing node using the key for that node. In the below program we locate the previous node of the node which is to be deleted.Then, point the next pointer of this node to the next node of the node to be deleted." }, { "code": null, "e": 52476, "s": 51389, "text": "class Node:\n def __init__(self, data=None):\n self.data = data\n self.next = None\nclass SLinkedList:\n def __init__(self):\n self.head = None\n\n def Atbegining(self, data_in):\n NewNode = Node(data_in)\n NewNode.next = self.head\n self.head = NewNode\n\n# Function to remove node\n def RemoveNode(self, Removekey):\n HeadVal = self.head\n \n if (HeadVal is not None):\n if (HeadVal.data == Removekey):\n self.head = HeadVal.next\n HeadVal = None\n return\n while (HeadVal is not None):\n if HeadVal.data == Removekey:\n break\n prev = HeadVal\n HeadVal = HeadVal.next\n\n if (HeadVal == None):\n return\n\n prev.next = HeadVal.next\n HeadVal = None\n\n def LListprint(self):\n printval = self.head\n while (printval):\n print(printval.data),\n printval = printval.next\n\nllist = SLinkedList()\nllist.Atbegining(\"Mon\")\nllist.Atbegining(\"Tue\")\nllist.Atbegining(\"Wed\")\nllist.Atbegining(\"Thu\")\nllist.RemoveNode(\"Tue\")\nllist.LListprint()" }, { "code": null, "e": 52544, "s": 52476, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 52557, "s": 52544, "text": "Thu\nWed\nMon\n" }, { "code": null, "e": 52978, "s": 52557, "text": "In the english dictionary the word stack means arranging objects on over another. It is the same way memory is allocated in this data structure. It stores the data elements in a similar fashion as a bunch of plates are stored one above another in the kitchen. So stack data strcuture allows operations at one end wich can be called top of the stack.We can add elements or remove elements only form this en dof the stack." }, { "code": null, "e": 53406, "s": 52978, "text": "In a stack the element insreted last in sequence will come out first as we can remove only from the top of the stack. Such feature is known as Last in First Out(LIFO) feature. The operations of adding and removing the elements is known as PUSH and POP. In the following program we implement it as add and and remove functions. We declare an empty list and use the append() and pop() methods to add and remove the data elements." }, { "code": null, "e": 53495, "s": 53406, "text": "Let us understand, how to use PUSH in Stack. Refer the program mentioned program below −" }, { "code": null, "e": 53987, "s": 53495, "text": "class Stack:\n def __init__(self):\n self.stack = []\n\n def add(self, dataval):\n# Use list append method to add element\n if dataval not in self.stack:\n self.stack.append(dataval)\n return True\n else:\n return False\n# Use peek to look at the top of the stack\n def peek(self): \n\t return self.stack[-1]\n\nAStack = Stack()\nAStack.add(\"Mon\")\nAStack.add(\"Tue\")\nAStack.peek()\nprint(AStack.peek())\nAStack.add(\"Wed\")\nAStack.add(\"Thu\")\nprint(AStack.peek())" }, { "code": null, "e": 54055, "s": 53987, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 54064, "s": 54055, "text": "Tue\nThu\n" }, { "code": null, "e": 54399, "s": 54064, "text": "As we know we can remove only the top most data element from the stack, we implement a python program which does that. The remove function in the following program returns the top most element. we check the top element by calculating the size of the stack first and then use the in-built pop() method to find out the top most element." }, { "code": null, "e": 54978, "s": 54399, "text": "class Stack:\n def __init__(self):\n self.stack = []\n\n def add(self, dataval):\n# Use list append method to add element\n if dataval not in self.stack:\n self.stack.append(dataval)\n return True\n else:\n return False\n \n# Use list pop method to remove element\n def remove(self):\n if len(self.stack) <= 0:\n return (\"No element in the Stack\")\n else:\n return self.stack.pop()\n\nAStack = Stack()\nAStack.add(\"Mon\")\nAStack.add(\"Tue\")\nAStack.add(\"Wed\")\nAStack.add(\"Thu\")\nprint(AStack.remove())\nprint(AStack.remove())" }, { "code": null, "e": 55046, "s": 54978, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 55055, "s": 55046, "text": "Thu\nWed\n" }, { "code": null, "e": 55396, "s": 55055, "text": "We are familiar with queue in our day to day life as we wait for a service. The queue data structure aslo means the same where the data elements are arranged in a queue. The uniqueness of queue lies in the way items are added and removed. The items are allowed at on end but removed form the other end. So it is a First-in-First out method." }, { "code": null, "e": 55598, "s": 55396, "text": "A queue can be implemented using python list where we can use the insert() and pop() methods to add and remove elements. Their is no insertion as data elements are always added at the end of the queue." }, { "code": null, "e": 55753, "s": 55598, "text": "In the below example we create a queue class where we implement the First-in-First-Out method. We use the in-built insert method for adding data elements." }, { "code": null, "e": 56139, "s": 55753, "text": "class Queue:\n def __init__(self):\n self.queue = list()\n\n def addtoq(self,dataval):\n# Insert method to add element\n if dataval not in self.queue:\n self.queue.insert(0,dataval)\n return True\n return False\n\n def size(self):\n return len(self.queue)\n\nTheQueue = Queue()\nTheQueue.addtoq(\"Mon\")\nTheQueue.addtoq(\"Tue\")\nTheQueue.addtoq(\"Wed\")\nprint(TheQueue.size())" }, { "code": null, "e": 56207, "s": 56139, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 56210, "s": 56207, "text": "3\n" }, { "code": null, "e": 56336, "s": 56210, "text": "In the below example we create a queue class where we insert the data and then remove the data using the in-built pop method." }, { "code": null, "e": 56867, "s": 56336, "text": "class Queue:\n def __init__(self):\n self.queue = list()\n\n def addtoq(self,dataval):\n# Insert method to add element\n if dataval not in self.queue:\n self.queue.insert(0,dataval)\n return True\n return False\n# Pop method to remove element\n def removefromq(self):\n if len(self.queue)>0:\n return self.queue.pop()\n return (\"No elements in Queue!\")\n\nTheQueue = Queue()\nTheQueue.addtoq(\"Mon\")\nTheQueue.addtoq(\"Tue\")\nTheQueue.addtoq(\"Wed\")\nprint(TheQueue.removefromq())\nprint(TheQueue.removefromq())" }, { "code": null, "e": 56935, "s": 56867, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 56944, "s": 56935, "text": "Mon\nTue\n" }, { "code": null, "e": 57165, "s": 56944, "text": "A double-ended queue, or deque, supports adding and removing elements from either end. The more commonly used stacks and queues are degenerate forms of deques, where the inputs and outputs are restricted to a single end." }, { "code": null, "e": 57556, "s": 57165, "text": "import collections\n\nDoubleEnded = collections.deque([\"Mon\",\"Tue\",\"Wed\"])\nDoubleEnded.append(\"Thu\")\n\nprint (\"Appended at right - \")\nprint (DoubleEnded)\n\nDoubleEnded.appendleft(\"Sun\")\nprint (\"Appended at right at left is - \")\nprint (DoubleEnded)\n\nDoubleEnded.pop()\nprint (\"Deleting from right - \")\nprint (DoubleEnded)\n\nDoubleEnded.popleft()\nprint (\"Deleting from left - \")\nprint (DoubleEnded)" }, { "code": null, "e": 57624, "s": 57556, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 57867, "s": 57624, "text": "Appended at right - \ndeque(['Mon', 'Tue', 'Wed', 'Thu'])\nAppended at right at left is - \ndeque(['Sun', 'Mon', 'Tue', 'Wed', 'Thu'])\nDeleting from right - \ndeque(['Sun', 'Mon', 'Tue', 'Wed'])\nDeleting from left - \ndeque(['Mon', 'Tue', 'Wed'])\n" }, { "code": null, "e": 58178, "s": 57867, "text": "We have already seen Linked List in earlier chapter in which it is possible only to travel forward. In this chapter we see another type of linked list in which it is possible to travel both forward and backward. Such a linked list is called Doubly Linked List. Following is the features of doubly linked list." }, { "code": null, "e": 58244, "s": 58178, "text": "Doubly Linked List contains a link element called first and last." }, { "code": null, "e": 58310, "s": 58244, "text": "Doubly Linked List contains a link element called first and last." }, { "code": null, "e": 58386, "s": 58310, "text": "Each link carries a data field(s) and two link fields called next and prev." }, { "code": null, "e": 58462, "s": 58386, "text": "Each link carries a data field(s) and two link fields called next and prev." }, { "code": null, "e": 58522, "s": 58462, "text": "Each link is linked with its next link using its next link." }, { "code": null, "e": 58582, "s": 58522, "text": "Each link is linked with its next link using its next link." }, { "code": null, "e": 58650, "s": 58582, "text": "Each link is linked with its previous link using its previous link." }, { "code": null, "e": 58718, "s": 58650, "text": "Each link is linked with its previous link using its previous link." }, { "code": null, "e": 58784, "s": 58718, "text": "The last link carries a link as null to mark the end of the list." }, { "code": null, "e": 58850, "s": 58784, "text": "The last link carries a link as null to mark the end of the list." }, { "code": null, "e": 59122, "s": 58850, "text": "We create a Doubly Linked list by using the Node class. Now we use the same approach as used in the Singly Linked List but the head and next pointers will be used for proper assignation to create two links in each of the nodes in addition to the data present in the node." }, { "code": null, "e": 59788, "s": 59122, "text": "class Node:\n def __init__(self, data):\n self.data = data\n self.next = None\n self.prev = None\n\nclass doubly_linked_list:\n def __init__(self):\n self.head = None\n\n# Adding data elements\t\t\n def push(self, NewVal):\n NewNode = Node(NewVal)\n NewNode.next = self.head\n if self.head is not None:\n self.head.prev = NewNode\n self.head = NewNode\n\n# Print the Doubly Linked list\t\t\n def listprint(self, node):\n while (node is not None):\n print(node.data),\n last = node\n node = node.next\n\ndllist = doubly_linked_list()\ndllist.push(12)\ndllist.push(8)\ndllist.push(62)\ndllist.listprint(dllist.head)" }, { "code": null, "e": 59856, "s": 59788, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 59865, "s": 59856, "text": "62 8 12\n" }, { "code": null, "e": 60094, "s": 59865, "text": "Here, we are going to see how to insert a node to the Doubly Link List using the following program. The program uses a method named insert which inserts the new node at the third position from the head of the doubly linked list." }, { "code": null, "e": 61218, "s": 60094, "text": "# Create the Node class\nclass Node:\n def __init__(self, data):\n self.data = data\n self.next = None\n self.prev = None\n\n# Create the doubly linked list\nclass doubly_linked_list:\n def __init__(self):\n self.head = None\n\n# Define the push method to add elements\t\t\n def push(self, NewVal):\n NewNode = Node(NewVal)\n NewNode.next = self.head\n if self.head is not None:\n self.head.prev = NewNode\n self.head = NewNode\n\n# Define the insert method to insert the element\t\t\n def insert(self, prev_node, NewVal):\n if prev_node is None:\n return\n NewNode = Node(NewVal)\n NewNode.next = prev_node.next\n prev_node.next = NewNode\n NewNode.prev = prev_node\n if NewNode.next is not None:\n NewNode.next.prev = NewNode\n\n# Define the method to print the linked list \n def listprint(self, node):\n while (node is not None):\n print(node.data),\n last = node\n node = node.next\n\ndllist = doubly_linked_list()\ndllist.push(12)\ndllist.push(8)\ndllist.push(62)\ndllist.insert(dllist.head.next, 13)\ndllist.listprint(dllist.head)" }, { "code": null, "e": 61286, "s": 61218, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 61301, "s": 61286, "text": "62 8 13 12\n" }, { "code": null, "e": 61368, "s": 61301, "text": "Appending to a doubly linked list will add the element at the end." }, { "code": null, "e": 62550, "s": 61368, "text": "# Create the node class\nclass Node:\n def __init__(self, data):\n self.data = data\n self.next = None\n self.prev = None\n# Create the doubly linked list class\nclass doubly_linked_list:\n def __init__(self):\n self.head = None\n\n# Define the push method to add elements at the begining\n def push(self, NewVal):\n NewNode = Node(NewVal)\n NewNode.next = self.head\n if self.head is not None:\n self.head.prev = NewNode\n self.head = NewNode\n\n# Define the append method to add elements at the end\n def append(self, NewVal):\n NewNode = Node(NewVal)\n NewNode.next = None\n if self.head is None:\n NewNode.prev = None\n self.head = NewNode\n return\n last = self.head\n while (last.next is not None):\n last = last.next\n last.next = NewNode\n NewNode.prev = last\n return\n\n# Define the method to print\n def listprint(self, node):\n while (node is not None):\n print(node.data),\n last = node\n node = node.next\n\ndllist = doubly_linked_list()\ndllist.push(12)\ndllist.append(9)\ndllist.push(8)\ndllist.push(62)\ndllist.append(45)\ndllist.listprint(dllist.head)" }, { "code": null, "e": 62618, "s": 62550, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 62632, "s": 62618, "text": "62 8 12 9 45\n" }, { "code": null, "e": 62708, "s": 62632, "text": "Please note the position of the elements 9 and 45 for the append operation." }, { "code": null, "e": 63039, "s": 62708, "text": "Hash tables are a type of data structure in which the address or the index value of the data element is generated from a hash function. That makes accessing the data faster as the index value behaves as a key for the data value. In other words Hash table stores key-value pairs but the key is generated through a hashing function." }, { "code": null, "e": 63196, "s": 63039, "text": "So the search and insertion function of a data element becomes much faster as the key values themselves become the index of the array which stores the data." }, { "code": null, "e": 63341, "s": 63196, "text": "In Python, the Dictionary data types represent the implementation of hash tables. The Keys in the dictionary satisfy the following requirements." }, { "code": null, "e": 63507, "s": 63341, "text": "The keys of the dictionary are hashable i.e. the are generated by hashing function which generates unique result for each unique value supplied to the hash function." }, { "code": null, "e": 63673, "s": 63507, "text": "The keys of the dictionary are hashable i.e. the are generated by hashing function which generates unique result for each unique value supplied to the hash function." }, { "code": null, "e": 63730, "s": 63673, "text": "The order of data elements in a dictionary is not fixed." }, { "code": null, "e": 63787, "s": 63730, "text": "The order of data elements in a dictionary is not fixed." }, { "code": null, "e": 63875, "s": 63787, "text": "So we see the implementation of hash table by using the dictionary data types as below." }, { "code": null, "e": 63987, "s": 63875, "text": "To access dictionary elements, you can use the familiar square brackets along with the key to obtain its value." }, { "code": null, "e": 64176, "s": 63987, "text": "# Declare a dictionary \ndict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}\n\n# Accessing the dictionary with its key\nprint \"dict['Name']: \", dict['Name']\nprint \"dict['Age']: \", dict['Age']" }, { "code": null, "e": 64244, "s": 64176, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 64281, "s": 64244, "text": "dict['Name']: Zara\ndict['Age']: 7\n" }, { "code": null, "e": 64450, "s": 64281, "text": "You can update a dictionary by adding a new entry or a key-value pair, modifying an existing entry, or deleting an existing entry as shown below in the simple example −" }, { "code": null, "e": 64689, "s": 64450, "text": "# Declare a dictionary\ndict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}\ndict['Age'] = 8; # update existing entry\ndict['School'] = \"DPS School\"; # Add new entry\nprint \"dict['Age']: \", dict['Age']\nprint \"dict['School']: \", dict['School']" }, { "code": null, "e": 64757, "s": 64689, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 64802, "s": 64757, "text": "dict['Age']: 8\ndict['School']: DPS School\n" }, { "code": null, "e": 65032, "s": 64802, "text": "You can either remove individual dictionary elements or clear the entire contents of a dictionary. You can also delete entire dictionary in a single operation.To explicitly remove an entire dictionary, just use the del statement." }, { "code": null, "e": 65302, "s": 65032, "text": "dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}\ndel dict['Name']; # remove entry with key 'Name'\ndict.clear(); # remove all entries in dict\ndel dict ; # delete entire dictionary\n\nprint \"dict['Age']: \", dict['Age']\nprint \"dict['School']: \", dict['School']" }, { "code": null, "e": 65429, "s": 65302, "text": "This produces the following result. Note that an exception is raised because after del dict dictionary does not exist anymore." }, { "code": null, "e": 65603, "s": 65429, "text": "dict['Age']:\nTraceback (most recent call last):\n File \"test.py\", line 8, in <module>\n print \"dict['Age']: \", dict['Age'];\nTypeError: 'type' object is unsubscriptable\n" }, { "code": null, "e": 65718, "s": 65603, "text": "Tree represents the nodes connected by edges. It is a non-linear data structure. It has the following properties −" }, { "code": null, "e": 65751, "s": 65718, "text": "One node is marked as Root node." }, { "code": null, "e": 65784, "s": 65751, "text": "One node is marked as Root node." }, { "code": null, "e": 65851, "s": 65784, "text": "Every node other than the root is associated with one parent node." }, { "code": null, "e": 65918, "s": 65851, "text": "Every node other than the root is associated with one parent node." }, { "code": null, "e": 65970, "s": 65918, "text": "Each node can have an arbiatry number of chid node." }, { "code": null, "e": 66022, "s": 65970, "text": "Each node can have an arbiatry number of chid node." }, { "code": null, "e": 66229, "s": 66022, "text": "We create a tree data structure in python by using the concept os node discussed earlier. We designate one node as root node and then add more nodes as child nodes. Below is program to create the root node." }, { "code": null, "e": 66334, "s": 66229, "text": "We just create a Node class and add assign a value to the node. This becomes tree with only a root node." }, { "code": null, "e": 66526, "s": 66334, "text": "class Node:\n def __init__(self, data):\n self.left = None\n self.right = None\n self.data = data\n def PrintTree(self):\n print(self.data)\n\nroot = Node(10)\nroot.PrintTree()" }, { "code": null, "e": 66594, "s": 66526, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 66598, "s": 66594, "text": "10\n" }, { "code": null, "e": 66867, "s": 66598, "text": "To insert into a tree we use the same node class created above and add a insert class to it. The insert class compares the value of the node to the parent node and decides to add it as a left node or a right node. Finally the PrintTree class is used to print the tree." }, { "code": null, "e": 67733, "s": 66867, "text": "class Node:\n def __init__(self, data):\n self.left = None\n self.right = None\n self.data = data\n\n def insert(self, data):\n# Compare the new value with the parent node\n if self.data:\n if data < self.data:\n if self.left is None:\n self.left = Node(data)\n else:\n self.left.insert(data)\n elif data > self.data:\n if self.right is None:\n self.right = Node(data)\n else:\n self.right.insert(data)\n else:\n self.data = data\n\n# Print the tree\n def PrintTree(self):\n if self.left:\n self.left.PrintTree()\n print( self.data),\n if self.right:\n self.right.PrintTree()\n\n# Use the insert method to add nodes\nroot = Node(12)\nroot.insert(6)\nroot.insert(14)\nroot.insert(3)\nroot.PrintTree()" }, { "code": null, "e": 67801, "s": 67733, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 67812, "s": 67801, "text": "3 6 12 14\n" }, { "code": null, "e": 68131, "s": 67812, "text": "The tree can be traversed by deciding on a sequence to visit each node. As we can clearly see we can start at a node then visit the left sub-tree first and right sub-tree next. Or we can also visit the right sub-tree first and left sub-tree next. Accordingly there are different names for these tree traversal methods." }, { "code": null, "e": 68420, "s": 68131, "text": "Traversal is a process to visit all the nodes of a tree and may print their values too. Because, all nodes are connected via edges (links) we always start from the root (head) node. That is, we cannot randomly access a node in a tree. There are three ways which we use to traverse a tree." }, { "code": null, "e": 68439, "s": 68420, "text": "In-order Traversal" }, { "code": null, "e": 68458, "s": 68439, "text": "In-order Traversal" }, { "code": null, "e": 68478, "s": 68458, "text": "Pre-order Traversal" }, { "code": null, "e": 68498, "s": 68478, "text": "Pre-order Traversal" }, { "code": null, "e": 68519, "s": 68498, "text": "Post-order Traversal" }, { "code": null, "e": 68540, "s": 68519, "text": "Post-order Traversal" }, { "code": null, "e": 68719, "s": 68540, "text": "In this traversal method, the left subtree is visited first, then the root and later the right sub-tree. We should always remember that every node may represent a subtree itself." }, { "code": null, "e": 69056, "s": 68719, "text": "In the below python program, we use the Node class to create place holders for the root node as well as the left and right nodes. Then, we create an insert function to add data to the tree. Finally, the In-order traversal logic is implemented by creating an empty list and adding the left node first followed by the root or parent node." }, { "code": null, "e": 69218, "s": 69056, "text": "At last the left node is added to complete the In-order traversal. Please note that this process is repeated for each sub-tree until all the nodes are traversed." }, { "code": null, "e": 70334, "s": 69218, "text": "class Node:\n def __init__(self, data):\n self.left = None\n self.right = None\n self.data = data\n# Insert Node\n def insert(self, data):\n if self.data:\n if data < self.data:\n if self.left is None:\n self.left = Node(data)\n else:\n self.left.insert(data)\n else data > self.data:\n if self.right is None:\n self.right = Node(data)\n else:\n self.right.insert(data)\n else:\n self.data = data\n# Print the Tree\n def PrintTree(self):\n if self.left:\n self.left.PrintTree()\n print( self.data),\n if self.right:\n self.right.PrintTree()\n# Inorder traversal\n# Left -> Root -> Right\n def inorderTraversal(self, root):\n res = []\n if root:\n res = self.inorderTraversal(root.left)\n res.append(root.data)\n res = res + self.inorderTraversal(root.right)\n return res\nroot = Node(27)\nroot.insert(14)\nroot.insert(35)\nroot.insert(10)\nroot.insert(19)\nroot.insert(31)\nroot.insert(42)\nprint(root.inorderTraversal(root)) " }, { "code": null, "e": 70402, "s": 70334, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 70432, "s": 70402, "text": "[10, 14, 19, 27, 31, 35, 42]\n" }, { "code": null, "e": 70543, "s": 70432, "text": "In this traversal method, the root node is visited first, then the left subtree and finally the right subtree." }, { "code": null, "e": 70871, "s": 70543, "text": "In the below python program, we use the Node class to create place holders for the root node as well as the left and right nodes. Then, we create an insert function to add data to the tree. Finally, the Pre-order traversal logic is implemented by creating an empty list and adding the root node first followed by the left node." }, { "code": null, "e": 71037, "s": 70871, "text": "At last, the right node is added to complete the Pre-order traversal. Please note that, this process is repeated for each sub-tree until all the nodes are traversed." }, { "code": null, "e": 72163, "s": 71037, "text": "class Node:\n def __init__(self, data):\n self.left = None\n self.right = None\n self.data = data\n# Insert Node\n def insert(self, data):\n if self.data:\n if data < self.data:\n if self.left is None:\n self.left = Node(data)\n else:\n self.left.insert(data)\n elif data > self.data:\n if self.right is None:\n self.right = Node(data)\n else:\n self.right.insert(data)\n else:\n self.data = data\n# Print the Tree\n def PrintTree(self):\n if self.left:\n self.left.PrintTree()\n print( self.data),\n if self.right:\n self.right.PrintTree()\n# Preorder traversal\n# Root -> Left ->Right\n def PreorderTraversal(self, root):\n res = []\n if root:\n res.append(root.data)\n res = res + self.PreorderTraversal(root.left)\n res = res + self.PreorderTraversal(root.right)\n return res\nroot = Node(27)\nroot.insert(14)\nroot.insert(35)\nroot.insert(10)\nroot.insert(19)\nroot.insert(31)\nroot.insert(42)\nprint(root.PreorderTraversal(root))" }, { "code": null, "e": 72231, "s": 72163, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 72261, "s": 72231, "text": "[27, 14, 10, 19, 35, 31, 42]\n" }, { "code": null, "e": 72421, "s": 72261, "text": "In this traversal method, the root node is visited last, hence the name. First, we traverse the left subtree, then the right subtree and finally the root node." }, { "code": null, "e": 72751, "s": 72421, "text": "In the below python program, we use the Node class to create place holders for the root node as well as the left and right nodes. Then, we create an insert function to add data to the tree. Finally, the Post-order traversal logic is implemented by creating an empty list and adding the left node first followed by the right node." }, { "code": null, "e": 72926, "s": 72751, "text": "At last the root or parent node is added to complete the Post-order traversal. Please note that, this process is repeated for each sub-tree until all the nodes are traversed." }, { "code": null, "e": 73980, "s": 72926, "text": "class Node:\n def __init__(self, data):\n self.left = None\n self.right = None\n self.data = data\n# Insert Node\n def insert(self, data):\n if self.data:\n if data < self.data:\n if self.left is None:\n self.left = Node(data)\n else:\n self.left.insert(data)\n else if data > self.data:\n if self.right is None:\n self.right = Node(data)\n else:\n\n self.right.insert(data)\n else:\n self.data = data\n# Print the Tree\n def PrintTree(self):\n if self.left:\n self.left.PrintTree()\nprint( self.data),\nif self.right:\nself.right.PrintTree()\n# Postorder traversal\n# Left ->Right -> Root\ndef PostorderTraversal(self, root):\nres = []\nif root:\nres = self.PostorderTraversal(root.left)\nres = res + self.PostorderTraversal(root.right)\nres.append(root.data)\nreturn res\nroot = Node(27)\nroot.insert(14)\nroot.insert(35)\nroot.insert(10)\nroot.insert(19)\nroot.insert(31)\nroot.insert(42)\nprint(root.PostorderTraversal(root))" }, { "code": null, "e": 74048, "s": 73980, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 74078, "s": 74048, "text": "[10, 19, 14, 31, 42, 35, 27]\n" }, { "code": null, "e": 74431, "s": 74078, "text": "A Binary Search Tree (BST) is a tree in which all the nodes follow the below-mentioned properties.The left sub-tree of a node has a key less than or equal to its parent node's key.The right sub-tree of a node has a key greater than to its parent node's key.Thus, BST divides all its sub-trees into two segments; the left sub-tree and the right sub-tree" }, { "code": null, "e": 74492, "s": 74431, "text": "left_subtree (keys) ≤ node (key) ≤ right_subtree (keys)\n" }, { "code": null, "e": 74817, "s": 74492, "text": "Searching for a value in a tree involves comparing the incoming value with the value exiting nodes. Here also we traverse the nodes from left to right and then finally with the parent. If the searched for value does not match any of the exiting value, then we return not found message, or else the found message is returned." }, { "code": null, "e": 76116, "s": 74817, "text": "class Node:\n def __init__(self, data):\n self.left = None\n self.right = None\n self.data = data\n# Insert method to create nodes\n def insert(self, data):\n if self.data:\n if data < self.data:\n if self.left is None:\n self.left = Node(data)\n else:\n self.left.insert(data)\n else data > self.data:\n if self.right is None:\n self.right = Node(data)\n else:\n self.right.insert(data)\n else:\n self.data = data\n# findval method to compare the value with nodes\n def findval(self, lkpval):\n if lkpval < self.data:\n if self.left is None:\n return str(lkpval)+\" Not Found\"\n return self.left.findval(lkpval)\n else if lkpval > self.data:\n if self.right is None:\n return str(lkpval)+\" Not Found\"\n return self.right.findval(lkpval)\n else:\n print(str(self.data) + ' is found')\n# Print the tree\n def PrintTree(self):\n if self.left:\n self.left.PrintTree()\n print( self.data),\n if self.right:\n self.right.PrintTree()\nroot = Node(12)\nroot.insert(6)\nroot.insert(14)\nroot.insert(3)\nprint(root.findval(7))\nprint(root.findval(14))" }, { "code": null, "e": 76184, "s": 76116, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 76209, "s": 76184, "text": "7 Not Found\n14 is found\n" }, { "code": null, "e": 76563, "s": 76209, "text": "Heap is a special tree structure in which each parent node is less than or equal to its child node. Then it is called a Min Heap. If each parent node is greater than or equal to its child node then it is called a max heap. It is very useful is implementing priority queues where the queue item with higher weightage is given more priority in processing." }, { "code": null, "e": 76773, "s": 76563, "text": "A detailed discussion on heaps is available in our website here. Please study it first if you are new to heap data structure. In this chapter we will see the implementation of heap data structure using python." }, { "code": null, "e": 76970, "s": 76773, "text": "A heap is created by using python’s inbuilt library named heapq. This library has the relevant functions to carry out various operations on heap data structure. Below is a list of these functions." }, { "code": null, "e": 77167, "s": 76970, "text": "heapify − This function converts a regular list to a heap. In the resulting heap the smallest element gets pushed to the index position 0. But rest of the data elements are not necessarily sorted." }, { "code": null, "e": 77364, "s": 77167, "text": "heapify − This function converts a regular list to a heap. In the resulting heap the smallest element gets pushed to the index position 0. But rest of the data elements are not necessarily sorted." }, { "code": null, "e": 77452, "s": 77364, "text": "heappush − This function adds an element to the heap without altering the current heap." }, { "code": null, "e": 77540, "s": 77452, "text": "heappush − This function adds an element to the heap without altering the current heap." }, { "code": null, "e": 77613, "s": 77540, "text": "heappop − This function returns the smallest data element from the heap." }, { "code": null, "e": 77686, "s": 77613, "text": "heappop − This function returns the smallest data element from the heap." }, { "code": null, "e": 77792, "s": 77686, "text": "heapreplace − This function replaces the smallest data element with a new value supplied in the function." }, { "code": null, "e": 77898, "s": 77792, "text": "heapreplace − This function replaces the smallest data element with a new value supplied in the function." }, { "code": null, "e": 78130, "s": 77898, "text": "A heap is created by simply using a list of elements with the heapify function. In the below example we supply a list of elements and the heapify function rearranges the elements bringing the smallest element to the first position." }, { "code": null, "e": 78231, "s": 78130, "text": "import heapq\n\nH = [21,1,45,78,3,5]\n# Use heapify to rearrange the elements\nheapq.heapify(H)\nprint(H)" }, { "code": null, "e": 78299, "s": 78231, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 78322, "s": 78299, "text": "[1, 3, 5, 78, 21, 45]\n" }, { "code": null, "e": 78568, "s": 78322, "text": "Inserting a data element to a heap always adds the element at the last index. But you can apply heapify function again to bring the newly added element to the first index only if it smallest in value. In the below example we insert the number 8." }, { "code": null, "e": 78692, "s": 78568, "text": "import heapq\n\nH = [21,1,45,78,3,5]\n# Covert to a heap\nheapq.heapify(H)\nprint(H)\n\n# Add element\nheapq.heappush(H,8)\nprint(H)" }, { "code": null, "e": 78760, "s": 78692, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 78808, "s": 78760, "text": "[1, 3, 5, 78, 21, 45]\n[1, 3, 5, 78, 21, 45, 8]\n" }, { "code": null, "e": 78964, "s": 78808, "text": "You can remove the element at first index by using this function. In the below example the function will always remove the element at the index position 1." }, { "code": null, "e": 79103, "s": 78964, "text": "import heapq\n\nH = [21,1,45,78,3,5]\n# Create the heap\n\nheapq.heapify(H)\nprint(H)\n\n# Remove element from the heap\nheapq.heappop(H)\n\nprint(H)" }, { "code": null, "e": 79171, "s": 79103, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 79213, "s": 79171, "text": "[1, 3, 5, 78, 21, 45]\n[3, 21, 5, 78, 45]\n" }, { "code": null, "e": 79362, "s": 79213, "text": "The heap replace function always removes the smallest element of the heap and inserts the new incoming element at some place not fixed by any order." }, { "code": null, "e": 79496, "s": 79362, "text": "import heapq\n\nH = [21,1,45,78,3,5]\n# Create the heap\n\nheapq.heapify(H)\nprint(H)\n\n# Replace an element\nheapq.heapreplace(H,6)\nprint(H)" }, { "code": null, "e": 79564, "s": 79496, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 79609, "s": 79564, "text": "[1, 3, 5, 78, 21, 45]\n[3, 6, 5, 78, 21, 45]\n" }, { "code": null, "e": 79963, "s": 79609, "text": "A graph is a pictorial representation of a set of objects where some pairs of objects are connected by links. The interconnected objects are represented by points termed as vertices, and the links that connect the vertices are called edges. The various terms and functionalities associated with a graph is described in great detail in our tutorial here." }, { "code": null, "e": 80138, "s": 79963, "text": "In this chapter we are going to see how to create a graph and add various data elements to it using a python program. Following are the basic operations we perform on graphs." }, { "code": null, "e": 80161, "s": 80138, "text": "Display graph vertices" }, { "code": null, "e": 80181, "s": 80161, "text": "Display graph edges" }, { "code": null, "e": 80194, "s": 80181, "text": "Add a vertex" }, { "code": null, "e": 80206, "s": 80194, "text": "Add an edge" }, { "code": null, "e": 80223, "s": 80206, "text": "Creating a graph" }, { "code": null, "e": 80442, "s": 80223, "text": "A graph can be easily presented using the python dictionary data types. We represent the vertices as the keys of the dictionary and the connection between the vertices also called edges as the values in the dictionary." }, { "code": null, "e": 80479, "s": 80442, "text": "Take a look at the following graph −" }, { "code": null, "e": 80499, "s": 80479, "text": "In the above graph," }, { "code": null, "e": 80545, "s": 80499, "text": "V = {a, b, c, d, e}\nE = {ab, ac, bd, cd, de}\n" }, { "code": null, "e": 80602, "s": 80545, "text": "We can present this graph in a python program as below −" }, { "code": null, "e": 80787, "s": 80602, "text": "# Create the dictionary with graph elements\ngraph = { \n \"a\" : [\"b\",\"c\"],\n \"b\" : [\"a\", \"d\"],\n \"c\" : [\"a\", \"d\"],\n \"d\" : [\"e\"],\n \"e\" : [\"d\"]\n}\n# Print the graph \t\t \nprint(graph)" }, { "code": null, "e": 80855, "s": 80787, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 80932, "s": 80855, "text": "{'c': ['a', 'd'], 'a': ['b', 'c'], 'e': ['d'], 'd': ['e'], 'b': ['a', 'd']}\n" }, { "code": null, "e": 81037, "s": 80932, "text": "To display the graph vertices we simple find the keys of the graph dictionary. We use the keys() method." }, { "code": null, "e": 81457, "s": 81037, "text": "class graph:\n def __init__(self,gdict=None):\n if gdict is None:\n gdict = []\n self.gdict = gdict\n# Get the keys of the dictionary\n def getVertices(self):\n return list(self.gdict.keys())\n# Create the dictionary with graph elements\ngraph_elements = { \n \"a\" : [\"b\",\"c\"],\n \"b\" : [\"a\", \"d\"],\n \"c\" : [\"a\", \"d\"],\n \"d\" : [\"e\"],\n \"e\" : [\"d\"]\n}\ng = graph(graph_elements)\nprint(g.getVertices())" }, { "code": null, "e": 81525, "s": 81457, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 81552, "s": 81525, "text": "['d', 'b', 'e', 'c', 'a']\n" }, { "code": null, "e": 81889, "s": 81552, "text": "Finding the graph edges is little tricker than the vertices as we have to find each of the pairs of vertices which have an edge in between them. So we create an empty list of edges then iterate through the edge values associated with each of the vertices. A list is formed containing the distinct group of edges found from the vertices." }, { "code": null, "e": 82526, "s": 81889, "text": "class graph:\n def __init__(self,gdict=None):\n if gdict is None:\n gdict = {}\n self.gdict = gdict\n\n def edges(self):\n return self.findedges()\n# Find the distinct list of edges\n def findedges(self):\n edgename = []\n for vrtx in self.gdict:\n for nxtvrtx in self.gdict[vrtx]:\n if {nxtvrtx, vrtx} not in edgename:\n edgename.append({vrtx, nxtvrtx})\n return edgename\n# Create the dictionary with graph elements\ngraph_elements = { \n \"a\" : [\"b\",\"c\"],\n \"b\" : [\"a\", \"d\"],\n \"c\" : [\"a\", \"d\"],\n \"d\" : [\"e\"],\n \"e\" : [\"d\"]\n}\ng = graph(graph_elements)\nprint(g.edges())" }, { "code": null, "e": 82594, "s": 82526, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 82656, "s": 82594, "text": "[{'b', 'a'}, {'b', 'd'}, {'e', 'd'}, {'a', 'c'}, {'c', 'd'}]\n" }, { "code": null, "e": 82753, "s": 82656, "text": "Adding a vertex is straight forward where we add another additional key to the graph dictionary." }, { "code": null, "e": 83277, "s": 82753, "text": "class graph:\n def __init__(self,gdict=None):\n if gdict is None:\n gdict = {}\n self.gdict = gdict\n def getVertices(self):\n return list(self.gdict.keys())\n# Add the vertex as a key\n def addVertex(self, vrtx):\n if vrtx not in self.gdict:\n self.gdict[vrtx] = []\n# Create the dictionary with graph elements\ngraph_elements = { \n \"a\" : [\"b\",\"c\"],\n \"b\" : [\"a\", \"d\"],\n \"c\" : [\"a\", \"d\"],\n \"d\" : [\"e\"],\n \"e\" : [\"d\"]\n}\ng = graph(graph_elements)\ng.addVertex(\"f\")\nprint(g.getVertices())" }, { "code": null, "e": 83345, "s": 83277, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 83376, "s": 83345, "text": "['f', 'e', 'b', 'a', 'c','d']\n" }, { "code": null, "e": 83534, "s": 83376, "text": "Adding an edge to an existing graph involves treating the new vertex as a tuple and validating if the edge is already present. If not then the edge is added." }, { "code": null, "e": 84427, "s": 83534, "text": "class graph:\n def __init__(self,gdict=None):\n if gdict is None:\n gdict = {}\n self.gdict = gdict\n def edges(self):\n return self.findedges()\n# Add the new edge\n def AddEdge(self, edge):\n edge = set(edge)\n (vrtx1, vrtx2) = tuple(edge)\n if vrtx1 in self.gdict:\n self.gdict[vrtx1].append(vrtx2)\n else:\n self.gdict[vrtx1] = [vrtx2]\n# List the edge names\n def findedges(self):\n edgename = []\n for vrtx in self.gdict:\n for nxtvrtx in self.gdict[vrtx]:\n if {nxtvrtx, vrtx} not in edgename:\n edgename.append({vrtx, nxtvrtx})\n return edgename\n# Create the dictionary with graph elements\ngraph_elements = { \n \"a\" : [\"b\",\"c\"],\n \"b\" : [\"a\", \"d\"],\n \"c\" : [\"a\", \"d\"],\n \"d\" : [\"e\"],\n \"e\" : [\"d\"]\n}\ng = graph(graph_elements)\ng.AddEdge({'a','e'})\ng.AddEdge({'a','c'})\nprint(g.edges())" }, { "code": null, "e": 84495, "s": 84427, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 84569, "s": 84495, "text": "[{'e', 'd'}, {'b', 'a'}, {'b', 'd'}, {'a', 'c'}, {'a', 'e'}, {'c', 'd'}]\n" }, { "code": null, "e": 84851, "s": 84569, "text": "Algorithm is a step-by-step procedure, which defines a set of instructions to be executed in a certain order to get the desired output. Algorithms are generally created independent of underlying languages, i.e. an algorithm can be implemented in more than one programming language." }, { "code": null, "e": 84946, "s": 84851, "text": "From the data structure point of view, following are some important categories of algorithms −" }, { "code": null, "e": 85004, "s": 84946, "text": "Search − Algorithm to search an item in a data structure." }, { "code": null, "e": 85062, "s": 85004, "text": "Search − Algorithm to search an item in a data structure." }, { "code": null, "e": 85113, "s": 85062, "text": "Sort − Algorithm to sort items in a certain order." }, { "code": null, "e": 85164, "s": 85113, "text": "Sort − Algorithm to sort items in a certain order." }, { "code": null, "e": 85219, "s": 85164, "text": "Insert − Algorithm to insert item in a data structure." }, { "code": null, "e": 85274, "s": 85219, "text": "Insert − Algorithm to insert item in a data structure." }, { "code": null, "e": 85342, "s": 85274, "text": "Update − Algorithm to update an existing item in a data structure." }, { "code": null, "e": 85410, "s": 85342, "text": "Update − Algorithm to update an existing item in a data structure." }, { "code": null, "e": 85479, "s": 85410, "text": "Delete − Algorithm to delete an existing item from a data structure." }, { "code": null, "e": 85548, "s": 85479, "text": "Delete − Algorithm to delete an existing item from a data structure." }, { "code": null, "e": 85652, "s": 85548, "text": "Not all procedures can be called an algorithm. An algorithm should have the following characteristics −" }, { "code": null, "e": 85816, "s": 85652, "text": "Unambiguous − Algorithm should be clear and unambiguous. Each of its steps (or phases), and their inputs/outputs should be clear and must lead to only one meaning." }, { "code": null, "e": 85980, "s": 85816, "text": "Unambiguous − Algorithm should be clear and unambiguous. Each of its steps (or phases), and their inputs/outputs should be clear and must lead to only one meaning." }, { "code": null, "e": 86044, "s": 85980, "text": "Input − An algorithm should have 0 or more well-defined inputs." }, { "code": null, "e": 86108, "s": 86044, "text": "Input − An algorithm should have 0 or more well-defined inputs." }, { "code": null, "e": 86211, "s": 86108, "text": "Output − An algorithm should have 1 or more well-defined outputs, and should match the desired output." }, { "code": null, "e": 86314, "s": 86211, "text": "Output − An algorithm should have 1 or more well-defined outputs, and should match the desired output." }, { "code": null, "e": 86385, "s": 86314, "text": "Finiteness − Algorithms must terminate after a finite number of steps." }, { "code": null, "e": 86456, "s": 86385, "text": "Finiteness − Algorithms must terminate after a finite number of steps." }, { "code": null, "e": 86519, "s": 86456, "text": "Feasibility − Should be feasible with the available resources." }, { "code": null, "e": 86582, "s": 86519, "text": "Feasibility − Should be feasible with the available resources." }, { "code": null, "e": 86699, "s": 86582, "text": "Independent − An algorithm should have step-by-step directions, which should be independent of any programming code." }, { "code": null, "e": 86816, "s": 86699, "text": "Independent − An algorithm should have step-by-step directions, which should be independent of any programming code." }, { "code": null, "e": 86993, "s": 86816, "text": "There are no well-defined standards for writing algorithms. Rather, it is problem and resource dependent. Algorithms are never written to support a particular programming code." }, { "code": null, "e": 87180, "s": 86993, "text": "As we know that all programming languages share basic code constructs like loops (do, for, while), flow-control (if-else), etc. These common constructs can be used to write an algorithm." }, { "code": null, "e": 87429, "s": 87180, "text": "We write algorithms in a step-by-step manner, but it is not always the case. Algorithm writing is a process and is executed after the problem domain is well-defined. That is, we should know the problem domain, for which we are designing a solution." }, { "code": null, "e": 87487, "s": 87429, "text": "Let's try to learn algorithm-writing by using an example." }, { "code": null, "e": 87560, "s": 87487, "text": "Problem − Design an algorithm to add two numbers and display the result." }, { "code": null, "e": 87633, "s": 87560, "text": "Problem − Design an algorithm to add two numbers and display the result." }, { "code": null, "e": 87648, "s": 87633, "text": "step 1 − START" }, { "code": null, "e": 87689, "s": 87648, "text": "step 2 − declare three integers a, b & c" }, { "code": null, "e": 87721, "s": 87689, "text": "step 3 − define values of a & b" }, { "code": null, "e": 87750, "s": 87721, "text": "step 4 − add values of a & b" }, { "code": null, "e": 87787, "s": 87750, "text": "step 5 − store output of step 4 to c" }, { "code": null, "e": 87804, "s": 87787, "text": "step 6 − print c" }, { "code": null, "e": 87818, "s": 87804, "text": "step 7 − STOP" }, { "code": null, "e": 87924, "s": 87818, "text": "Algorithms tell the programmers how to code the program. Alternatively, the algorithm can be written as −" }, { "code": null, "e": 87943, "s": 87924, "text": "step 1 − START ADD" }, { "code": null, "e": 87972, "s": 87943, "text": "step 2 − get values of a & b" }, { "code": null, "e": 87991, "s": 87972, "text": "step 3 − c ← a + b" }, { "code": null, "e": 88010, "s": 87991, "text": "step 4 − display c" }, { "code": null, "e": 88024, "s": 88010, "text": "step 5 − STOP" }, { "code": null, "e": 88293, "s": 88024, "text": "In design and analysis of algorithms, usually the second method is used to describe an algorithm. It makes it easy for the analyst to analyze the algorithm ignoring all unwanted definitions. He can observe what operations are being used and how the process is flowing." }, { "code": null, "e": 88328, "s": 88293, "text": "Writing step numbers, is optional." }, { "code": null, "e": 88436, "s": 88328, "text": "We design an algorithm to get a solution of a given problem. A problem can be solved in more than one ways." }, { "code": null, "e": 88609, "s": 88436, "text": "Hence, many solution algorithms can be derived for a given problem. The next step is to analyze those proposed solution algorithms and implement the best suitable solution." }, { "code": null, "e": 89063, "s": 88609, "text": "In divide and conquer approach, the problem in hand, is divided into smaller sub-problems and then each problem is solved independently. When we keep on dividing the subproblems into even smaller sub-problems, we may eventually reach a stage where no more division is possible. Those \"atomic\" smallest possible sub-problem (fractions) are solved. The solution of all sub-problems is finally merged in order to obtain the solution of an original problem." }, { "code": null, "e": 89143, "s": 89063, "text": "Broadly, we can understand divide-and-conquer approach in a three-step process." }, { "code": null, "e": 89489, "s": 89143, "text": "This step involves breaking the problem into smaller sub-problems. Sub-problems should represent a part of the original problem. This step generally takes a recursive approach to divide the problem until no sub-problem is further divisible. At this stage, sub-problems become atomic in nature but still represent some part of the actual problem." }, { "code": null, "e": 89629, "s": 89489, "text": "This step receives a lot of smaller sub-problems to be solved. Generally, at this level, the problems are considered 'solved' on their own." }, { "code": null, "e": 89877, "s": 89629, "text": "When the smaller sub-problems are solved, this stage recursively combines them until they formulate a solution of the original problem. This algorithmic approach works recursively and conquer &s; merge steps works so close that they appear as one." }, { "code": null, "e": 90009, "s": 89877, "text": "The following program is an example of divide-and-conquer programming approach where the binary search is implemented using python." }, { "code": null, "e": 90374, "s": 90009, "text": "In binary search we take a sorted list of elements and start looking for an element at the middle of the list. If the search value matches with the middle value in the list we complete the search. Otherwise we eleminate half of the list of elements by choosing whether to procees with the right or left half of the list depending on the value of the item searched." }, { "code": null, "e": 90631, "s": 90374, "text": "This is possible as the list is sorted and it is much quicker than linear search.Here we divide the given list and conquer by choosing the proper half of the list. We repeat this approcah till we find the element or conclude about it's absence in the list." }, { "code": null, "e": 91145, "s": 90631, "text": "def bsearch(list, val):\n list_size = len(list) - 1\n idx0 = 0\n idxn = list_size\n# Find the middle most value\n while idx0 <= idxn:\n midval = (idx0 + idxn)// 2\n if list[midval] == val:\n return midval\n# Compare the value the middle most value\n if val > list[midval]:\n idx0 = midval + 1\n else:\n idxn = midval - 1\n if idx0 > idxn:\n return None\n# Initialize the sorted list\nlist = [2,7,19,34,53,72]\n\n# Print the search result\nprint(bsearch(list,72))\nprint(bsearch(list,11))" }, { "code": null, "e": 91213, "s": 91145, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 91221, "s": 91213, "text": "5\nNone\n" }, { "code": null, "e": 91556, "s": 91221, "text": "Recursion allows a function to call itself. Fixed steps of code get executed again and again for new values. We also have to set criteria for deciding when the recursive call ends. In the below example we see a recursive approach to the binary search. We take a sorted list and give its index range as input to the recursive function." }, { "code": null, "e": 91878, "s": 91556, "text": "We implement the algorithm of binary search using python as shown below. We use an ordered list of items and design a recursive function to take in the list along with starting and ending index as input. Then, the binary search function calls itself till find the searched item or concludes about its absence in the list." }, { "code": null, "e": 92324, "s": 91878, "text": "def bsearch(list, idx0, idxn, val):\n if (idxn < idx0):\n return None\n else:\n midval = idx0 + ((idxn - idx0) // 2)\n# Compare the search item with middle most value\n if list[midval] > val:\n return bsearch(list, idx0, midval-1,val)\n else if list[midval] < val:\n return bsearch(list, midval+1, idxn, val)\n else:\n return midval\nlist = [8,11,24,56,88,131]\nprint(bsearch(list, 0, 5, 24))\nprint(bsearch(list, 0, 5, 51))" }, { "code": null, "e": 92392, "s": 92324, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 92400, "s": 92392, "text": "2\nNone\n" }, { "code": null, "e": 92750, "s": 92400, "text": "Backtracking is a form of recursion. But it involves choosing only option out of any possibilities. We begin by choosing an option and backtrack from it, if we reach a state where we conclude that this specific option does not give the required solution. We repeat these steps by going across each available option until we get the desired solution." }, { "code": null, "e": 93030, "s": 92750, "text": "Below is an example of finding all possible order of arrangements of a given set of letters. When we choose a pair we apply backtracking to verify if that exact pair has already been created or not. If not already created, the pair is added to the answer list else it is ignored." }, { "code": null, "e": 93269, "s": 93030, "text": "def permute(list, s):\n if list == 1:\n return s\n else:\n return [ \n y + x\n for y in permute(1, s)\n for x in permute(list - 1, s)\n ]\nprint(permute(1, [\"a\",\"b\",\"c\"]))\nprint(permute(2, [\"a\",\"b\",\"c\"]))" }, { "code": null, "e": 93337, "s": 93269, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 93409, "s": 93337, "text": "['a', 'b', 'c']\n['aa', 'ab', 'ac', 'ba', 'bb', 'bc', 'ca', 'cb', 'cc']\n" }, { "code": null, "e": 93603, "s": 93409, "text": "Sorting refers to arranging data in a particular format. Sorting algorithm specifies the way to arrange data in a particular order. Most common orders are in numerical or lexicographical order." }, { "code": null, "e": 93869, "s": 93603, "text": "The importance of sorting lies in the fact that data searching can be optimized to a very high level, if data is stored in a sorted manner. Sorting is also used to represent data in more readable formats. Below we see five such implementations of sorting in python." }, { "code": null, "e": 93881, "s": 93869, "text": "Bubble Sort" }, { "code": null, "e": 93893, "s": 93881, "text": "Bubble Sort" }, { "code": null, "e": 93904, "s": 93893, "text": "Merge Sort" }, { "code": null, "e": 93915, "s": 93904, "text": "Merge Sort" }, { "code": null, "e": 93930, "s": 93915, "text": "Insertion Sort" }, { "code": null, "e": 93945, "s": 93930, "text": "Insertion Sort" }, { "code": null, "e": 93956, "s": 93945, "text": "Shell Sort" }, { "code": null, "e": 93967, "s": 93956, "text": "Shell Sort" }, { "code": null, "e": 93982, "s": 93967, "text": "Selection Sort" }, { "code": null, "e": 93997, "s": 93982, "text": "Selection Sort" }, { "code": null, "e": 94139, "s": 93997, "text": "It is a comparison-based algorithm in which each pair of adjacent elements is compared and the elements are swapped if they are not in order." }, { "code": null, "e": 94472, "s": 94139, "text": "def bubblesort(list):\n\n# Swap the elements to arrange in order\n for iter_num in range(len(list)-1,0,-1):\n for idx in range(iter_num):\n if list[idx]>list[idx+1]:\n temp = list[idx]\n list[idx] = list[idx+1]\n list[idx+1] = temp\nlist = [19,2,31,45,6,11,121,27]\nbubblesort(list)\nprint(list)" }, { "code": null, "e": 94540, "s": 94472, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 94573, "s": 94540, "text": "[2, 6, 11, 19, 27, 31, 45, 121]\n" }, { "code": null, "e": 94669, "s": 94573, "text": "Merge sort first divides the array into equal halves and then combines them in a sorted manner." }, { "code": null, "e": 95545, "s": 94669, "text": "def merge_sort(unsorted_list):\n if len(unsorted_list) <= 1:\n return unsorted_list\n# Find the middle point and devide it\n middle = len(unsorted_list) // 2\n left_list = unsorted_list[:middle]\n right_list = unsorted_list[middle:]\n\n left_list = merge_sort(left_list)\n right_list = merge_sort(right_list)\n return list(merge(left_list, right_list))\n\n# Merge the sorted halves\ndef merge(left_half,right_half):\n res = []\n while len(left_half) != 0 and len(right_half) != 0:\n if left_half[0] < right_half[0]:\n res.append(left_half[0])\n left_half.remove(left_half[0])\n else:\n res.append(right_half[0])\n right_half.remove(right_half[0])\n if len(left_half) == 0:\n res = res + right_half\n else:\n res = res + left_half\n return res\nunsorted_list = [64, 34, 25, 12, 22, 11, 90]\nprint(merge_sort(unsorted_list))" }, { "code": null, "e": 95613, "s": 95545, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 95643, "s": 95613, "text": "[11, 12, 22, 25, 34, 64, 90]\n" }, { "code": null, "e": 96030, "s": 95643, "text": "Insertion sort involves finding the right place for a given element in a sorted list. So in beginning we compare the first two elements and sort them by comparing them. Then we pick the third element and find its proper position among the previous two sorted elements. This way we gradually go on adding more elements to the already sorted list by putting them in their proper position." }, { "code": null, "e": 96388, "s": 96030, "text": "def insertion_sort(InputList):\n for i in range(1, len(InputList)):\n j = i-1\n nxt_element = InputList[i]\n# Compare the current element with next one\n while (InputList[j] > nxt_element) and (j >= 0):\n InputList[j+1] = InputList[j]\n j=j-1\n InputList[j+1] = nxt_element\nlist = [19,2,31,45,30,11,121,27]\ninsertion_sort(list)\nprint(list)" }, { "code": null, "e": 96456, "s": 96388, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 96490, "s": 96456, "text": "[2, 11, 19, 27, 30, 31, 45, 121]\n" }, { "code": null, "e": 96864, "s": 96490, "text": "Shell Sort involves sorting elements which are away from each other. We sort a large sublist of a given list and go on reducing the size of the list until all elements are sorted. The below program finds the gap by equating it to half of the length of the list size and then starts sorting all elements in it. Then we keep resetting the gap until the entire list is sorted." }, { "code": null, "e": 97311, "s": 96864, "text": "def shellSort(input_list):\n gap = len(input_list) // 2\n while gap > 0:\n for i in range(gap, len(input_list)):\n temp = input_list[i]\n j = i\n# Sort the sub list for this gap\n while j >= gap and input_list[j - gap] > temp:\n input_list[j] = input_list[j - gap]\n j = j-gap\n input_list[j] = temp\n# Reduce the gap for the next element\n gap = gap//2\nlist = [19,2,31,45,30,11,121,27]\nshellSort(list)\nprint(list)" }, { "code": null, "e": 97379, "s": 97311, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 97413, "s": 97379, "text": "[2, 11, 19, 27, 30, 31, 45, 121]\n" }, { "code": null, "e": 97782, "s": 97413, "text": "In selection sort we start by finding the minimum value in a given list and move it to a sorted list. Then we repeat the process for each of the remaining elements in the unsorted list. The next element entering the sorted list is compared with the existing elements and placed at its correct position.So, at the end all the elements from the unsorted list are sorted." }, { "code": null, "e": 98175, "s": 97782, "text": "def selection_sort(input_list):\n for idx in range(len(input_list)):\n min_idx = idx\n for j in range( idx +1, len(input_list)):\n if input_list[min_idx] > input_list[j]:\n min_idx = j\n# Swap the minimum value with the compared value\n input_list[idx], input_list[min_idx] = input_list[min_idx], input_list[idx]\nl = [19,2,31,45,30,11,121,27]\nselection_sort(l)\nprint(l)" }, { "code": null, "e": 98243, "s": 98175, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 98277, "s": 98243, "text": "[2, 11, 19, 27, 30, 31, 45, 121]\n" }, { "code": null, "e": 98658, "s": 98277, "text": "Searching is a very basic necessity when you store data in different data structures. The simplest approach is to go across every element in the data structure and match it with the value you are searching for.This is known as Linear search. It is inefficient and rarely used, but creating a program for it gives an idea about how we can implement some advanced search algorithms." }, { "code": null, "e": 98889, "s": 98658, "text": "In this type of search, a sequential search is made over all items one by one. Every item is checked and if a match is found then that particular item is returned, otherwise the search continues till the end of the data structure." }, { "code": null, "e": 99293, "s": 98889, "text": "def linear_search(values, search_for):\n search_at = 0\n search_res = False\n# Match the value with each data element\t\n while search_at < len(values) and search_res is False:\n if values[search_at] == search_for:\n search_res = True\n else:\n search_at = search_at + 1\n return search_res\nl = [64, 34, 25, 12, 22, 11, 90]\nprint(linear_search(l, 12))\nprint(linear_search(l, 91))" }, { "code": null, "e": 99361, "s": 99293, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 99373, "s": 99361, "text": "True\nFalse\n" }, { "code": null, "e": 100013, "s": 99373, "text": "This search algorithm works on the probing position of the required value. For this algorithm to work properly, the data collection should be in a sorted form and equally distributed.Initially, the probe position is the position of the middle most item of the collection.If a match occurs, then the index of the item is returned.If the middle item is greater than the item, then the probe position is again calculated in the sub-array to the right of the middle item. Otherwise, the item is searched in the subarray to the left of the middle item. This process continues on the sub-array as well until the size of subarray reduces to zero." }, { "code": null, "e": 100116, "s": 100013, "text": "There is a specific formula to calculate the middle position which is indicated in the program below −" }, { "code": null, "e": 100660, "s": 100116, "text": "def intpolsearch(values,x ):\n idx0 = 0\n idxn = (len(values) - 1)\n while idx0 <= idxn and x >= values[idx0] and x <= values[idxn]:\n# Find the mid point\n\tmid = idx0 +\\\n int(((float(idxn - idx0)/( values[idxn] - values[idx0]))\n * ( x - values[idx0])))\n# Compare the value at mid point with search value \n if values[mid] == x:\n return \"Found \"+str(x)+\" at index \"+str(mid)\n if values[mid] < x:\n idx0 = mid + 1\n return \"Searched element not in the list\"\n\nl = [2, 6, 11, 19, 27, 31, 45, 121]\nprint(intpolsearch(l, 2))" }, { "code": null, "e": 100728, "s": 100660, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 100748, "s": 100728, "text": "Found 2 at index 0\n" }, { "code": null, "e": 101265, "s": 100748, "text": "Graphs are very useful data structures in solving many important mathematical challenges. For example computer network topology or analysing molecular structures of chemical compounds. They are also used in city traffic or route planning and even in human languages and their grammar. All these applications have a common challenge of traversing the graph using their edges and ensuring that all nodes of the graphs are visited. There are two common established methods to do this traversal which is described below." }, { "code": null, "e": 101625, "s": 101265, "text": "Also called depth first search (DFS),this algorithm traverses a graph in a depth ward motion and uses a stack to remember to get the next vertex to start a search, when a dead end occurs in any iteration. We implement DFS for a graph in python using the set data types as they provide the required functionalities to keep track of visited and unvisited nodes." }, { "code": null, "e": 102145, "s": 101625, "text": "class graph:\n def __init__(self,gdict=None):\n if gdict is None:\n gdict = {}\n self.gdict = gdict\n# Check for the visisted and unvisited nodes\ndef dfs(graph, start, visited = None):\n if visited is None:\n visited = set()\n visited.add(start)\n print(start)\n for next in graph[start] - visited:\n dfs(graph, next, visited)\n return visited\n\ngdict = { \n \"a\" : set([\"b\",\"c\"]),\n \"b\" : set([\"a\", \"d\"]),\n \"c\" : set([\"a\", \"d\"]),\n \"d\" : set([\"e\"]),\n \"e\" : set([\"a\"])\n}\ndfs(gdict, 'a')" }, { "code": null, "e": 102213, "s": 102145, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 102224, "s": 102213, "text": "a b d e c\n" }, { "code": null, "e": 102518, "s": 102224, "text": "Also called breadth first search (BFS),this algorithm traverses a graph breadth ward motion and uses a queue to remember to get the next vertex to start a search, when a dead end occurs in any iteration. Please visit this link in our website to understand the details of BFS steps for a graph." }, { "code": null, "e": 102833, "s": 102518, "text": "We implement BFS for a graph in python using queue data structure discussed earlier. When we keep visiting the adjacent unvisited nodes and keep adding it to the queue. Then we start dequeue only the node which is left with no unvisited nodes. We stop the program when there is no next adjacent node to be visited." }, { "code": null, "e": 103501, "s": 102833, "text": "import collections\nclass graph:\n def __init__(self,gdict=None):\n if gdict is None:\n gdict = {}\n self.gdict = gdict\ndef bfs(graph, startnode):\n# Track the visited and unvisited nodes using queue\n seen, queue = set([startnode]), collections.deque([startnode])\n while queue:\n vertex = queue.popleft()\n marked(vertex)\n for node in graph[vertex]:\n if node not in seen:\n seen.add(node)\n queue.append(node)\n\ndef marked(n):\n print(n)\n\n# The graph dictionary\ngdict = { \n \"a\" : set([\"b\",\"c\"]),\n \"b\" : set([\"a\", \"d\"]),\n \"c\" : set([\"a\", \"d\"]),\n \"d\" : set([\"e\"]),\n \"e\" : set([\"a\"])\n}\nbfs(gdict, \"a\")" }, { "code": null, "e": 103569, "s": 103501, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 103581, "s": 103569, "text": "a c b d e \n" }, { "code": null, "e": 103722, "s": 103581, "text": "Efficiency of an algorithm can be analyzed at two different stages, before implementation and after implementation. They are the following −" }, { "code": null, "e": 103950, "s": 103722, "text": "A Priori Analysis − This is a theoretical analysis of an algorithm. Efficiency of an algorithm is measured by assuming that all other factors, for example, processor speed, are constant and have no effect on the implementation." }, { "code": null, "e": 104178, "s": 103950, "text": "A Priori Analysis − This is a theoretical analysis of an algorithm. Efficiency of an algorithm is measured by assuming that all other factors, for example, processor speed, are constant and have no effect on the implementation." }, { "code": null, "e": 104453, "s": 104178, "text": "A Posterior Analysis − This is an empirical analysis of an algorithm. The selected algorithm is implemented using programming language. This is then executed on target computer machine. In this analysis, actual statistics like running time and space required, are collected." }, { "code": null, "e": 104728, "s": 104453, "text": "A Posterior Analysis − This is an empirical analysis of an algorithm. The selected algorithm is implemented using programming language. This is then executed on target computer machine. In this analysis, actual statistics like running time and space required, are collected." }, { "code": null, "e": 104890, "s": 104728, "text": "Suppose X is an algorithm and n is the size of input data, the time and space used by the algorithm X are the two main factors, which decide the efficiency of X." }, { "code": null, "e": 105008, "s": 104890, "text": "Time Factor − Time is measured by counting the number of key operations such as comparisons in the sorting algorithm." }, { "code": null, "e": 105126, "s": 105008, "text": "Time Factor − Time is measured by counting the number of key operations such as comparisons in the sorting algorithm." }, { "code": null, "e": 105223, "s": 105126, "text": "Space Factor − Space is measured by counting the maximum memory space required by the algorithm." }, { "code": null, "e": 105320, "s": 105223, "text": "Space Factor − Space is measured by counting the maximum memory space required by the algorithm." }, { "code": null, "e": 105471, "s": 105320, "text": "The complexity of an algorithm f(n) gives the running time and/or the storage space required by the algorithm in terms of n as the size of input data." }, { "code": null, "e": 105676, "s": 105471, "text": "Space complexity of an algorithm represents the amount of memory space required by the algorithm in its life cycle. The space required by an algorithm is equal to the sum of the following two components −" }, { "code": null, "e": 105869, "s": 105676, "text": "A fixed part that is a space required to store certain data and variables, that are independent of the size of the problem. For example, simple variables and constants used, program size, etc." }, { "code": null, "e": 106062, "s": 105869, "text": "A fixed part that is a space required to store certain data and variables, that are independent of the size of the problem. For example, simple variables and constants used, program size, etc." }, { "code": null, "e": 106227, "s": 106062, "text": "A variable part is a space required by variables, whose size depends on the size of the problem. For example, dynamic memory allocation, recursion stack space, etc." }, { "code": null, "e": 106392, "s": 106227, "text": "A variable part is a space required by variables, whose size depends on the size of the problem. For example, dynamic memory allocation, recursion stack space, etc." }, { "code": null, "e": 106638, "s": 106392, "text": "Space complexity S(P) of any algorithm P is S(P) = C + SP(I), where C is the fixed part and S(I) is the variable part of the algorithm, which depends on instance characteristic I. Following is a simple example that tries to explain the concept −" }, { "code": null, "e": 106659, "s": 106638, "text": "Algorithm: SUM(A, B)" }, { "code": null, "e": 106674, "s": 106659, "text": "Step 1 − START" }, { "code": null, "e": 106698, "s": 106674, "text": "Step 2 − C ← A + B + 10" }, { "code": null, "e": 106712, "s": 106698, "text": "Step 3 − Stop" }, { "code": null, "e": 106901, "s": 106712, "text": "Here we have three variables A, B, and C and one constant. Hence S(P) = 1 + 3. Now, space depends on data types of given variables and constant types and it will be multiplied accordingly." }, { "code": null, "e": 107168, "s": 106901, "text": "Time complexity of an algorithm represents the amount of time required by the algorithm to run to completion. Time requirements can be defined as a numerical function T(n), where T(n) can be measured as the number of steps, provided each step consumes constant time." }, { "code": null, "e": 107414, "s": 107168, "text": "For example, addition of two n-bit integers takes n steps. Consequently, the total computational time is T(n) = c ∗ n, where c is the time taken for the addition of two bits. Here, we observe that T(n) grows linearly as the input size increases." }, { "code": null, "e": 107710, "s": 107414, "text": "The efficiency and accuracy of algorithms have to be analysed to compare them and choose a specific algorithm for certain scenarios. The process of making this analysis is called Asymptotic analysis. It refers to computing the running time of any operation in mathematical units of computation." }, { "code": null, "e": 108116, "s": 107710, "text": "For example, the running time of one operation is computed as f(n) and may be for another operation it is computed as g(n2). This means the first operation running time will increase linearly with the increase in n and the running time of the second operation will increase exponentially when n increases. Similarly, the running time of both operations will be nearly the same if n is significantly small." }, { "code": null, "e": 108185, "s": 108116, "text": "Usually, the time required by an algorithm falls under three types −" }, { "code": null, "e": 108242, "s": 108185, "text": "Best Case − Minimum time required for program execution." }, { "code": null, "e": 108299, "s": 108242, "text": "Best Case − Minimum time required for program execution." }, { "code": null, "e": 108359, "s": 108299, "text": "Average Case − Average time required for program execution." }, { "code": null, "e": 108419, "s": 108359, "text": "Average Case − Average time required for program execution." }, { "code": null, "e": 108477, "s": 108419, "text": "Worst Case − Maximum time required for program execution." }, { "code": null, "e": 108535, "s": 108477, "text": "Worst Case − Maximum time required for program execution." }, { "code": null, "e": 108632, "s": 108535, "text": "The commonly used asymptotic notations to calculate the running time complexity of an algorithm." }, { "code": null, "e": 108643, "s": 108632, "text": "Ο Notation" }, { "code": null, "e": 108654, "s": 108643, "text": "Ο Notation" }, { "code": null, "e": 108665, "s": 108654, "text": "Ω Notation" }, { "code": null, "e": 108676, "s": 108665, "text": "Ω Notation" }, { "code": null, "e": 108687, "s": 108676, "text": "θ Notation" }, { "code": null, "e": 108698, "s": 108687, "text": "θ Notation" }, { "code": null, "e": 108910, "s": 108698, "text": "The notation Ο(n) is the formal way to express the upper bound of an algorithm's running time. It measures the worst case time complexity or the longest amount of time an algorithm can possibly take to complete." }, { "code": null, "e": 108943, "s": 108910, "text": "For example, for a function f(n)" }, { "code": null, "e": 109031, "s": 108943, "text": "Ο(f(n)) = { g(n) : there exists c > 0 and n0 such that f(n) ≤ c.g(n) for all n > n0. }\n" }, { "code": null, "e": 109239, "s": 109031, "text": "The notation Ω(n) is the formal way to express the lower bound of an algorithm's running time. It measures the best case time complexity or the best amount of time an algorithm can possibly take to complete." }, { "code": null, "e": 109272, "s": 109239, "text": "For example, for a function f(n)" }, { "code": null, "e": 109360, "s": 109272, "text": "Ω(f(n)) ≥ { g(n) : there exists c > 0 and n0 such that g(n) ≤ c.f(n) for all n > n0. }\n" }, { "code": null, "e": 109511, "s": 109360, "text": "The notation θ(n) is the formal way to express both the lower bound and the upper bound of an algorithm's running time. It is represented as follows −" }, { "code": null, "e": 109597, "s": 109511, "text": "θ(f(n)) = { g(n) if and only if g(n) = Ο(f(n)) and g(n) = Ω(f(n)) for all n > n0. }\n" }, { "code": null, "e": 109661, "s": 109597, "text": "A list of some common asymptotic notations is mentioned below −" }, { "code": null, "e": 109941, "s": 109661, "text": "Algorithms are unambiguous steps which should give us a well-defined output by processing zero or more inputs. This leads to many approaches in designing and writing the algorithms. It has been observed that most of the algorithms can be classified into the following categories." }, { "code": null, "e": 110142, "s": 109941, "text": "Greedy algorithms try to find a localized optimum solution, which may eventually lead to globally optimized solutions. However, generally greedy algorithms do not provide globally optimized solutions." }, { "code": null, "e": 110373, "s": 110142, "text": "So greedy algorithms look for a easy solution at that point in time without considering how it impacts the future steps. It is similar to how humans solve problems without going through the complete details of the inputs provided." }, { "code": null, "e": 110457, "s": 110373, "text": "Most networking algorithms use the greedy approach. Here is a list of few of them −" }, { "code": null, "e": 110485, "s": 110457, "text": "Travelling Salesman Problem" }, { "code": null, "e": 110513, "s": 110485, "text": "Travelling Salesman Problem" }, { "code": null, "e": 110552, "s": 110513, "text": "Prim's Minimal Spanning Tree Algorithm" }, { "code": null, "e": 110591, "s": 110552, "text": "Prim's Minimal Spanning Tree Algorithm" }, { "code": null, "e": 110633, "s": 110591, "text": "Kruskal's Minimal Spanning Tree Algorithm" }, { "code": null, "e": 110675, "s": 110633, "text": "Kruskal's Minimal Spanning Tree Algorithm" }, { "code": null, "e": 110718, "s": 110675, "text": "Dijkstra's Minimal Spanning Tree Algorithm" }, { "code": null, "e": 110761, "s": 110718, "text": "Dijkstra's Minimal Spanning Tree Algorithm" }, { "code": null, "e": 111059, "s": 110761, "text": "This class of algorithms involve dividing the given problem into smaller sub-problems and then solving each of the sub-problem independently. When the problem can not be further sub divided, we start merging the solution to each of the sub-problem to arrive at the solution for the bigger problem." }, { "code": null, "e": 111121, "s": 111059, "text": "The important examples of divide and conquer algorithms are −" }, { "code": null, "e": 111132, "s": 111121, "text": "Merge Sort" }, { "code": null, "e": 111143, "s": 111132, "text": "Merge Sort" }, { "code": null, "e": 111154, "s": 111143, "text": "Quick Sort" }, { "code": null, "e": 111165, "s": 111154, "text": "Quick Sort" }, { "code": null, "e": 111207, "s": 111165, "text": "Kruskal's Minimal Spanning Tree Algorithm" }, { "code": null, "e": 111249, "s": 111207, "text": "Kruskal's Minimal Spanning Tree Algorithm" }, { "code": null, "e": 111263, "s": 111249, "text": "Binary Search" }, { "code": null, "e": 111277, "s": 111263, "text": "Binary Search" }, { "code": null, "e": 111550, "s": 111277, "text": "Dynamic programming involves dividing the bigger problem into smaller ones but unlike divide and conquer it does not involve solving each sub-problem independently. Rather the results of smaller sub-problems are remembered and used for similar or overlapping sub-problems." }, { "code": null, "e": 111838, "s": 111550, "text": "Mostly, these algorithms are used for optimization. Before solving the in-hand sub-problem, dynamic algorithm will try to examine the results of the previously solved sub-problems.Dynamic algorithms are motivated for an overall optimization of the problem and not the local optimization." }, { "code": null, "e": 111901, "s": 111838, "text": "The important examples of Dynamic programming algorithms are −" }, { "code": null, "e": 111926, "s": 111901, "text": "Fibonacci number series " }, { "code": null, "e": 111951, "s": 111926, "text": "Fibonacci number series " }, { "code": null, "e": 111969, "s": 111951, "text": "Knapsack problem " }, { "code": null, "e": 111987, "s": 111969, "text": "Knapsack problem " }, { "code": null, "e": 112002, "s": 111987, "text": "Tower of Hanoi" }, { "code": null, "e": 112017, "s": 112002, "text": "Tower of Hanoi" }, { "code": null, "e": 112292, "s": 112017, "text": "Amortized analysis involves estimating the run time for the sequence of operations in a program without taking into consideration the span of the data distribution in the input values. A simple example is finding a value in a sorted list is quicker than in an unsorted list." }, { "code": null, "e": 112513, "s": 112292, "text": "If the list is already sorted, it does not matter how distributed the data is. But of course the length of the list has an impact as it decides the number of steps the algorithm has to go through to get the final result." }, { "code": null, "e": 112838, "s": 112513, "text": "So we see that if the initial cost of a single step of obtaining a sorted list is high, then the cost of subsequent steps of finding an element becomes considerably low. So Amortized analysis helps us find a bound on the worst-case running time for a sequence of operations. There are three approaches to amortized analysis." }, { "code": null, "e": 113040, "s": 112838, "text": "Accounting Method − This involves assigning a cost to each operation performed. If the actual operation finishes quicker than the assigned time then some positive credit is accumulated in the analysis." }, { "code": null, "e": 113242, "s": 113040, "text": "Accounting Method − This involves assigning a cost to each operation performed. If the actual operation finishes quicker than the assigned time then some positive credit is accumulated in the analysis." }, { "code": null, "e": 113636, "s": 113242, "text": "In the reverse scenario it will be negative credit. To keep track of these accumulated credits, we use a stack or tree data structure. The operations which are carried out early ( like sorting the list) have high amortized cost but the operations that are late in sequence have lower amortized cost as the accumulated credit is utilized. So the amortized cost is an upper bound of actual cost." }, { "code": null, "e": 114021, "s": 113636, "text": "Potential Method − In this method the saved credit is utilized for future operations as mathematical function of the state of the data structure. The evaluation of the mathematical function and the amortized cost should be equal. So when the actual cost is greater than amortized cost there is a decrease in potential and it is used utilized for future operations which are expensive." }, { "code": null, "e": 114406, "s": 114021, "text": "Potential Method − In this method the saved credit is utilized for future operations as mathematical function of the state of the data structure. The evaluation of the mathematical function and the amortized cost should be equal. So when the actual cost is greater than amortized cost there is a decrease in potential and it is used utilized for future operations which are expensive." }, { "code": null, "e": 114585, "s": 114406, "text": "Aggregate analysis − In this method we estimate the upper bound on the total cost of n steps. The amortized cost is a simple division of total cost and the number of steps (n).." }, { "code": null, "e": 114764, "s": 114585, "text": "Aggregate analysis − In this method we estimate the upper bound on the total cost of n steps. The amortized cost is a simple division of total cost and the number of steps (n).." }, { "code": null, "e": 115102, "s": 114764, "text": "In order to make claims about an Algorithm being efficient we need some mathematical tools as proof. These tools help us on providing a mathematically satisfying explanation on the performance and accuracy of the algorithms. Below is a list of some of those mathematical tools which can be used for justifying one algorithm over another." }, { "code": null, "e": 115347, "s": 115102, "text": "Direct Proof − It is direct verification of the statement by using the direct calculations. For example sum of two even numbers is always an even number. In this case just add the two numbers you are investigating and verify the result as even." }, { "code": null, "e": 115592, "s": 115347, "text": "Direct Proof − It is direct verification of the statement by using the direct calculations. For example sum of two even numbers is always an even number. In this case just add the two numbers you are investigating and verify the result as even." }, { "code": null, "e": 116071, "s": 115592, "text": "Proof by induction − Here we start with a specific instance of a truth and then generalize it to all possible values which are part of the truth. The approach is to take a case of verified truth, then prove it is also true for the next case for the same given condition. For example all positive numbers of the form 2n-1 are odd. We prove it for a certain value of n, then prove it for the next value of n. This establishes the statement as generally true by proof of induction." }, { "code": null, "e": 116550, "s": 116071, "text": "Proof by induction − Here we start with a specific instance of a truth and then generalize it to all possible values which are part of the truth. The approach is to take a case of verified truth, then prove it is also true for the next case for the same given condition. For example all positive numbers of the form 2n-1 are odd. We prove it for a certain value of n, then prove it for the next value of n. This establishes the statement as generally true by proof of induction." }, { "code": null, "e": 116773, "s": 116550, "text": "Proof by contraposition − This proof is based on the condition If Not A implies Not B then A implies B. A simple example is if square of n is even then n must be even. Because if square on n is not even then n is not even." }, { "code": null, "e": 116996, "s": 116773, "text": "Proof by contraposition − This proof is based on the condition If Not A implies Not B then A implies B. A simple example is if square of n is even then n must be even. Because if square on n is not even then n is not even." }, { "code": null, "e": 117183, "s": 116996, "text": "Proof by exhaustion − This is similar to direct proof but it is established by visiting each case separately and proving each of them. An example of such proof is the four color theorem." }, { "code": null, "e": 117370, "s": 117183, "text": "Proof by exhaustion − This is similar to direct proof but it is established by visiting each case separately and proving each of them. An example of such proof is the four color theorem." }, { "code": null, "e": 117407, "s": 117370, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 117423, "s": 117407, "text": " Malhar Lathkar" }, { "code": null, "e": 117456, "s": 117423, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 117475, "s": 117456, "text": " Arnab Chakraborty" }, { "code": null, "e": 117510, "s": 117475, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 117532, "s": 117510, "text": " In28Minutes Official" }, { "code": null, "e": 117566, "s": 117532, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 117594, "s": 117566, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 117629, "s": 117594, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 117643, "s": 117629, "text": " Lets Kode It" }, { "code": null, "e": 117676, "s": 117643, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 117693, "s": 117676, "text": " Abhilash Nelson" }, { "code": null, "e": 117700, "s": 117693, "text": " Print" }, { "code": null, "e": 117711, "s": 117700, "text": " Add Notes" } ]
Java Examples - Printing Array using Method
How to use method overloading for printing different types of array ? This example displays the way of using overloaded method for printing types of array (integer, double and character). public class MainClass { public static void printArray(Integer[] inputArray) { for (Integer element : inputArray){ System.out.printf("%s ", element); System.out.println(); } } public static void printArray(Double[] inputArray) { for (Double element : inputArray){ System.out.printf("%s ", element); System.out.println(); } } public static void printArray(Character[] inputArray) { for (Character element : inputArray){ System.out.printf("%s ", element); System.out.println(); } } public static void main(String args[]) { Integer[] integerArray = { 1, 2, 3, 4, 5, 6 }; Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7 }; Character[] characterArray = { 'H', 'E', 'L', 'L', 'O' }; System.out.println("Array integerArray contains:"); printArray(integerArray); System.out.println("\nArray doubleArray contains:"); printArray(doubleArray); System.out.println("\nArray characterArray contains:"); printArray(characterArray); } } The above code sample will produce the following result. Array integerArray contains: 1 2 3 4 5 6 Array doubleArray contains: 1.1 2.2 3.3 4.4 5.5 6.6 7.7 Array characterArray contains: H E L L O Print Add Notes Bookmark this page
[ { "code": null, "e": 2139, "s": 2068, "text": "How to use method overloading for printing different types of array ?" }, { "code": null, "e": 2257, "s": 2139, "text": "This example displays the way of using overloaded method for printing types of array (integer, double and character)." }, { "code": null, "e": 3378, "s": 2257, "text": "public class MainClass {\n public static void printArray(Integer[] inputArray) {\n for (Integer element : inputArray){\n System.out.printf(\"%s \", element);\n System.out.println();\n }\n }\n public static void printArray(Double[] inputArray) {\n for (Double element : inputArray){\n System.out.printf(\"%s \", element);\n System.out.println();\n }\n }\n public static void printArray(Character[] inputArray) {\n for (Character element : inputArray){\n System.out.printf(\"%s \", element);\n System.out.println();\n }\n }\n public static void main(String args[]) {\n Integer[] integerArray = { 1, 2, 3, 4, 5, 6 };\n Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7 };\n Character[] characterArray = { 'H', 'E', 'L', 'L', 'O' };\n \n System.out.println(\"Array integerArray contains:\");\n printArray(integerArray);\n \n System.out.println(\"\\nArray doubleArray contains:\");\n printArray(doubleArray);\n \n System.out.println(\"\\nArray characterArray contains:\");\n printArray(characterArray);\n }\n}" }, { "code": null, "e": 3435, "s": 3378, "text": "The above code sample will produce the following result." }, { "code": null, "e": 3594, "s": 3435, "text": "Array integerArray contains:\n1 \n2 \n3 \n4 \n5 \n6 \n\nArray doubleArray contains:\n1.1 \n2.2 \n3.3 \n4.4 \n5.5 \n6.6 \n7.7 \n\nArray characterArray contains:\nH \nE \nL \nL \nO \n" }, { "code": null, "e": 3601, "s": 3594, "text": " Print" }, { "code": null, "e": 3612, "s": 3601, "text": " Add Notes" } ]
Insert in a Sorted List | Practice | GeeksforGeeks
Given a linked list sorted in ascending order and an integer called data, insert data in the linked list such that the list remains sorted. Example 1: Input: LinkedList: 25->36->47->58->69->80 data: 19 Output: 19 25 36 47 58 69 80 Example 2: Input: LinkedList: 50->100 data: 75 Output: 50 75 100 Your Task: The task is to complete the function sortedInsert() which should insert the element in sorted Linked List and return the head of the linked list Expected Time Complexity: O(N). Expected Auxiliary Space: O(1). Constraints: 1 <= N <= 104 -99999 <= A[i] <= 99999, for each valid i 0 tthakare731 week ago //java solution class Solution { Node sortedInsert(Node head, int key) { // Add your code here. Node insert = new Node(key), dummy = head, pre = null; while(dummy != null && dummy.data <= key){ pre = dummy; dummy = dummy.next; } if(pre != null) pre.next = insert; else head = insert; insert.next = dummy; return head; } } 0 swatisingh727773 weeks ago Node *sortedInsert(struct Node* head, int data) { Node* temp = new Node(data); if(head == NULL) { return temp; } if(head -> data > data) { temp -> next = head ; return temp; } Node* curr = head; while(curr -> next != NULL && curr -> next -> data < data) { curr = curr -> next; } temp -> next = curr -> next; curr -> next = temp; return head; } 0 kuldeepy104594 weeks ago Node *sortedInsert(struct Node* head, int data) { // Code here Node *newnode= new Node(data); Node * curr= head; Node *prev=NULL; while(curr!=NULL){ if(curr->data<data){ prev=curr; curr=curr->next; } else{ break; } } if(prev){ prev->next=newnode; newnode->next=curr; } else{ newnode->next=curr; head = newnode; } return head; } 0 nihalbaranwal This comment was deleted. 0 sachinmishraravi1 month ago JAVA //please replace head1 to head class Solution { Node sortedInsert(Node head, int key) { // Add your code here. Node newNode= new Node(key); Node current=head,temp; if(current.data>newNode.data){ newNode.next=current; return newNode; } while(current.next!=null){ if(newNode.data>current.next.data){ current=current.next; } else{ // System.out.println(current.data); temp=current.next; current.next=newNode; newNode.next=temp; return head; } } current.next=newNode; return head; } } 0 prabhveer011 month ago Node sortedInsert(Node head1, int key) { // Add your code here. Node current=head1; Node temp=null; Node newNode=new Node(key); while(current!=null && current.data<key) { temp=current; current=current.next; } try{ newNode.next=current; temp.next=newNode; }catch(Exception e) { newNode.next=head1; head1=newNode; } return head1; } 0 as0042301 month ago In C++; Node *sortedInsert(struct Node* head, int data) { Node *ptr = new Node(data); Node *cur = head; if(head->data > data) { ptr->next = head; head = ptr; return head; } while(cur->next) { if(cur->next->data >= data){ ptr->next = cur->next; cur->next = ptr; return head; } cur = cur->next; } if(cur->data < data) { cur->next = ptr; ptr->next = NULL; return head; } } 0 mashhadihossain1 month ago SIMPLE JAVA SOLUTION (3.5/7.6 SEC) class Solution { Node sortedInsert(Node head1, int key) { Node temp=head1; Node add=new Node(key); if(key<temp.data) { add.next=temp; return add; } else { while(temp.next!=null) { if(temp.next.data<key) { temp=temp.next; } else { Node curr=temp.next; temp.next=add; add.next=curr; return head1; } } temp.next=add; add.next=null; return head1; } }} +1 anuraggulati2411 month ago C++ EASY SOLUTION class Solution{ public: // Should return head of the modified linked list Node *sortedInsert(struct Node* head, int data) { // Code here Node* temp = new Node(data); if(head == NULL) { return temp; } if(head -> data > data) { temp -> next = head ; return temp; } Node* curr = head; while(curr -> next != NULL && curr -> next -> data < data) { curr = curr -> next; } temp -> next = curr -> next; curr -> next = temp; return head; }}; 0 roshantekam10202 months ago Node sortedInsert(Node head1, int key) { // Add your code here. Node node=new Node(key); Node temp=head1; Node t=temp; if(key<temp.data) { node.next=head1; return node; } else { boolean flag=true; while(temp!=null) { if(key<temp.data) { flag=false; t.next=node; node.next=temp; break; } t=temp; temp=temp.next; } if(flag==true) { t.next=node; node.next=null; } return head1; } } We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 378, "s": 238, "text": "Given a linked list sorted in ascending order and an integer called data, insert data in the linked list such that the list remains sorted." }, { "code": null, "e": 389, "s": 378, "text": "Example 1:" }, { "code": null, "e": 470, "s": 389, "text": "Input:\nLinkedList: 25->36->47->58->69->80\ndata: 19\nOutput: 19 25 36 47 58 69 80\n" }, { "code": null, "e": 481, "s": 470, "text": "Example 2:" }, { "code": null, "e": 535, "s": 481, "text": "Input:\nLinkedList: 50->100\ndata: 75\nOutput: 50 75 100" }, { "code": null, "e": 691, "s": 535, "text": "Your Task:\nThe task is to complete the function sortedInsert() which should insert the element in sorted Linked List and return the head of the linked list" }, { "code": null, "e": 755, "s": 691, "text": "Expected Time Complexity: O(N).\nExpected Auxiliary Space: O(1)." }, { "code": null, "e": 824, "s": 755, "text": "Constraints:\n1 <= N <= 104\n-99999 <= A[i] <= 99999, for each valid i" }, { "code": null, "e": 828, "s": 826, "text": "0" }, { "code": null, "e": 849, "s": 828, "text": "tthakare731 week ago" }, { "code": null, "e": 1312, "s": 849, "text": "//java solution\nclass Solution {\n Node sortedInsert(Node head, int key) {\n // Add your code here.\n Node insert = new Node(key), dummy = head, pre = null;\n while(dummy != null && dummy.data <= key){\n pre = dummy;\n dummy = dummy.next;\n }\n \n if(pre != null)\n pre.next = insert;\n else \n head = insert;\n \n insert.next = dummy;\n return head;\n }\n}" }, { "code": null, "e": 1314, "s": 1312, "text": "0" }, { "code": null, "e": 1341, "s": 1314, "text": "swatisingh727773 weeks ago" }, { "code": null, "e": 1874, "s": 1341, "text": " Node *sortedInsert(struct Node* head, int data) {\n \n Node* temp = new Node(data);\n if(head == NULL) {\n return temp;\n }\n if(head -> data > data) {\n temp -> next = head ;\n \n return temp;\n } \n \n Node* curr = head;\n \n while(curr -> next != NULL && curr -> next -> data < data) {\n curr = curr -> next;\n }\n temp -> next = curr -> next;\n curr -> next = temp;\n return head;\n \n \n }" }, { "code": null, "e": 1876, "s": 1874, "text": "0" }, { "code": null, "e": 1901, "s": 1876, "text": "kuldeepy104594 weeks ago" }, { "code": null, "e": 2418, "s": 1901, "text": "Node *sortedInsert(struct Node* head, int data) { // Code here Node *newnode= new Node(data); Node * curr= head; Node *prev=NULL; while(curr!=NULL){ if(curr->data<data){ prev=curr; curr=curr->next; } else{ break; } } if(prev){ prev->next=newnode; newnode->next=curr; } else{ newnode->next=curr; head = newnode; } return head; }" }, { "code": null, "e": 2420, "s": 2418, "text": "0" }, { "code": null, "e": 2434, "s": 2420, "text": "nihalbaranwal" }, { "code": null, "e": 2460, "s": 2434, "text": "This comment was deleted." }, { "code": null, "e": 2462, "s": 2460, "text": "0" }, { "code": null, "e": 2490, "s": 2462, "text": "sachinmishraravi1 month ago" }, { "code": null, "e": 2495, "s": 2490, "text": "JAVA" }, { "code": null, "e": 3181, "s": 2495, "text": "//please replace head1 to head\n class Solution {\n Node sortedInsert(Node head, int key) {\n // Add your code here.\n Node newNode= new Node(key);\n Node current=head,temp;\n if(current.data>newNode.data){\n newNode.next=current;\n return newNode;\n }\n while(current.next!=null){\n if(newNode.data>current.next.data){\n current=current.next;\n }\n else{\n // System.out.println(current.data);\n temp=current.next;\n current.next=newNode;\n newNode.next=temp;\n return head;\n }\n }\n current.next=newNode;\n return head; \n \n }\n}" }, { "code": null, "e": 3183, "s": 3181, "text": "0" }, { "code": null, "e": 3206, "s": 3183, "text": "prabhveer011 month ago" }, { "code": null, "e": 3670, "s": 3206, "text": "Node sortedInsert(Node head1, int key) { // Add your code here. Node current=head1; Node temp=null; Node newNode=new Node(key); while(current!=null && current.data<key) { temp=current; current=current.next; } try{ newNode.next=current; temp.next=newNode; }catch(Exception e) { newNode.next=head1; head1=newNode; } return head1; }" }, { "code": null, "e": 3672, "s": 3670, "text": "0" }, { "code": null, "e": 3692, "s": 3672, "text": "as0042301 month ago" }, { "code": null, "e": 3700, "s": 3692, "text": "In C++;" }, { "code": null, "e": 4278, "s": 3700, "text": " Node *sortedInsert(struct Node* head, int data) { Node *ptr = new Node(data); Node *cur = head; if(head->data > data) { ptr->next = head; head = ptr; return head; } while(cur->next) { if(cur->next->data >= data){ ptr->next = cur->next; cur->next = ptr; return head; } cur = cur->next; } if(cur->data < data) { cur->next = ptr; ptr->next = NULL; return head; } }" }, { "code": null, "e": 4280, "s": 4278, "text": "0" }, { "code": null, "e": 4307, "s": 4280, "text": "mashhadihossain1 month ago" }, { "code": null, "e": 4342, "s": 4307, "text": "SIMPLE JAVA SOLUTION (3.5/7.6 SEC)" }, { "code": null, "e": 4943, "s": 4342, "text": "class Solution { Node sortedInsert(Node head1, int key) { Node temp=head1; Node add=new Node(key); if(key<temp.data) { add.next=temp; return add; } else { while(temp.next!=null) { if(temp.next.data<key) { temp=temp.next; } else { Node curr=temp.next; temp.next=add; add.next=curr; return head1; } } temp.next=add; add.next=null; return head1; } }}" }, { "code": null, "e": 4946, "s": 4943, "text": "+1" }, { "code": null, "e": 4973, "s": 4946, "text": "anuraggulati2411 month ago" }, { "code": null, "e": 4992, "s": 4973, "text": "C++ EASY SOLUTION " }, { "code": null, "e": 5592, "s": 4994, "text": "class Solution{ public: // Should return head of the modified linked list Node *sortedInsert(struct Node* head, int data) { // Code here Node* temp = new Node(data); if(head == NULL) { return temp; } if(head -> data > data) { temp -> next = head ; return temp; } Node* curr = head; while(curr -> next != NULL && curr -> next -> data < data) { curr = curr -> next; } temp -> next = curr -> next; curr -> next = temp; return head; }};" }, { "code": null, "e": 5594, "s": 5592, "text": "0" }, { "code": null, "e": 5622, "s": 5594, "text": "roshantekam10202 months ago" }, { "code": null, "e": 6275, "s": 5622, "text": "Node sortedInsert(Node head1, int key) { // Add your code here. Node node=new Node(key); Node temp=head1; Node t=temp; if(key<temp.data) { node.next=head1; return node; } else { boolean flag=true; while(temp!=null) { if(key<temp.data) { flag=false; t.next=node; node.next=temp; break; } t=temp; temp=temp.next; } if(flag==true) { t.next=node; node.next=null; } return head1; } }" }, { "code": null, "e": 6421, "s": 6275, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 6457, "s": 6421, "text": " Login to access your submissions. " }, { "code": null, "e": 6467, "s": 6457, "text": "\nProblem\n" }, { "code": null, "e": 6477, "s": 6467, "text": "\nContest\n" }, { "code": null, "e": 6540, "s": 6477, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 6688, "s": 6540, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 6896, "s": 6688, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 7002, "s": 6896, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
sysinfo() - Unix, Linux System Call
Unix - Home Unix - Getting Started Unix - File Management Unix - Directories Unix - File Permission Unix - Environment Unix - Basic Utilities Unix - Pipes & Filters Unix - Processes Unix - Communication Unix - The vi Editor Unix - What is Shell? Unix - Using Variables Unix - Special Variables Unix - Using Arrays Unix - Basic Operators Unix - Decision Making Unix - Shell Loops Unix - Loop Control Unix - Shell Substitutions Unix - Quoting Mechanisms Unix - IO Redirections Unix - Shell Functions Unix - Manpage Help Unix - Regular Expressions Unix - File System Basics Unix - User Administration Unix - System Performance Unix - System Logging Unix - Signals and Traps Unix - Useful Commands Unix - Quick Guide Unix - Builtin Functions Unix - System Calls Unix - Commands List Unix Useful Resources Computer Glossary Who is Who Copyright © 2014 by tutorialspoint int sysinfo(struct sysinfo *info); struct sysinfo { long uptime; /* Seconds since boot */ unsigned long loads[3]; /* 1, 5, and 15 minute load averages */ unsigned long totalram; /* Total usable main memory size */ unsigned long freeram; /* Available memory size */ unsigned long sharedram; /* Amount of shared memory */ unsigned long bufferram; /* Memory used by buffers */ unsigned long totalswap; /* Total swap space size */ unsigned long freeswap; /* swap space still available */ unsigned short procs; /* Number of current processes */ char _f[22]; /* Pads structure to 64 bytes */ }; and the sizes were given in bytes. Since Linux 2.3.23 (i386), 2.3.48 (all architectures) the structure is struct sysinfo { long uptime; /* Seconds since boot */ unsigned long loads[3]; /* 1, 5, and 15 minute load averages */ unsigned long totalram; /* Total usable main memory size */ unsigned long freeram; /* Available memory size */ unsigned long sharedram; /* Amount of shared memory */ unsigned long bufferram; /* Memory used by buffers */ unsigned long totalswap; /* Total swap space size */ unsigned long freeswap; /* swap space still available */ unsigned short procs; /* Number of current processes */ unsigned long totalhigh; /* Total high memory size */ unsigned long freehigh; /* Available high memory size */ unsigned int mem_unit; /* Memory unit size in bytes */ char _f[20-2*sizeof(long)-sizeof(int)]; /* Padding for libc5 */ }; and the sizes are given as multiples of mem_unit bytes. sysinfo() provides a simple way of getting overall system statistics. This is more portable than reading /dev/kmem. For an example of its use, see intro(2). The Linux kernel has a sysinfo() system call since 0.98.pl6. Linux libc contains a sysinfo() routine since 5.3.5, and glibc has one since 1.90. Advertisements 129 Lectures 23 hours Eduonix Learning Solutions 5 Lectures 4.5 hours Frahaan Hussain 35 Lectures 2 hours Pradeep D 41 Lectures 2.5 hours Musab Zayadneh 46 Lectures 4 hours GUHARAJANM 6 Lectures 4 hours Uplatz Print Add Notes Bookmark this page
[ { "code": null, "e": 1466, "s": 1454, "text": "Unix - Home" }, { "code": null, "e": 1489, "s": 1466, "text": "Unix - Getting Started" }, { "code": null, "e": 1512, "s": 1489, "text": "Unix - File Management" }, { "code": null, "e": 1531, "s": 1512, "text": "Unix - Directories" }, { "code": null, "e": 1554, "s": 1531, "text": "Unix - File Permission" }, { "code": null, "e": 1573, "s": 1554, "text": "Unix - Environment" }, { "code": null, "e": 1596, "s": 1573, "text": "Unix - Basic Utilities" }, { "code": null, "e": 1619, "s": 1596, "text": "Unix - Pipes & Filters" }, { "code": null, "e": 1636, "s": 1619, "text": "Unix - Processes" }, { "code": null, "e": 1657, "s": 1636, "text": "Unix - Communication" }, { "code": null, "e": 1678, "s": 1657, "text": "Unix - The vi Editor" }, { "code": null, "e": 1700, "s": 1678, "text": "Unix - What is Shell?" }, { "code": null, "e": 1723, "s": 1700, "text": "Unix - Using Variables" }, { "code": null, "e": 1748, "s": 1723, "text": "Unix - Special Variables" }, { "code": null, "e": 1768, "s": 1748, "text": "Unix - Using Arrays" }, { "code": null, "e": 1791, "s": 1768, "text": "Unix - Basic Operators" }, { "code": null, "e": 1814, "s": 1791, "text": "Unix - Decision Making" }, { "code": null, "e": 1833, "s": 1814, "text": "Unix - Shell Loops" }, { "code": null, "e": 1853, "s": 1833, "text": "Unix - Loop Control" }, { "code": null, "e": 1880, "s": 1853, "text": "Unix - Shell Substitutions" }, { "code": null, "e": 1906, "s": 1880, "text": "Unix - Quoting Mechanisms" }, { "code": null, "e": 1929, "s": 1906, "text": "Unix - IO Redirections" }, { "code": null, "e": 1952, "s": 1929, "text": "Unix - Shell Functions" }, { "code": null, "e": 1972, "s": 1952, "text": "Unix - Manpage Help" }, { "code": null, "e": 1999, "s": 1972, "text": "Unix - Regular Expressions" }, { "code": null, "e": 2025, "s": 1999, "text": "Unix - File System Basics" }, { "code": null, "e": 2052, "s": 2025, "text": "Unix - User Administration" }, { "code": null, "e": 2078, "s": 2052, "text": "Unix - System Performance" }, { "code": null, "e": 2100, "s": 2078, "text": "Unix - System Logging" }, { "code": null, "e": 2125, "s": 2100, "text": "Unix - Signals and Traps" }, { "code": null, "e": 2148, "s": 2125, "text": "Unix - Useful Commands" }, { "code": null, "e": 2167, "s": 2148, "text": "Unix - Quick Guide" }, { "code": null, "e": 2192, "s": 2167, "text": "Unix - Builtin Functions" }, { "code": null, "e": 2212, "s": 2192, "text": "Unix - System Calls" }, { "code": null, "e": 2233, "s": 2212, "text": "Unix - Commands List" }, { "code": null, "e": 2255, "s": 2233, "text": "Unix Useful Resources" }, { "code": null, "e": 2273, "s": 2255, "text": "Computer Glossary" }, { "code": null, "e": 2284, "s": 2273, "text": "Who is Who" }, { "code": null, "e": 2319, "s": 2284, "text": "Copyright © 2014 by tutorialspoint" }, { "code": null, "e": 2356, "s": 2319, "text": "\nint sysinfo(struct sysinfo *info); " }, { "code": null, "e": 3025, "s": 2358, "text": "struct sysinfo {\n long uptime; /* Seconds since boot */\n unsigned long loads[3]; /* 1, 5, and 15 minute load averages */\n unsigned long totalram; /* Total usable main memory size */\n unsigned long freeram; /* Available memory size */\n unsigned long sharedram; /* Amount of shared memory */\n unsigned long bufferram; /* Memory used by buffers */\n unsigned long totalswap; /* Total swap space size */\n unsigned long freeswap; /* swap space still available */\n unsigned short procs; /* Number of current processes */\n char _f[22]; /* Pads structure to 64 bytes */\n};\n" }, { "code": null, "e": 3133, "s": 3025, "text": "\nand the sizes were given in bytes. Since Linux 2.3.23 (i386), 2.3.48\n(all architectures) the structure is\n" }, { "code": null, "e": 4001, "s": 3135, "text": "struct sysinfo {\n long uptime; /* Seconds since boot */\n unsigned long loads[3]; /* 1, 5, and 15 minute load averages */\n unsigned long totalram; /* Total usable main memory size */\n unsigned long freeram; /* Available memory size */\n unsigned long sharedram; /* Amount of shared memory */\n unsigned long bufferram; /* Memory used by buffers */\n unsigned long totalswap; /* Total swap space size */\n unsigned long freeswap; /* swap space still available */\n unsigned short procs; /* Number of current processes */\n unsigned long totalhigh; /* Total high memory size */\n unsigned long freehigh; /* Available high memory size */\n unsigned int mem_unit; /* Memory unit size in bytes */\n char _f[20-2*sizeof(long)-sizeof(int)]; /* Padding for libc5 */\n};\n" }, { "code": null, "e": 4059, "s": 4001, "text": "\nand the sizes are given as multiples of mem_unit bytes.\n" }, { "code": null, "e": 4219, "s": 4059, "text": "\nsysinfo() provides a simple way of getting overall system statistics. This is more\nportable than reading /dev/kmem.\nFor an example of its use, see\nintro(2).\n" }, { "code": null, "e": 4365, "s": 4219, "text": "\nThe Linux kernel has a\nsysinfo() system call since 0.98.pl6.\nLinux libc contains a\nsysinfo() routine since 5.3.5, and\nglibc has one since 1.90.\n" }, { "code": null, "e": 4382, "s": 4365, "text": "\nAdvertisements\n" }, { "code": null, "e": 4417, "s": 4382, "text": "\n 129 Lectures \n 23 hours \n" }, { "code": null, "e": 4445, "s": 4417, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 4479, "s": 4445, "text": "\n 5 Lectures \n 4.5 hours \n" }, { "code": null, "e": 4496, "s": 4479, "text": " Frahaan Hussain" }, { "code": null, "e": 4529, "s": 4496, "text": "\n 35 Lectures \n 2 hours \n" }, { "code": null, "e": 4540, "s": 4529, "text": " Pradeep D" }, { "code": null, "e": 4575, "s": 4540, "text": "\n 41 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4591, "s": 4575, "text": " Musab Zayadneh" }, { "code": null, "e": 4624, "s": 4591, "text": "\n 46 Lectures \n 4 hours \n" }, { "code": null, "e": 4636, "s": 4624, "text": " GUHARAJANM" }, { "code": null, "e": 4668, "s": 4636, "text": "\n 6 Lectures \n 4 hours \n" }, { "code": null, "e": 4676, "s": 4668, "text": " Uplatz" }, { "code": null, "e": 4683, "s": 4676, "text": " Print" }, { "code": null, "e": 4694, "s": 4683, "text": " Add Notes" } ]
Convert string to integer in Python - GeeksforGeeks
29 Apr, 2020 In Python an strings can be converted into a integer using the built-in int() function. The int() function takes in any python data type and converts it into a integer.But use of the int() function is not the only way to do so. This type of conversion can also be done using thefloat() keyword, as a float value can be used to compute with integers. Below is the list of possible ways to convert an integer to string in python: 1. Using int() function Syntax: int(string) Example: num = '10' # check and print type num variableprint(type(num)) # convert the num into string converted_num = int(num) # print type of converted_numprint(type(converted_num)) # We can check by doing some mathematical operationsprint(converted_num + 20) As a side note, to convert to float, we can use float() in Python num = '10.5' # check and print type num variableprint(type(num)) # convert the num into string converted_num = float(num) # print type of converted_numprint(type(converted_num)) # We can check by doing some mathematical operationsprint(converted_num + 20.5) 2. Using float() function We first convert to float, then convert float to integer. Obviously the above method is better (directly convert to integer) Syntax: float(string) Example: a = '2'b = '3' # print the data type of a and bprint(type(a))print(type(b)) # convert a using floata = float(a) # convert b using intb = int(b) # sum both integerssum = a + b # as strings and integers can't be added# try testing the sumprint(sum) Output: class 'str' class 'str' 5.0 Note: float values are decimal values that can be used with integers for computation. python-basics Python-datatype python-string Python Write From Home 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 Python infinity How to set input type date in dd-mm-yyyy format using HTML ? Matplotlib.pyplot.title() in Python Factory method design pattern in Java Similarities and Difference between Java and C++
[ { "code": null, "e": 24278, "s": 24250, "text": "\n29 Apr, 2020" }, { "code": null, "e": 24628, "s": 24278, "text": "In Python an strings can be converted into a integer using the built-in int() function. The int() function takes in any python data type and converts it into a integer.But use of the int() function is not the only way to do so. This type of conversion can also be done using thefloat() keyword, as a float value can be used to compute with integers." }, { "code": null, "e": 24706, "s": 24628, "text": "Below is the list of possible ways to convert an integer to string in python:" }, { "code": null, "e": 24730, "s": 24706, "text": "1. Using int() function" }, { "code": null, "e": 24750, "s": 24730, "text": "Syntax: int(string)" }, { "code": null, "e": 24759, "s": 24750, "text": "Example:" }, { "code": "num = '10' # check and print type num variableprint(type(num)) # convert the num into string converted_num = int(num) # print type of converted_numprint(type(converted_num)) # We can check by doing some mathematical operationsprint(converted_num + 20)", "e": 25016, "s": 24759, "text": null }, { "code": null, "e": 25082, "s": 25016, "text": "As a side note, to convert to float, we can use float() in Python" }, { "code": "num = '10.5' # check and print type num variableprint(type(num)) # convert the num into string converted_num = float(num) # print type of converted_numprint(type(converted_num)) # We can check by doing some mathematical operationsprint(converted_num + 20.5)", "e": 25345, "s": 25082, "text": null }, { "code": null, "e": 25371, "s": 25345, "text": "2. Using float() function" }, { "code": null, "e": 25496, "s": 25371, "text": "We first convert to float, then convert float to integer. Obviously the above method is better (directly convert to integer)" }, { "code": null, "e": 25518, "s": 25496, "text": "Syntax: float(string)" }, { "code": null, "e": 25527, "s": 25518, "text": "Example:" }, { "code": "a = '2'b = '3' # print the data type of a and bprint(type(a))print(type(b)) # convert a using floata = float(a) # convert b using intb = int(b) # sum both integerssum = a + b # as strings and integers can't be added# try testing the sumprint(sum)", "e": 25779, "s": 25527, "text": null }, { "code": null, "e": 25787, "s": 25779, "text": "Output:" }, { "code": null, "e": 25815, "s": 25787, "text": "class 'str'\nclass 'str'\n5.0" }, { "code": null, "e": 25901, "s": 25815, "text": "Note: float values are decimal values that can be used with integers for computation." }, { "code": null, "e": 25915, "s": 25901, "text": "python-basics" }, { "code": null, "e": 25931, "s": 25915, "text": "Python-datatype" }, { "code": null, "e": 25945, "s": 25931, "text": "python-string" }, { "code": null, "e": 25952, "s": 25945, "text": "Python" }, { "code": null, "e": 25968, "s": 25952, "text": "Write From Home" }, { "code": null, "e": 26066, "s": 25968, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26075, "s": 26066, "text": "Comments" }, { "code": null, "e": 26088, "s": 26075, "text": "Old Comments" }, { "code": null, "e": 26106, "s": 26088, "text": "Python Dictionary" }, { "code": null, "e": 26141, "s": 26106, "text": "Read a file line by line in Python" }, { "code": null, "e": 26163, "s": 26141, "text": "Enumerate() in Python" }, { "code": null, "e": 26195, "s": 26163, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26225, "s": 26195, "text": "Iterate over a list in Python" }, { "code": null, "e": 26241, "s": 26225, "text": "Python infinity" }, { "code": null, "e": 26302, "s": 26241, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 26338, "s": 26302, "text": "Matplotlib.pyplot.title() in Python" }, { "code": null, "e": 26376, "s": 26338, "text": "Factory method design pattern in Java" } ]
matplotlib.pyplot.magnitude_spectrum() in Python
22 Apr, 2020 Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. There are various plots which can be used in Pyplot are Line Plot, Contour, Histogram, Scatter, 3D Plot, etc. The magnitude_spectrum() function in pyplot module of matplotlib library is used to plot the magnitude spectrum. Generally, it compute the magnitude spectrum of sequence and plotting is done. Syntax: magnitude_spectrum(x, Fs=2, Fc=0, window=mlab.window_hanning, pad_to=None, sides=’default’, **kwargs) Parameters: This method accept the following parameters that are described below: x: This parameter is a sequence of data. Fs : This parameter is a scalar. Its default value is 2. window: This parameter take a data segment as an argument and return the windowed version of the segment. Its default value is window_hanning() sides: This parameter specifies which sides of the spectrum to return. This can have following values : ‘default’, ‘onesided’ and ‘twosided’. pad_to : This parameter contains the integer value to which the data segment is padded. Fc: This parameter is also contains the integer value to offsets the x extents of the plot to reflect the frequency range. Its default value is 0 Returns: This returns the following: spectrum :This returns the angle spectrum in radians. freqs :This returns the frequencies corresponding to the elements in spectrum. line : This returns the line created by this function. The resultant is (spectrum, freqs, line) Below examples illustrate the matplotlib.pyplot.magnitude_spectrum() function in matplotlib.pyplot: Example #1: # Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np np.random.seed(10**5) dt = 0.0001Fs = 1 / dtgeeks = np.array([24.40, 110.25, 20.05, 22.00, 61.90, 7.80, 15.00, 22.80, 34.90, 57.30]) nse = np.random.randn(len(geeks))r = np.exp(-geeks / 0.05) s = 0.1 * np.sin(2 * np.pi * geeks) + nse # plot magnitude_spectrumplt.magnitude_spectrum(s, Fs = Fs)plt.title('matplotlib.pyplot.magnitude_spectrum() function Example', fontweight ="bold")plt.show() Output: Example #2: # Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np np.random.seed(0) dt = 0.01Fs = 1 / dtt = np.arange(0, 10, dt)nse = np.random.randn(len(t))r = np.exp(-t / 0.05) cnse = np.convolve(nse, r)*dtcnse = cnse[:len(t)]s = 0.1 * np.sin(2 * np.pi * t) + cnse # plot simple spectrumplt.subplot(2, 1, 1)plt.plot(t, s)plt.title('matplotlib.pyplot.magnitude_spectrum() function Example', fontweight ="bold") plt.subplot(2, 1, 2)plt.magnitude_spectrum(s, Fs = Fs) plt.show() Output: Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Apr, 2020" }, { "code": null, "e": 333, "s": 28, "text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. There are various plots which can be used in Pyplot are Line Plot, Contour, Histogram, Scatter, 3D Plot, etc." }, { "code": null, "e": 525, "s": 333, "text": "The magnitude_spectrum() function in pyplot module of matplotlib library is used to plot the magnitude spectrum. Generally, it compute the magnitude spectrum of sequence and plotting is done." }, { "code": null, "e": 635, "s": 525, "text": "Syntax: magnitude_spectrum(x, Fs=2, Fc=0, window=mlab.window_hanning, pad_to=None, sides=’default’, **kwargs)" }, { "code": null, "e": 717, "s": 635, "text": "Parameters: This method accept the following parameters that are described below:" }, { "code": null, "e": 758, "s": 717, "text": "x: This parameter is a sequence of data." }, { "code": null, "e": 815, "s": 758, "text": "Fs : This parameter is a scalar. Its default value is 2." }, { "code": null, "e": 959, "s": 815, "text": "window: This parameter take a data segment as an argument and return the windowed version of the segment. Its default value is window_hanning()" }, { "code": null, "e": 1101, "s": 959, "text": "sides: This parameter specifies which sides of the spectrum to return. This can have following values : ‘default’, ‘onesided’ and ‘twosided’." }, { "code": null, "e": 1189, "s": 1101, "text": "pad_to : This parameter contains the integer value to which the data segment is padded." }, { "code": null, "e": 1335, "s": 1189, "text": "Fc: This parameter is also contains the integer value to offsets the x extents of the plot to reflect the frequency range. Its default value is 0" }, { "code": null, "e": 1372, "s": 1335, "text": "Returns: This returns the following:" }, { "code": null, "e": 1426, "s": 1372, "text": "spectrum :This returns the angle spectrum in radians." }, { "code": null, "e": 1505, "s": 1426, "text": "freqs :This returns the frequencies corresponding to the elements in spectrum." }, { "code": null, "e": 1560, "s": 1505, "text": "line : This returns the line created by this function." }, { "code": null, "e": 1601, "s": 1560, "text": "The resultant is (spectrum, freqs, line)" }, { "code": null, "e": 1701, "s": 1601, "text": "Below examples illustrate the matplotlib.pyplot.magnitude_spectrum() function in matplotlib.pyplot:" }, { "code": null, "e": 1713, "s": 1701, "text": "Example #1:" }, { "code": "# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np np.random.seed(10**5) dt = 0.0001Fs = 1 / dtgeeks = np.array([24.40, 110.25, 20.05, 22.00, 61.90, 7.80, 15.00, 22.80, 34.90, 57.30]) nse = np.random.randn(len(geeks))r = np.exp(-geeks / 0.05) s = 0.1 * np.sin(2 * np.pi * geeks) + nse # plot magnitude_spectrumplt.magnitude_spectrum(s, Fs = Fs)plt.title('matplotlib.pyplot.magnitude_spectrum() function Example', fontweight =\"bold\")plt.show()", "e": 2271, "s": 1713, "text": null }, { "code": null, "e": 2279, "s": 2271, "text": "Output:" }, { "code": null, "e": 2291, "s": 2279, "text": "Example #2:" }, { "code": "# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np np.random.seed(0) dt = 0.01Fs = 1 / dtt = np.arange(0, 10, dt)nse = np.random.randn(len(t))r = np.exp(-t / 0.05) cnse = np.convolve(nse, r)*dtcnse = cnse[:len(t)]s = 0.1 * np.sin(2 * np.pi * t) + cnse # plot simple spectrumplt.subplot(2, 1, 1)plt.plot(t, s)plt.title('matplotlib.pyplot.magnitude_spectrum() function Example', fontweight =\"bold\") plt.subplot(2, 1, 2)plt.magnitude_spectrum(s, Fs = Fs) plt.show()", "e": 2851, "s": 2291, "text": null }, { "code": null, "e": 2859, "s": 2851, "text": "Output:" }, { "code": null, "e": 2877, "s": 2859, "text": "Python-matplotlib" }, { "code": null, "e": 2884, "s": 2877, "text": "Python" } ]
Three-dimensional Plotting in Python using Matplotlib
05 Jun, 2021 Matplotlib was introduced keeping in mind, only two-dimensional plotting. But at the time when the release of 1.0 occurred, the 3d utilities were developed upon the 2d and thus, we have 3d implementation of data available today! The 3d plots are enabled by importing the mplot3d toolkit. In this article, we will deal with the 3d plots using matplotlib.Example: Python3 import numpy as npimport matplotlib.pyplot as plt fig = plt.figure()ax = plt.axes(projection ='3d') Output: With the above syntax three -dimensional axes are enabled and data can be plotted in 3 dimensions. 3 dimension graph gives a dynamic approach and makes data more interactive. Like 2-D graphs, we can use different ways to represent 3-D graph. We can make a scatter plot, contour plot, surface plot, etc. Let’s have a look at different 3-D plots. Graph with lines and point are the simplest 3 dimensional graph. ax.plot3d and ax.scatter are the function to plot line and point graph respectively.Example 1: 3 dimensional line graph Python3 # importing mplot3d toolkits, numpy and matplotlibfrom mpl_toolkits import mplot3dimport numpy as npimport matplotlib.pyplot as plt fig = plt.figure() # syntax for 3-D projectionax = plt.axes(projection ='3d') # defining all 3 axesz = np.linspace(0, 1, 100)x = z * np.sin(25 * z)y = z * np.cos(25 * z) # plottingax.plot3D(x, y, z, 'green')ax.set_title('3D line plot geeks for geeks')plt.show() Output: Example 2: 3 dimensional scattered graph Python3 # importing mplot3d toolkitsfrom mpl_toolkits import mplot3dimport numpy as npimport matplotlib.pyplot as plt fig = plt.figure() # syntax for 3-D projectionax = plt.axes(projection ='3d') # defining axesz = np.linspace(0, 1, 100)x = z * np.sin(25 * z)y = z * np.cos(25 * z)c = x + yax.scatter(x, y, z, c = c) # syntax for plottingax.set_title('3d Scatter plot geeks for geeks')plt.show() Output: Surface graph and Wireframes graph work on gridded data. They take grid value and plot it on three-dimensional surface.Example 1: Surface graph Python3 # importing librariesfrom mpl_toolkits import mplot3dimport numpy as npimport matplotlib.pyplot as plt # defining surface and axesx = np.outer(np.linspace(-2, 2, 10), np.ones(10))y = x.copy().Tz = np.cos(x ** 2 + y ** 3) fig = plt.figure() # syntax for 3-D plottingax = plt.axes(projection ='3d') # syntax for plottingax.plot_surface(x, y, z, cmap ='viridis', edgecolor ='green')ax.set_title('Surface plot geeks for geeks')plt.show() Output: Example 2: Wireframes Python3 from mpl_toolkits import mplot3dimport numpy as npimport matplotlib.pyplot as plt # function for z axeadef f(x, y): return np.sin(np.sqrt(x ** 2 + y ** 2)) # x and y axisx = np.linspace(-1, 5, 10)y = np.linspace(-1, 5, 10) X, Y = np.meshgrid(x, y)Z = f(X, Y) fig = plt.figure()ax = plt.axes(projection ='3d')ax.plot_wireframe(X, Y, Z, color ='green')ax.set_title('wireframe geeks for geeks'); Output: Contour graph takes all the input data in two-dimensional regular grids, and the Z data is evaluated at every point.We use ax.contour3D function to plot a contour graph.Example: Python3 from mpl_toolkits import mplot3dimport numpy as npimport matplotlib.pyplot as plt # function for z axisdef f(x, y): return np.sin(np.sqrt(x ** 2 + y ** 3)) # x and y axisx = np.linspace(-1, 5, 10)y = np.linspace(-1, 5, 10)X, Y = np.meshgrid(x, y)Z = f(X, Y) fig = plt.figure()ax = plt.axes(projection ='3d') # ax.contour3D is used plot a contour graphax.contour3D(X, Y, Z) Output: The above graph is sometimes overly restricted and inconvenient. So by this method, we use a set of random draws. The function ax.plot_trisurf is used to draw this graph. It is not that clear but more flexible.Example: Python3 from mpl_toolkits import mplot3dimport numpy as npimport matplotlib.pyplot as plt # angle and radiustheta = 2 * np.pi * np.random.random(100)r = 6 * np.random.random(100) # all three axesx = np.ravel(r * np.sin(theta))y = np.ravel(r * np.cos(theta))z = f(x, y) ax = plt.axes(projection ='3d')ax.scatter(x, y, z, c = z, cmap ='viridis', linewidth = 0.25); ax = plt.axes(projection ='3d')ax.plot_trisurf(x, y, z, cmap ='viridis', edgecolor ='green'); Output: Möbius strip also called the twisted cylinder, is a one-sided surface without boundaries. To create the Möbius strip think about its parameterization, it’s a two-dimensional strip, and we need two intrinsic dimensions. Its angle range from 0 to 2 pie around the loop and width ranges from -1 to 1.Example: Python3 from mpl_toolkits import mplot3dimport numpy as npimport matplotlib.pyplot as pltfrom matplotlib.tri import Triangulation theta = np.linspace(0, 2 * np.pi, 10)w = np.linspace(-1, 5, 8)w, theta = np.meshgrid(w, theta)phi = 0.5 * theta # radius in x-y planer = 1 + w * np.cos(phi) # all three axesx = np.ravel(r * np.cos(theta))y = np.ravel(r * np.sin(theta))z = np.ravel(w * np.sin(phi)) # triangulate in the underlying# parameterizationtri = Triangulation(np.ravel(w), np.ravel(theta)) ax = plt.axes(projection ='3d')ax.plot_trisurf(x, y, z, triangles = tri.triangles, cmap ='viridis', linewidths = 0.2); Output: anikaseth98 Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function Python Dictionary How to get column names in Pandas dataframe Different ways to create Pandas Dataframe Taking input in Python Enumerate() in Python Read a file line by line in Python Python String | replace()
[ { "code": null, "e": 54, "s": 26, "text": "\n05 Jun, 2021" }, { "code": null, "e": 418, "s": 54, "text": "Matplotlib was introduced keeping in mind, only two-dimensional plotting. But at the time when the release of 1.0 occurred, the 3d utilities were developed upon the 2d and thus, we have 3d implementation of data available today! The 3d plots are enabled by importing the mplot3d toolkit. In this article, we will deal with the 3d plots using matplotlib.Example: " }, { "code": null, "e": 426, "s": 418, "text": "Python3" }, { "code": "import numpy as npimport matplotlib.pyplot as plt fig = plt.figure()ax = plt.axes(projection ='3d')", "e": 527, "s": 426, "text": null }, { "code": null, "e": 536, "s": 527, "text": "Output: " }, { "code": null, "e": 882, "s": 536, "text": "With the above syntax three -dimensional axes are enabled and data can be plotted in 3 dimensions. 3 dimension graph gives a dynamic approach and makes data more interactive. Like 2-D graphs, we can use different ways to represent 3-D graph. We can make a scatter plot, contour plot, surface plot, etc. Let’s have a look at different 3-D plots. " }, { "code": null, "e": 1069, "s": 882, "text": "Graph with lines and point are the simplest 3 dimensional graph. ax.plot3d and ax.scatter are the function to plot line and point graph respectively.Example 1: 3 dimensional line graph " }, { "code": null, "e": 1077, "s": 1069, "text": "Python3" }, { "code": "# importing mplot3d toolkits, numpy and matplotlibfrom mpl_toolkits import mplot3dimport numpy as npimport matplotlib.pyplot as plt fig = plt.figure() # syntax for 3-D projectionax = plt.axes(projection ='3d') # defining all 3 axesz = np.linspace(0, 1, 100)x = z * np.sin(25 * z)y = z * np.cos(25 * z) # plottingax.plot3D(x, y, z, 'green')ax.set_title('3D line plot geeks for geeks')plt.show()", "e": 1471, "s": 1077, "text": null }, { "code": null, "e": 1480, "s": 1471, "text": "Output: " }, { "code": null, "e": 1523, "s": 1480, "text": "Example 2: 3 dimensional scattered graph " }, { "code": null, "e": 1531, "s": 1523, "text": "Python3" }, { "code": "# importing mplot3d toolkitsfrom mpl_toolkits import mplot3dimport numpy as npimport matplotlib.pyplot as plt fig = plt.figure() # syntax for 3-D projectionax = plt.axes(projection ='3d') # defining axesz = np.linspace(0, 1, 100)x = z * np.sin(25 * z)y = z * np.cos(25 * z)c = x + yax.scatter(x, y, z, c = c) # syntax for plottingax.set_title('3d Scatter plot geeks for geeks')plt.show()", "e": 1919, "s": 1531, "text": null }, { "code": null, "e": 1928, "s": 1919, "text": "Output: " }, { "code": null, "e": 2076, "s": 1930, "text": "Surface graph and Wireframes graph work on gridded data. They take grid value and plot it on three-dimensional surface.Example 1: Surface graph " }, { "code": null, "e": 2084, "s": 2076, "text": "Python3" }, { "code": "# importing librariesfrom mpl_toolkits import mplot3dimport numpy as npimport matplotlib.pyplot as plt # defining surface and axesx = np.outer(np.linspace(-2, 2, 10), np.ones(10))y = x.copy().Tz = np.cos(x ** 2 + y ** 3) fig = plt.figure() # syntax for 3-D plottingax = plt.axes(projection ='3d') # syntax for plottingax.plot_surface(x, y, z, cmap ='viridis', edgecolor ='green')ax.set_title('Surface plot geeks for geeks')plt.show()", "e": 2518, "s": 2084, "text": null }, { "code": null, "e": 2527, "s": 2518, "text": "Output: " }, { "code": null, "e": 2551, "s": 2527, "text": "Example 2: Wireframes " }, { "code": null, "e": 2559, "s": 2551, "text": "Python3" }, { "code": "from mpl_toolkits import mplot3dimport numpy as npimport matplotlib.pyplot as plt # function for z axeadef f(x, y): return np.sin(np.sqrt(x ** 2 + y ** 2)) # x and y axisx = np.linspace(-1, 5, 10)y = np.linspace(-1, 5, 10) X, Y = np.meshgrid(x, y)Z = f(X, Y) fig = plt.figure()ax = plt.axes(projection ='3d')ax.plot_wireframe(X, Y, Z, color ='green')ax.set_title('wireframe geeks for geeks');", "e": 2957, "s": 2559, "text": null }, { "code": null, "e": 2966, "s": 2957, "text": "Output: " }, { "code": null, "e": 3148, "s": 2968, "text": "Contour graph takes all the input data in two-dimensional regular grids, and the Z data is evaluated at every point.We use ax.contour3D function to plot a contour graph.Example: " }, { "code": null, "e": 3156, "s": 3148, "text": "Python3" }, { "code": "from mpl_toolkits import mplot3dimport numpy as npimport matplotlib.pyplot as plt # function for z axisdef f(x, y): return np.sin(np.sqrt(x ** 2 + y ** 3)) # x and y axisx = np.linspace(-1, 5, 10)y = np.linspace(-1, 5, 10)X, Y = np.meshgrid(x, y)Z = f(X, Y) fig = plt.figure()ax = plt.axes(projection ='3d') # ax.contour3D is used plot a contour graphax.contour3D(X, Y, Z)", "e": 3533, "s": 3156, "text": null }, { "code": null, "e": 3542, "s": 3533, "text": "Output: " }, { "code": null, "e": 3765, "s": 3544, "text": "The above graph is sometimes overly restricted and inconvenient. So by this method, we use a set of random draws. The function ax.plot_trisurf is used to draw this graph. It is not that clear but more flexible.Example: " }, { "code": null, "e": 3773, "s": 3765, "text": "Python3" }, { "code": "from mpl_toolkits import mplot3dimport numpy as npimport matplotlib.pyplot as plt # angle and radiustheta = 2 * np.pi * np.random.random(100)r = 6 * np.random.random(100) # all three axesx = np.ravel(r * np.sin(theta))y = np.ravel(r * np.cos(theta))z = f(x, y) ax = plt.axes(projection ='3d')ax.scatter(x, y, z, c = z, cmap ='viridis', linewidth = 0.25); ax = plt.axes(projection ='3d')ax.plot_trisurf(x, y, z, cmap ='viridis', edgecolor ='green');", "e": 4223, "s": 3773, "text": null }, { "code": null, "e": 4232, "s": 4223, "text": "Output: " }, { "code": null, "e": 4544, "s": 4234, "text": "Möbius strip also called the twisted cylinder, is a one-sided surface without boundaries. To create the Möbius strip think about its parameterization, it’s a two-dimensional strip, and we need two intrinsic dimensions. Its angle range from 0 to 2 pie around the loop and width ranges from -1 to 1.Example: " }, { "code": null, "e": 4552, "s": 4544, "text": "Python3" }, { "code": "from mpl_toolkits import mplot3dimport numpy as npimport matplotlib.pyplot as pltfrom matplotlib.tri import Triangulation theta = np.linspace(0, 2 * np.pi, 10)w = np.linspace(-1, 5, 8)w, theta = np.meshgrid(w, theta)phi = 0.5 * theta # radius in x-y planer = 1 + w * np.cos(phi) # all three axesx = np.ravel(r * np.cos(theta))y = np.ravel(r * np.sin(theta))z = np.ravel(w * np.sin(phi)) # triangulate in the underlying# parameterizationtri = Triangulation(np.ravel(w), np.ravel(theta)) ax = plt.axes(projection ='3d')ax.plot_trisurf(x, y, z, triangles = tri.triangles, cmap ='viridis', linewidths = 0.2);", "e": 5174, "s": 4552, "text": null }, { "code": null, "e": 5183, "s": 5174, "text": "Output: " }, { "code": null, "e": 5197, "s": 5185, "text": "anikaseth98" }, { "code": null, "e": 5215, "s": 5197, "text": "Python-matplotlib" }, { "code": null, "e": 5222, "s": 5215, "text": "Python" }, { "code": null, "e": 5320, "s": 5222, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5348, "s": 5320, "text": "Read JSON file using Python" }, { "code": null, "e": 5398, "s": 5348, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 5420, "s": 5398, "text": "Python map() function" }, { "code": null, "e": 5438, "s": 5420, "text": "Python Dictionary" }, { "code": null, "e": 5482, "s": 5438, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 5524, "s": 5482, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 5547, "s": 5524, "text": "Taking input in Python" }, { "code": null, "e": 5569, "s": 5547, "text": "Enumerate() in Python" }, { "code": null, "e": 5604, "s": 5569, "text": "Read a file line by line in Python" } ]
CSS - Lists
Lists are very helpful in conveying a set of either numbered or bullet points. This chapter teaches you how to control list type, position, style, etc., using CSS. We have the following five CSS properties, which can be used to control lists − The list-style-type allows you to control the shape or appearance of the marker. The list-style-type allows you to control the shape or appearance of the marker. The list-style-position specifies whether a long point that wraps to a second line should align with the first line or start underneath the start of the marker. The list-style-position specifies whether a long point that wraps to a second line should align with the first line or start underneath the start of the marker. The list-style-image specifies an image for the marker rather than a bullet point or number. The list-style-image specifies an image for the marker rather than a bullet point or number. The list-style serves as shorthand for the preceding properties. The list-style serves as shorthand for the preceding properties. The marker-offset specifies the distance between a marker and the text in the list. The marker-offset specifies the distance between a marker and the text in the list. Now, we will see how to use these properties with examples. The list-style-type property allows you to control the shape or style of bullet point (also known as a marker) in the case of unordered lists and the style of numbering characters in ordered lists. Here are the values which can be used for an unordered list − none NA disc (default) A filled-in circle circle An empty circle square A filled-in square Here are the values, which can be used for an ordered list − Here is an example − <html> <head> </head> <body> <ul style = "list-style-type:circle;"> <li>Maths</li> <li>Social Science</li> <li>Physics</li> </ul> <ul style = "list-style-type:square;"> <li>Maths</li> <li>Social Science</li> <li>Physics</li> </ul> <ol style = "list-style-type:decimal;"> <li>Maths</li> <li>Social Science</li> <li>Physics</li> </ol> <ol style = "list-style-type:lower-alpha;"> <li>Maths</li> <li>Social Science</li> <li>Physics</li> </ol> <ol style = "list-style-type:lower-roman;"> <li>Maths</li> <li>Social Science</li> <li>Physics</li> </ol> </body> </html> It will produce the following result − Maths Social Science Physics Maths Social Science Physics Maths Social Science Physics Maths Social Science Physics Maths Social Science Physics Maths Social Science Physics Maths Social Science Physics Maths Social Science Physics The list-style-position property indicates whether the marker should appear inside or outside of the box containing the bullet points. It can have one the two values − none NA inside If the text goes onto a second line, the text will wrap underneath the marker. It will also appear indented to where the text would have started if the list had a value of outside. outside If the text goes onto a second line, the text will be aligned with the start of the first line (to the right of the bullet). Here is an example − <html> <head> </head> <body> <ul style = "list-style-type:circle; list-stlye-position:outside;"> <li>Maths</li> <li>Social Science</li> <li>Physics</li> </ul> <ul style = "list-style-type:square;list-style-position:inside;"> <li>Maths</li> <li>Social Science</li> <li>Physics</li> </ul> <ol style = "list-style-type:decimal;list-stlye-position:outside;"> <li>Maths</li> <li>Social Science</li> <li>Physics</li> </ol> <ol style = "list-style-type:lower-alpha;list-style-position:inside;"> <li>Maths</li> <li>Social Science</li> <li>Physics</li> </ol> </body> </html> It will produce the following result − Maths Social Science Physics Maths Social Science Physics Maths Social Science Physics Maths Social Science Physics Maths Social Science Physics Maths Social Science Physics The list-style-image allows you to specify an image so that you can use your own bullet style. The syntax is similar to the background-image property with the letters url starting the value of the property followed by the URL in brackets. If it does not find the given image then default bullets are used. Here is an example − <html> <head> </head> <body> <ul> <li style = "list-style-image: url(/images/bullet.gif);">Maths</li> <li>Social Science</li> <li>Physics</li> </ul> <ol> <li style = "list-style-image: url(/images/bullet.gif);">Maths</li> <li>Social Science</li> <li>Physics</li> </ol> </body> </html> It will produce the following result − Maths Social Science Physics Maths Social Science Physics Maths Social Science Physics The list-style allows you to specify all the list properties into a single expression. These properties can appear in any order. Here is an example − <html> <head> </head> <body> <ul style = "list-style: inside square;"> <li>Maths</li> <li>Social Science</li> <li>Physics</li> </ul> <ol style = "list-style: outside upper-alpha;"> <li>Maths</li> <li>Social Science</li> <li>Physics</li> </ol> </body> </html> It will produce the following result − Maths Social Science Physics Maths Social Science Physics Maths Social Science Physics The marker-offset property allows you to specify the distance between the marker and the text relating to that marker. Its value should be a length as shown in the following example − Unfortunately, this property is not supported in IE 6 or Netscape 7. Here is an example − <html> <head> </head> <body> <ul style = "list-style: inside square; marker-offset:2em;"> <li>Maths</li> <li>Social Science</li> <li>Physics</li> </ul> <ol style = "list-style: outside upper-alpha; marker-offset:2cm;"> <li>Maths</li> <li>Social Science</li> <li>Physics</li> </ol> </body> </html> It will produce the following result −
[ { "code": null, "e": 2924, "s": 2760, "text": "Lists are very helpful in conveying a set of either numbered or bullet points. This chapter teaches you how to control list type, position, style, etc., using CSS." }, { "code": null, "e": 3004, "s": 2924, "text": "We have the following five CSS properties, which can be used to control lists −" }, { "code": null, "e": 3085, "s": 3004, "text": "The list-style-type allows you to control the shape or appearance of the marker." }, { "code": null, "e": 3166, "s": 3085, "text": "The list-style-type allows you to control the shape or appearance of the marker." }, { "code": null, "e": 3327, "s": 3166, "text": "The list-style-position specifies whether a long point that wraps to a second line should align with the first line or start underneath the start of the marker." }, { "code": null, "e": 3488, "s": 3327, "text": "The list-style-position specifies whether a long point that wraps to a second line should align with the first line or start underneath the start of the marker." }, { "code": null, "e": 3581, "s": 3488, "text": "The list-style-image specifies an image for the marker rather than a bullet point or number." }, { "code": null, "e": 3674, "s": 3581, "text": "The list-style-image specifies an image for the marker rather than a bullet point or number." }, { "code": null, "e": 3739, "s": 3674, "text": "The list-style serves as shorthand for the preceding properties." }, { "code": null, "e": 3804, "s": 3739, "text": "The list-style serves as shorthand for the preceding properties." }, { "code": null, "e": 3888, "s": 3804, "text": "The marker-offset specifies the distance between a marker and the text in the list." }, { "code": null, "e": 3972, "s": 3888, "text": "The marker-offset specifies the distance between a marker and the text in the list." }, { "code": null, "e": 4032, "s": 3972, "text": "Now, we will see how to use these properties with examples." }, { "code": null, "e": 4230, "s": 4032, "text": "The list-style-type property allows you to control the shape or style of bullet point (also known as a marker) in the case of unordered lists and the style of numbering characters in ordered lists." }, { "code": null, "e": 4292, "s": 4230, "text": "Here are the values which can be used for an unordered list −" }, { "code": null, "e": 4297, "s": 4292, "text": "none" }, { "code": null, "e": 4300, "s": 4297, "text": "NA" }, { "code": null, "e": 4315, "s": 4300, "text": "disc (default)" }, { "code": null, "e": 4334, "s": 4315, "text": "A filled-in circle" }, { "code": null, "e": 4341, "s": 4334, "text": "circle" }, { "code": null, "e": 4357, "s": 4341, "text": "An empty circle" }, { "code": null, "e": 4364, "s": 4357, "text": "square" }, { "code": null, "e": 4383, "s": 4364, "text": "A filled-in square" }, { "code": null, "e": 4444, "s": 4383, "text": "Here are the values, which can be used for an ordered list −" }, { "code": null, "e": 4465, "s": 4444, "text": "Here is an example −" }, { "code": null, "e": 5266, "s": 4465, "text": "<html>\n <head>\n </head>\n \n <body>\n <ul style = \"list-style-type:circle;\">\n <li>Maths</li>\n <li>Social Science</li>\n <li>Physics</li>\n </ul>\n \n <ul style = \"list-style-type:square;\">\n <li>Maths</li>\n <li>Social Science</li>\n <li>Physics</li>\n </ul>\n \n <ol style = \"list-style-type:decimal;\">\n <li>Maths</li>\n <li>Social Science</li>\n <li>Physics</li>\n </ol>\n \n <ol style = \"list-style-type:lower-alpha;\">\n <li>Maths</li>\n <li>Social Science</li>\n <li>Physics</li>\n </ol>\n \n <ol style = \"list-style-type:lower-roman;\">\n <li>Maths</li>\n <li>Social Science</li>\n <li>Physics</li>\n </ol>\n </body>\n</html> " }, { "code": null, "e": 5305, "s": 5266, "text": "It will produce the following result −" }, { "code": null, "e": 5311, "s": 5305, "text": "Maths" }, { "code": null, "e": 5326, "s": 5311, "text": "Social Science" }, { "code": null, "e": 5334, "s": 5326, "text": "Physics" }, { "code": null, "e": 5340, "s": 5334, "text": "Maths" }, { "code": null, "e": 5355, "s": 5340, "text": "Social Science" }, { "code": null, "e": 5363, "s": 5355, "text": "Physics" }, { "code": null, "e": 5394, "s": 5363, "text": "\nMaths\nSocial Science\nPhysics\n" }, { "code": null, "e": 5400, "s": 5394, "text": "Maths" }, { "code": null, "e": 5415, "s": 5400, "text": "Social Science" }, { "code": null, "e": 5423, "s": 5415, "text": "Physics" }, { "code": null, "e": 5454, "s": 5423, "text": "\nMaths\nSocial Science\nPhysics\n" }, { "code": null, "e": 5460, "s": 5454, "text": "Maths" }, { "code": null, "e": 5475, "s": 5460, "text": "Social Science" }, { "code": null, "e": 5483, "s": 5475, "text": "Physics" }, { "code": null, "e": 5514, "s": 5483, "text": "\nMaths\nSocial Science\nPhysics\n" }, { "code": null, "e": 5520, "s": 5514, "text": "Maths" }, { "code": null, "e": 5535, "s": 5520, "text": "Social Science" }, { "code": null, "e": 5543, "s": 5535, "text": "Physics" }, { "code": null, "e": 5711, "s": 5543, "text": "The list-style-position property indicates whether the marker should appear inside or outside of the box containing the bullet points. It can have one the two values −" }, { "code": null, "e": 5716, "s": 5711, "text": "none" }, { "code": null, "e": 5719, "s": 5716, "text": "NA" }, { "code": null, "e": 5726, "s": 5719, "text": "inside" }, { "code": null, "e": 5907, "s": 5726, "text": "If the text goes onto a second line, the text will wrap underneath the marker. It will also appear indented to where the text would have started if the list had a value of outside." }, { "code": null, "e": 5915, "s": 5907, "text": "outside" }, { "code": null, "e": 6040, "s": 5915, "text": "If the text goes onto a second line, the text will be aligned with the start of the first line (to the right of the bullet)." }, { "code": null, "e": 6061, "s": 6040, "text": "Here is an example −" }, { "code": null, "e": 6821, "s": 6061, "text": "<html>\n <head>\n </head>\n \n <body>\n <ul style = \"list-style-type:circle; list-stlye-position:outside;\">\n <li>Maths</li>\n <li>Social Science</li>\n <li>Physics</li>\n </ul>\n \n <ul style = \"list-style-type:square;list-style-position:inside;\">\n <li>Maths</li>\n <li>Social Science</li>\n <li>Physics</li>\n </ul>\n \n <ol style = \"list-style-type:decimal;list-stlye-position:outside;\">\n <li>Maths</li>\n <li>Social Science</li>\n <li>Physics</li>\n </ol>\n \n <ol style = \"list-style-type:lower-alpha;list-style-position:inside;\">\n <li>Maths</li>\n <li>Social Science</li>\n <li>Physics</li>\n </ol>\n </body>\n</html> " }, { "code": null, "e": 6860, "s": 6821, "text": "It will produce the following result −" }, { "code": null, "e": 6866, "s": 6860, "text": "Maths" }, { "code": null, "e": 6881, "s": 6866, "text": "Social Science" }, { "code": null, "e": 6889, "s": 6881, "text": "Physics" }, { "code": null, "e": 6895, "s": 6889, "text": "Maths" }, { "code": null, "e": 6910, "s": 6895, "text": "Social Science" }, { "code": null, "e": 6918, "s": 6910, "text": "Physics" }, { "code": null, "e": 6949, "s": 6918, "text": "\nMaths\nSocial Science\nPhysics\n" }, { "code": null, "e": 6955, "s": 6949, "text": "Maths" }, { "code": null, "e": 6970, "s": 6955, "text": "Social Science" }, { "code": null, "e": 6978, "s": 6970, "text": "Physics" }, { "code": null, "e": 7009, "s": 6978, "text": "\nMaths\nSocial Science\nPhysics\n" }, { "code": null, "e": 7015, "s": 7009, "text": "Maths" }, { "code": null, "e": 7030, "s": 7015, "text": "Social Science" }, { "code": null, "e": 7038, "s": 7030, "text": "Physics" }, { "code": null, "e": 7344, "s": 7038, "text": "The list-style-image allows you to specify an image so that you can use your own bullet style. The syntax is similar to the background-image property with the letters url starting the value of the property followed by the URL in brackets. If it does not find the given image then default bullets are used." }, { "code": null, "e": 7365, "s": 7344, "text": "Here is an example −" }, { "code": null, "e": 7752, "s": 7365, "text": "<html>\n <head>\n </head>\n \n <body>\n <ul>\n <li style = \"list-style-image: url(/images/bullet.gif);\">Maths</li>\n <li>Social Science</li>\n <li>Physics</li>\n </ul>\n \n <ol>\n <li style = \"list-style-image: url(/images/bullet.gif);\">Maths</li>\n <li>Social Science</li>\n <li>Physics</li>\n </ol>\n </body>\n</html> " }, { "code": null, "e": 7791, "s": 7752, "text": "It will produce the following result −" }, { "code": null, "e": 7797, "s": 7791, "text": "Maths" }, { "code": null, "e": 7812, "s": 7797, "text": "Social Science" }, { "code": null, "e": 7820, "s": 7812, "text": "Physics" }, { "code": null, "e": 7851, "s": 7820, "text": "\nMaths\nSocial Science\nPhysics\n" }, { "code": null, "e": 7857, "s": 7851, "text": "Maths" }, { "code": null, "e": 7872, "s": 7857, "text": "Social Science" }, { "code": null, "e": 7880, "s": 7872, "text": "Physics" }, { "code": null, "e": 8009, "s": 7880, "text": "The list-style allows you to specify all the list properties into a single expression. These properties can appear in any order." }, { "code": null, "e": 8030, "s": 8009, "text": "Here is an example −" }, { "code": null, "e": 8391, "s": 8030, "text": "<html>\n <head>\n </head>\n \n <body>\n <ul style = \"list-style: inside square;\">\n <li>Maths</li>\n <li>Social Science</li>\n <li>Physics</li>\n </ul>\n \n <ol style = \"list-style: outside upper-alpha;\">\n <li>Maths</li>\n <li>Social Science</li>\n <li>Physics</li>\n </ol>\n </body>\n</html> " }, { "code": null, "e": 8430, "s": 8391, "text": "It will produce the following result −" }, { "code": null, "e": 8436, "s": 8430, "text": "Maths" }, { "code": null, "e": 8451, "s": 8436, "text": "Social Science" }, { "code": null, "e": 8459, "s": 8451, "text": "Physics" }, { "code": null, "e": 8490, "s": 8459, "text": "\nMaths\nSocial Science\nPhysics\n" }, { "code": null, "e": 8496, "s": 8490, "text": "Maths" }, { "code": null, "e": 8511, "s": 8496, "text": "Social Science" }, { "code": null, "e": 8519, "s": 8511, "text": "Physics" }, { "code": null, "e": 8703, "s": 8519, "text": "The marker-offset property allows you to specify the distance between the marker and the text relating to that marker. Its value should be a length as shown in the following example −" }, { "code": null, "e": 8772, "s": 8703, "text": "Unfortunately, this property is not supported in IE 6 or Netscape 7." }, { "code": null, "e": 8793, "s": 8772, "text": "Here is an example −" }, { "code": null, "e": 9188, "s": 8793, "text": "<html>\n <head>\n </head>\n\n <body>\n <ul style = \"list-style: inside square; marker-offset:2em;\">\n <li>Maths</li>\n <li>Social Science</li>\n <li>Physics</li>\n </ul>\n \n <ol style = \"list-style: outside upper-alpha; marker-offset:2cm;\">\n <li>Maths</li>\n <li>Social Science</li>\n <li>Physics</li>\n </ol>\n </body>\n</html>" } ]
Print even and odd numbers in increasing order using two threads in Java
27 Jan, 2022 Prerequisite: Multithreading Given an integer N, the task is to write Java Program to print the first N natural numbers in increasing order using two threads. Examples: Input: N = 10Output: 1 2 3 4 5 6 7 8 9 10 Input: N = 18Output: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 Approach: The idea is to create two threads and print even numbers with one thread and odd numbers with another thread. Below are the steps: Create two threads T1 and T2 using the below syntax, where T1 and T2 are used to print odd and even numbers respectively.Thread T1 = new Thread(new Runnable() { public void run() { mt.printEvenNumber(); }});Thread T2 = new Thread(new Runnable() { public void run() { mt.printOddNumber(); }});where,printOddNumber() is used to print all the odd numbers till N,printEvenNumber() is used to print all the even numbers till N. Thread T1 = new Thread(new Runnable() { public void run() { mt.printEvenNumber(); }}); Thread T2 = new Thread(new Runnable() { public void run() { mt.printOddNumber(); }}); where,printOddNumber() is used to print all the odd numbers till N,printEvenNumber() is used to print all the even numbers till N. Maintain a global counter variable and start both threads using the below function:T1.start();T2.start(); T1.start();T2.start(); If the counter is even in the Thread T1, then wait for the thread T2 to print that even number. Otherwise, print that odd number, increment the counter and notify to the Thread T2 using the function notify(). If the counter is odd in the Thread T2, then wait for the thread T1 to print that odd number. Otherwise, print that even number, increment the counter and notify the Thread T1 using the function notify(). Below is the implementation of the above approach: Java // Java program for the above approach public class GFG { // Starting counter int counter = 1; static int N; // Function to print odd numbers public void printOddNumber() { synchronized (this) { // Print number till the N while (counter < N) { // If count is even then print while (counter % 2 == 0) { // Exception handle try { wait(); } catch ( InterruptedException e) { e.printStackTrace(); } } // Print the number System.out.print(counter + " "); // Increment counter counter++; // Notify to second thread notify(); } } } // Function to print even numbers public void printEvenNumber() { synchronized (this) { // Print number till the N while (counter < N) { // If count is odd then print while (counter % 2 == 1) { // Exception handle try { wait(); } catch ( InterruptedException e) { e.printStackTrace(); } } // Print the number System.out.print( counter + " "); // Increment counter counter++; // Notify to 2nd thread notify(); } } } // Driver Code public static void main(String[] args) { // Given Number N N = 10; // Create an object of class GFG mt = new GFG(); // Create thread t1 Thread t1 = new Thread(new Runnable() { public void run() { mt.printEvenNumber(); } }); // Create thread t2 Thread t2 = new Thread(new Runnable() { public void run() { mt.printOddNumber(); } }); // Start both threads t1.start(); t2.start(); }} 1 2 3 4 5 6 7 8 9 10 Time Complexity: O(N)Auxiliary Space: O(1) rajpiyush72 Java-Multithreading Java Java Programs 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": 54, "s": 26, "text": "\n27 Jan, 2022" }, { "code": null, "e": 83, "s": 54, "text": "Prerequisite: Multithreading" }, { "code": null, "e": 213, "s": 83, "text": "Given an integer N, the task is to write Java Program to print the first N natural numbers in increasing order using two threads." }, { "code": null, "e": 223, "s": 213, "text": "Examples:" }, { "code": null, "e": 265, "s": 223, "text": "Input: N = 10Output: 1 2 3 4 5 6 7 8 9 10" }, { "code": null, "e": 331, "s": 265, "text": "Input: N = 18Output: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18" }, { "code": null, "e": 472, "s": 331, "text": "Approach: The idea is to create two threads and print even numbers with one thread and odd numbers with another thread. Below are the steps:" }, { "code": null, "e": 915, "s": 472, "text": "Create two threads T1 and T2 using the below syntax, where T1 and T2 are used to print odd and even numbers respectively.Thread T1 = new Thread(new Runnable() { public void run() { mt.printEvenNumber(); }});Thread T2 = new Thread(new Runnable() { public void run() { mt.printOddNumber(); }});where,printOddNumber() is used to print all the odd numbers till N,printEvenNumber() is used to print all the even numbers till N." }, { "code": null, "e": 1012, "s": 915, "text": "Thread T1 = new Thread(new Runnable() { public void run() { mt.printEvenNumber(); }});" }, { "code": null, "e": 1108, "s": 1012, "text": "Thread T2 = new Thread(new Runnable() { public void run() { mt.printOddNumber(); }});" }, { "code": null, "e": 1239, "s": 1108, "text": "where,printOddNumber() is used to print all the odd numbers till N,printEvenNumber() is used to print all the even numbers till N." }, { "code": null, "e": 1345, "s": 1239, "text": "Maintain a global counter variable and start both threads using the below function:T1.start();T2.start();" }, { "code": null, "e": 1368, "s": 1345, "text": "T1.start();T2.start();" }, { "code": null, "e": 1577, "s": 1368, "text": "If the counter is even in the Thread T1, then wait for the thread T2 to print that even number. Otherwise, print that odd number, increment the counter and notify to the Thread T2 using the function notify()." }, { "code": null, "e": 1782, "s": 1577, "text": "If the counter is odd in the Thread T2, then wait for the thread T1 to print that odd number. Otherwise, print that even number, increment the counter and notify the Thread T1 using the function notify()." }, { "code": null, "e": 1833, "s": 1782, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 1838, "s": 1833, "text": "Java" }, { "code": "// Java program for the above approach public class GFG { // Starting counter int counter = 1; static int N; // Function to print odd numbers public void printOddNumber() { synchronized (this) { // Print number till the N while (counter < N) { // If count is even then print while (counter % 2 == 0) { // Exception handle try { wait(); } catch ( InterruptedException e) { e.printStackTrace(); } } // Print the number System.out.print(counter + \" \"); // Increment counter counter++; // Notify to second thread notify(); } } } // Function to print even numbers public void printEvenNumber() { synchronized (this) { // Print number till the N while (counter < N) { // If count is odd then print while (counter % 2 == 1) { // Exception handle try { wait(); } catch ( InterruptedException e) { e.printStackTrace(); } } // Print the number System.out.print( counter + \" \"); // Increment counter counter++; // Notify to 2nd thread notify(); } } } // Driver Code public static void main(String[] args) { // Given Number N N = 10; // Create an object of class GFG mt = new GFG(); // Create thread t1 Thread t1 = new Thread(new Runnable() { public void run() { mt.printEvenNumber(); } }); // Create thread t2 Thread t2 = new Thread(new Runnable() { public void run() { mt.printOddNumber(); } }); // Start both threads t1.start(); t2.start(); }}", "e": 4169, "s": 1838, "text": null }, { "code": null, "e": 4191, "s": 4169, "text": "1 2 3 4 5 6 7 8 9 10\n" }, { "code": null, "e": 4234, "s": 4191, "text": "Time Complexity: O(N)Auxiliary Space: O(1)" }, { "code": null, "e": 4246, "s": 4234, "text": "rajpiyush72" }, { "code": null, "e": 4266, "s": 4246, "text": "Java-Multithreading" }, { "code": null, "e": 4271, "s": 4266, "text": "Java" }, { "code": null, "e": 4285, "s": 4271, "text": "Java Programs" }, { "code": null, "e": 4290, "s": 4285, "text": "Java" }, { "code": null, "e": 4388, "s": 4290, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4403, "s": 4388, "text": "Stream In Java" }, { "code": null, "e": 4424, "s": 4403, "text": "Introduction to Java" }, { "code": null, "e": 4445, "s": 4424, "text": "Constructors in Java" }, { "code": null, "e": 4464, "s": 4445, "text": "Exceptions in Java" }, { "code": null, "e": 4481, "s": 4464, "text": "Generics in Java" }, { "code": null, "e": 4507, "s": 4481, "text": "Java Programming Examples" }, { "code": null, "e": 4541, "s": 4507, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 4588, "s": 4541, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 4626, "s": 4588, "text": "Factory method design pattern in Java" } ]
SQLite - PRIMARY KEY
A primary key is a field in a table which uniquely identifies the each rows/records in a database table. Primary keys must contain unique values. A primary key column cannot have NULL values. A table can have only one primary key, which may consist of single or multiple fields. When multiple fields are used as a primary key, they are called a composite key. If a table has a primary key defined on any field(s), then you cannot have two records having the same value of that field(s). Note: You would use these concepts while creating database tables. Here is the syntax to define ID attribute as a primary key in a COMPANY table. CREATE TABLE COMPANY( ID INT PRIMARY KEY , NAME TEXT NOT NULL, AGE INT NOT NULL UNIQUE, ADDRESS CHAR (25) , SALARY REAL , ); To create a PRIMARY KEY constraint on the "ID" column when COMPANY table already exists, use the following SQLite syntax − ALTER TABLE COMPANY ADD PRIMARY KEY (ID); For defining a PRIMARY KEY constraint on multiple columns, use the following SQLite syntax − CREATE TABLE COMPANY( ID INT PRIMARY KEY , NAME TEXT NOT NULL, AGE INT NOT NULL UNIQUE, ADDRESS CHAR (25) , SALARY REAL , ); To create a PRIMARY KEY constraint on the "ID" and "NAMES" columns when COMPANY table already exists, use the following SQLite syntax − ALTER TABLE COMPANY ADD CONSTRAINT PK_CUSTID PRIMARY KEY (ID, NAME); You can clear the primary key constraints from the table, Use syntax − ALTER TABLE COMPANY DROP PRIMARY KEY ;
[ { "code": null, "e": 2964, "s": 2772, "text": "A primary key is a field in a table which uniquely identifies the each rows/records in a database table. Primary keys must contain unique values. A primary key column cannot have NULL values." }, { "code": null, "e": 3132, "s": 2964, "text": "A table can have only one primary key, which may consist of single or multiple fields. When multiple fields are used as a primary key, they are called a composite key." }, { "code": null, "e": 3259, "s": 3132, "text": "If a table has a primary key defined on any field(s), then you cannot have two records having the same value of that field(s)." }, { "code": null, "e": 3326, "s": 3259, "text": "Note: You would use these concepts while creating database tables." }, { "code": null, "e": 3405, "s": 3326, "text": "Here is the syntax to define ID attribute as a primary key in a COMPANY table." }, { "code": null, "e": 3600, "s": 3405, "text": "CREATE TABLE COMPANY(\n ID INT PRIMARY KEY ,\n NAME TEXT NOT NULL,\n AGE INT NOT NULL UNIQUE,\n ADDRESS CHAR (25) ,\n SALARY REAL , \n \n);\n" }, { "code": null, "e": 3723, "s": 3600, "text": "To create a PRIMARY KEY constraint on the \"ID\" column when COMPANY table already exists, use the following SQLite syntax −" }, { "code": null, "e": 3766, "s": 3723, "text": "ALTER TABLE COMPANY ADD PRIMARY KEY (ID);\n" }, { "code": null, "e": 3859, "s": 3766, "text": "For defining a PRIMARY KEY constraint on multiple columns, use the following SQLite syntax −" }, { "code": null, "e": 4054, "s": 3859, "text": "CREATE TABLE COMPANY(\n ID INT PRIMARY KEY ,\n NAME TEXT NOT NULL,\n AGE INT NOT NULL UNIQUE,\n ADDRESS CHAR (25) ,\n SALARY REAL , \n \n);\n" }, { "code": null, "e": 4190, "s": 4054, "text": "To create a PRIMARY KEY constraint on the \"ID\" and \"NAMES\" columns when COMPANY table already exists, use the following SQLite syntax −" }, { "code": null, "e": 4264, "s": 4190, "text": "ALTER TABLE COMPANY \n ADD CONSTRAINT PK_CUSTID PRIMARY KEY (ID, NAME);\n" }, { "code": null, "e": 4335, "s": 4264, "text": "You can clear the primary key constraints from the table, Use syntax −" } ]
Correcting Words using NLTK in Python
18 Jul, 2021 nltk stands for Natural Language Toolkit and is a powerful suite consisting of libraries and programs that can be used for statistical natural language processing. The libraries can implement tokenization, classification, parsing, stemming, tagging, semantic reasoning, etc. This toolkit can make machines understand human language. We are going to use two methods for spelling correction. Each method takes a list of misspelled words and gives the suggestion of the correct word for each incorrect word. It tries to find a word in the list of correct spellings that has the shortest distance and the same initial letter as the misspelled word. It then returns the word which matches the given criteria. The methods can be differentiated on the basis of the distance measure they use to find the closest word. ‘words’ package from nltk is used as the dictionary of correct words. Jaccard distance, the opposite of the Jaccard coefficient, is used to measure the dissimilarity between two sample sets. We get Jaccard distance by subtracting the Jaccard coefficient from 1. We can also get it by dividing the difference between the sizes of the union and the intersection of two sets by the size of the union. We work with Q-grams (these are equivalent to N-grams) which are referred to as characters instead of tokens. Jaccard Distance is given by the following formula. Step 1: First, we install and import the nltk suite and Jaccard distance metric that we discussed before. ‘ngrams’ are used to get a set of co-occurring words in a given window and are imported from nltk.utils package. Python3 # importing the nltk suite import nltk # importing jaccard distance# and ngrams from nltk.utilfrom nltk.metrics.distance import jaccard_distancefrom nltk.util import ngrams Step 2: Now, we download the ‘words’ resource (which contains the list of correct spellings of words) from the nltk downloader and import it through nltk.corpus and assign it to correct_words. Python3 # Downloading and importing# package 'words' from nltk corpusnltk.download('words')from nltk.corpus import words correct_words = words.words() Step 3: We define the list of incorrect_words for which we need the correct spellings. Then we run a loop for each word in the incorrect words list in which we calculate the Jaccard distance of the incorrect word with each correct spelling word having the same initial letter in the form of bigrams of characters. We then sort them in ascending order so the shortest distance is on top and extract the word corresponding to it and print it. Python3 # list of incorrect spellings# that need to be corrected incorrect_words=['happpy', 'azmaing', 'intelliengt'] # loop for finding correct spellings# based on jaccard distance# and printing the correct wordfor word in incorrect_words: temp = [(jaccard_distance(set(ngrams(word, 2)), set(ngrams(w, 2))),w) for w in correct_words if w[0]==word[0]] print(sorted(temp, key = lambda val:val[0])[0][1]) Output: Output screenshot after implementing Jaccard Distance to find correct spelling words Edit Distance measures dissimilarity between two strings by finding the minimum number of operations needed to transform one string into the other. The transformations that can be performed are: Inserting a new character: bat -> bats (insertion of 's') Deleting an existing character. care -> car (deletion of 'e') Substituting an existing character. bin -> bit (substitution of n with t) Transposition of two existing consecutive characters. sing -> sign (transposition of ng to gn) Step 1: First of all, we install and import the nltk suite. Python3 # importing the nltk suite import nltk # importing edit distance from nltk.metrics.distance import edit_distance Step 2: Now, we download the ‘words’ resource (which contains correct spellings of words) from the nltk downloader and import it through nltk.corpus and assign it to correct_words. Python3 # Downloading and importing package 'words'nltk.download('words')from nltk.corpus import wordscorrect_words = words.words() Step 3: We define the list of incorrect_words for which we need the correct spellings. Then we run a loop for each word in the incorrect words list in which we calculate the Edit distance of the incorrect word with each correct spelling word having the same initial letter. We then sort them in ascending order so the shortest distance is on top and extract the word corresponding to it and print it. Python3 # list of incorrect spellings# that need to be corrected incorrect_words=['happpy', 'azmaing', 'intelliengt'] # loop for finding correct spellings# based on edit distance and# printing the correct wordsfor word in incorrect_words: temp = [(edit_distance(word, w),w) for w in correct_words if w[0]==word[0]] print(sorted(temp, key = lambda val:val[0])[0][1]) Output: Output screenshot after implementing Edit Distance to find correct spelling words Picked Python-nltk Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python | os.path.join() method Introduction To PYTHON Python OOPs Concepts How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Get unique values from a list Create a directory in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n18 Jul, 2021" }, { "code": null, "e": 362, "s": 28, "text": "nltk stands for Natural Language Toolkit and is a powerful suite consisting of libraries and programs that can be used for statistical natural language processing. The libraries can implement tokenization, classification, parsing, stemming, tagging, semantic reasoning, etc. This toolkit can make machines understand human language. " }, { "code": null, "e": 910, "s": 362, "text": "We are going to use two methods for spelling correction. Each method takes a list of misspelled words and gives the suggestion of the correct word for each incorrect word. It tries to find a word in the list of correct spellings that has the shortest distance and the same initial letter as the misspelled word. It then returns the word which matches the given criteria. The methods can be differentiated on the basis of the distance measure they use to find the closest word. ‘words’ package from nltk is used as the dictionary of correct words." }, { "code": null, "e": 1400, "s": 910, "text": "Jaccard distance, the opposite of the Jaccard coefficient, is used to measure the dissimilarity between two sample sets. We get Jaccard distance by subtracting the Jaccard coefficient from 1. We can also get it by dividing the difference between the sizes of the union and the intersection of two sets by the size of the union. We work with Q-grams (these are equivalent to N-grams) which are referred to as characters instead of tokens. Jaccard Distance is given by the following formula." }, { "code": null, "e": 1619, "s": 1400, "text": "Step 1: First, we install and import the nltk suite and Jaccard distance metric that we discussed before. ‘ngrams’ are used to get a set of co-occurring words in a given window and are imported from nltk.utils package." }, { "code": null, "e": 1627, "s": 1619, "text": "Python3" }, { "code": "# importing the nltk suite import nltk # importing jaccard distance# and ngrams from nltk.utilfrom nltk.metrics.distance import jaccard_distancefrom nltk.util import ngrams", "e": 1801, "s": 1627, "text": null }, { "code": null, "e": 1994, "s": 1801, "text": "Step 2: Now, we download the ‘words’ resource (which contains the list of correct spellings of words) from the nltk downloader and import it through nltk.corpus and assign it to correct_words." }, { "code": null, "e": 2002, "s": 1994, "text": "Python3" }, { "code": "# Downloading and importing# package 'words' from nltk corpusnltk.download('words')from nltk.corpus import words correct_words = words.words()", "e": 2148, "s": 2002, "text": null }, { "code": null, "e": 2589, "s": 2148, "text": "Step 3: We define the list of incorrect_words for which we need the correct spellings. Then we run a loop for each word in the incorrect words list in which we calculate the Jaccard distance of the incorrect word with each correct spelling word having the same initial letter in the form of bigrams of characters. We then sort them in ascending order so the shortest distance is on top and extract the word corresponding to it and print it." }, { "code": null, "e": 2597, "s": 2589, "text": "Python3" }, { "code": "# list of incorrect spellings# that need to be corrected incorrect_words=['happpy', 'azmaing', 'intelliengt'] # loop for finding correct spellings# based on jaccard distance# and printing the correct wordfor word in incorrect_words: temp = [(jaccard_distance(set(ngrams(word, 2)), set(ngrams(w, 2))),w) for w in correct_words if w[0]==word[0]] print(sorted(temp, key = lambda val:val[0])[0][1])", "e": 3039, "s": 2597, "text": null }, { "code": null, "e": 3047, "s": 3039, "text": "Output:" }, { "code": null, "e": 3132, "s": 3047, "text": "Output screenshot after implementing Jaccard Distance to find correct spelling words" }, { "code": null, "e": 3327, "s": 3132, "text": "Edit Distance measures dissimilarity between two strings by finding the minimum number of operations needed to transform one string into the other. The transformations that can be performed are:" }, { "code": null, "e": 3355, "s": 3327, "text": "Inserting a new character: " }, { "code": null, "e": 3386, "s": 3355, "text": "bat -> bats (insertion of 's')" }, { "code": null, "e": 3419, "s": 3386, "text": "Deleting an existing character. " }, { "code": null, "e": 3449, "s": 3419, "text": "care -> car (deletion of 'e')" }, { "code": null, "e": 3485, "s": 3449, "text": "Substituting an existing character." }, { "code": null, "e": 3523, "s": 3485, "text": "bin -> bit (substitution of n with t)" }, { "code": null, "e": 3578, "s": 3523, "text": "Transposition of two existing consecutive characters. " }, { "code": null, "e": 3619, "s": 3578, "text": "sing -> sign (transposition of ng to gn)" }, { "code": null, "e": 3679, "s": 3619, "text": "Step 1: First of all, we install and import the nltk suite." }, { "code": null, "e": 3687, "s": 3679, "text": "Python3" }, { "code": "# importing the nltk suite import nltk # importing edit distance from nltk.metrics.distance import edit_distance", "e": 3803, "s": 3687, "text": null }, { "code": null, "e": 3984, "s": 3803, "text": "Step 2: Now, we download the ‘words’ resource (which contains correct spellings of words) from the nltk downloader and import it through nltk.corpus and assign it to correct_words." }, { "code": null, "e": 3992, "s": 3984, "text": "Python3" }, { "code": "# Downloading and importing package 'words'nltk.download('words')from nltk.corpus import wordscorrect_words = words.words()", "e": 4116, "s": 3992, "text": null }, { "code": null, "e": 4517, "s": 4116, "text": "Step 3: We define the list of incorrect_words for which we need the correct spellings. Then we run a loop for each word in the incorrect words list in which we calculate the Edit distance of the incorrect word with each correct spelling word having the same initial letter. We then sort them in ascending order so the shortest distance is on top and extract the word corresponding to it and print it." }, { "code": null, "e": 4525, "s": 4517, "text": "Python3" }, { "code": "# list of incorrect spellings# that need to be corrected incorrect_words=['happpy', 'azmaing', 'intelliengt'] # loop for finding correct spellings# based on edit distance and# printing the correct wordsfor word in incorrect_words: temp = [(edit_distance(word, w),w) for w in correct_words if w[0]==word[0]] print(sorted(temp, key = lambda val:val[0])[0][1])", "e": 4890, "s": 4525, "text": null }, { "code": null, "e": 4898, "s": 4890, "text": "Output:" }, { "code": null, "e": 4980, "s": 4898, "text": "Output screenshot after implementing Edit Distance to find correct spelling words" }, { "code": null, "e": 4987, "s": 4980, "text": "Picked" }, { "code": null, "e": 4999, "s": 4987, "text": "Python-nltk" }, { "code": null, "e": 5006, "s": 4999, "text": "Python" }, { "code": null, "e": 5104, "s": 5006, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5136, "s": 5104, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 5163, "s": 5136, "text": "Python Classes and Objects" }, { "code": null, "e": 5194, "s": 5163, "text": "Python | os.path.join() method" }, { "code": null, "e": 5217, "s": 5194, "text": "Introduction To PYTHON" }, { "code": null, "e": 5238, "s": 5217, "text": "Python OOPs Concepts" }, { "code": null, "e": 5294, "s": 5238, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 5336, "s": 5294, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 5378, "s": 5336, "text": "Check if element exists in list in Python" }, { "code": null, "e": 5417, "s": 5378, "text": "Python | Get unique values from a list" } ]
Add packages to Anaconda environment in Python
21 Aug, 2021 Let’s see some methods that can be used to install packages to Anaconda environment. There are many ways one can add pre-built packages to anaconda environment. So, let’s see how to direct the path in anaconda and install them. Using pip command : Open Anaconda Command prompt as administratorUse cd\ to come out of set directory or path.Run pip install command. Open Anaconda Command prompt as administrator Use cd\ to come out of set directory or path. Run pip install command. pip install numpy pip install scikit-learn Using git : Download git filesClone or download git hub files in some directory.Open Anaconda Command prompt as administrator.Use cd C:\Users\... to locate downloaded site.Then run pip install setup.py. Download git files Clone or download git hub files in some directory. Open Anaconda Command prompt as administrator. Use cd C:\Users\... to locate downloaded site. Then run pip install setup.py. Using wheel : Download wheel package.Download binary files or .whl file from authentic website.Open Anaconda Command prompt as administrator.Use cd C:\Users\... to locate downloaded site.Then run pip install ___.whl Download wheel package. Download binary files or .whl file from authentic website. Open Anaconda Command prompt as administrator. Use cd C:\Users\... to locate downloaded site. Then run pip install ___.whl Using Conda forge Command : This type of installation will guarantee that package will be downloaded to the system. Because this type of installation resolves environments, package-package conflicts, etc. Self Upgrade related packages to the downloading package.Open Anaconda Command prompt as administrator.Then run conda install -c conda-forge ____ Self Upgrade related packages to the downloading package. Open Anaconda Command prompt as administrator. Then run conda install -c conda-forge ____ conda install -c conda-forge opencv surindertarika1234 python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n21 Aug, 2021" }, { "code": null, "e": 139, "s": 53, "text": "Let’s see some methods that can be used to install packages to Anaconda environment. " }, { "code": null, "e": 283, "s": 139, "text": "There are many ways one can add pre-built packages to anaconda environment. So, let’s see how to direct the path in anaconda and install them. " }, { "code": null, "e": 304, "s": 283, "text": "Using pip command : " }, { "code": null, "e": 420, "s": 304, "text": "Open Anaconda Command prompt as administratorUse cd\\ to come out of set directory or path.Run pip install command. " }, { "code": null, "e": 466, "s": 420, "text": "Open Anaconda Command prompt as administrator" }, { "code": null, "e": 512, "s": 466, "text": "Use cd\\ to come out of set directory or path." }, { "code": null, "e": 538, "s": 512, "text": "Run pip install command. " }, { "code": null, "e": 581, "s": 538, "text": "pip install numpy\npip install scikit-learn" }, { "code": null, "e": 596, "s": 581, "text": " Using git : " }, { "code": null, "e": 787, "s": 596, "text": "Download git filesClone or download git hub files in some directory.Open Anaconda Command prompt as administrator.Use cd C:\\Users\\... to locate downloaded site.Then run pip install setup.py." }, { "code": null, "e": 806, "s": 787, "text": "Download git files" }, { "code": null, "e": 857, "s": 806, "text": "Clone or download git hub files in some directory." }, { "code": null, "e": 904, "s": 857, "text": "Open Anaconda Command prompt as administrator." }, { "code": null, "e": 951, "s": 904, "text": "Use cd C:\\Users\\... to locate downloaded site." }, { "code": null, "e": 982, "s": 951, "text": "Then run pip install setup.py." }, { "code": null, "e": 1000, "s": 982, "text": " Using wheel : " }, { "code": null, "e": 1202, "s": 1000, "text": "Download wheel package.Download binary files or .whl file from authentic website.Open Anaconda Command prompt as administrator.Use cd C:\\Users\\... to locate downloaded site.Then run pip install ___.whl" }, { "code": null, "e": 1226, "s": 1202, "text": "Download wheel package." }, { "code": null, "e": 1285, "s": 1226, "text": "Download binary files or .whl file from authentic website." }, { "code": null, "e": 1332, "s": 1285, "text": "Open Anaconda Command prompt as administrator." }, { "code": null, "e": 1379, "s": 1332, "text": "Use cd C:\\Users\\... to locate downloaded site." }, { "code": null, "e": 1408, "s": 1379, "text": "Then run pip install ___.whl" }, { "code": null, "e": 1615, "s": 1408, "text": "Using Conda forge Command : This type of installation will guarantee that package will be downloaded to the system. Because this type of installation resolves environments, package-package conflicts, etc. " }, { "code": null, "e": 1761, "s": 1615, "text": "Self Upgrade related packages to the downloading package.Open Anaconda Command prompt as administrator.Then run conda install -c conda-forge ____" }, { "code": null, "e": 1819, "s": 1761, "text": "Self Upgrade related packages to the downloading package." }, { "code": null, "e": 1866, "s": 1819, "text": "Open Anaconda Command prompt as administrator." }, { "code": null, "e": 1909, "s": 1866, "text": "Then run conda install -c conda-forge ____" }, { "code": null, "e": 1946, "s": 1909, "text": "conda install -c conda-forge opencv " }, { "code": null, "e": 1965, "s": 1946, "text": "surindertarika1234" }, { "code": null, "e": 1980, "s": 1965, "text": "python-utility" }, { "code": null, "e": 1987, "s": 1980, "text": "Python" } ]
Python | Convert flattened dictionary into nested dictionary
16 Aug, 2021 Given a flattened dictionary, the task is to convert that dictionary into a nested dictionary where keys are needed to be split at ‘_’ considering where nested dictionary will be started. Method #1: Using Naive Approach Python3 # Python code to demonstrate# conversion of flattened dictionary# into nested dictionary def insert(dct, lst): for x in lst[:-2]: dct[x] = dct = dct.get(x, dict()) dct.update({lst[-2]: lst[-1]}) def convert_nested(dct): # empty dict to store the result result = dict() # create an iterator of lists # representing nested or hierarchical flow lists = ([*k.split("_"), v] for k, v in dct.items()) # insert each list into the result for lst in lists: insert(result, lst) return result # initialising_dictionaryini_dict = {'Geeks_for_for':1,'Geeks_for_geeks':4, 'for_geeks_Geeks':3,'geeks_Geeks_for':7} # printing initial dictionaryprint ("initial_dictionary", str(ini_dict)) # code to convert ini_dict to nested# dictionary splitting_dict_keys_split_dict = [[*a.split('_'), b] for a, b in ini_dict.items()] # printing final dictionaryprint ("final_dictionary", str(convert_nested(ini_dict))) Method #2: Using default dict and recursive approach Python3 # Python code to demonstrate# conversion of flattened dictionary# into nested dictionary # code to convert dict into nested dictdef nest_dict(dict1): result = {} for k, v in dict1.items(): # for each key call method split_rec which # will split keys to form recursively # nested dictionary split_rec(k, v, result) return result def split_rec(k, v, out): # splitting keys in dict # calling_recursively to break items on '_' k, *rest = k.split('_', 1) if rest: split_rec(rest[0], v, out.setdefault(k, {})) else: out[k] = v # initialising_dictionaryini_dict = {'Geeks_for_for':1,'Geeks_for_geeks':4, 'for_geeks_Geeks':3,'geeks_Geeks_for':7} # printing initial dictionaryprint ("initial_dictionary", str(ini_dict)) # printing final dictionaryprint ("final_dictionary", str(nest_dict(ini_dict))) Method #3: Using reduce and getitem Python3 # Python code to demonstrate# conversion of flattened dictionary# into nested dictionary from collections import defaultdictfrom functools import reducefrom operator import getitem def getFromDict(dataDict, mapList): # Iterate nested dictionary return reduce(getitem, mapList, dataDict) # instantiate nested defaultdict of defaultdictstree = lambda: defaultdict(tree)d = tree() # converting default_dict_to regular dictdef default_to_regular(d): """Convert nested defaultdict to regular dict of dicts.""" if isinstance(d, defaultdict): d = {k: default_to_regular(v) for k, v in d.items()} return d # initialising_dictionaryini_dict = {'Geeks_for_for':1,'Geeks_for_geeks':4, 'for_geeks_Geeks':3,'geeks_Geeks_for':7} # printing initial dictionaryprint ("initial_dictionary", str(ini_dict)) # code to convert ini_dict to nested dictionary# iterating_over_dictfor k, v in ini_dict.items(): # splitting keys * keys, final_key = k.split('_') getFromDict(d, keys)[final_key] = v # printing final dictionaryprint ("final_dictionary", str(default_to_regular(d))) simmytarika5 arorakashish0911 surindertarika1234 Python dictionary-programs Python-nested-dictionary Python Python Programs 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 Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python | Convert string dictionary to dictionary Python Program for Fibonacci numbers
[ { "code": null, "e": 28, "s": 0, "text": "\n16 Aug, 2021" }, { "code": null, "e": 216, "s": 28, "text": "Given a flattened dictionary, the task is to convert that dictionary into a nested dictionary where keys are needed to be split at ‘_’ considering where nested dictionary will be started." }, { "code": null, "e": 249, "s": 216, "text": "Method #1: Using Naive Approach " }, { "code": null, "e": 257, "s": 249, "text": "Python3" }, { "code": "# Python code to demonstrate# conversion of flattened dictionary# into nested dictionary def insert(dct, lst): for x in lst[:-2]: dct[x] = dct = dct.get(x, dict()) dct.update({lst[-2]: lst[-1]}) def convert_nested(dct): # empty dict to store the result result = dict() # create an iterator of lists # representing nested or hierarchical flow lists = ([*k.split(\"_\"), v] for k, v in dct.items()) # insert each list into the result for lst in lists: insert(result, lst) return result # initialising_dictionaryini_dict = {'Geeks_for_for':1,'Geeks_for_geeks':4, 'for_geeks_Geeks':3,'geeks_Geeks_for':7} # printing initial dictionaryprint (\"initial_dictionary\", str(ini_dict)) # code to convert ini_dict to nested# dictionary splitting_dict_keys_split_dict = [[*a.split('_'), b] for a, b in ini_dict.items()] # printing final dictionaryprint (\"final_dictionary\", str(convert_nested(ini_dict)))", "e": 1218, "s": 257, "text": null }, { "code": null, "e": 1274, "s": 1218, "text": " Method #2: Using default dict and recursive approach " }, { "code": null, "e": 1282, "s": 1274, "text": "Python3" }, { "code": "# Python code to demonstrate# conversion of flattened dictionary# into nested dictionary # code to convert dict into nested dictdef nest_dict(dict1): result = {} for k, v in dict1.items(): # for each key call method split_rec which # will split keys to form recursively # nested dictionary split_rec(k, v, result) return result def split_rec(k, v, out): # splitting keys in dict # calling_recursively to break items on '_' k, *rest = k.split('_', 1) if rest: split_rec(rest[0], v, out.setdefault(k, {})) else: out[k] = v # initialising_dictionaryini_dict = {'Geeks_for_for':1,'Geeks_for_geeks':4, 'for_geeks_Geeks':3,'geeks_Geeks_for':7} # printing initial dictionaryprint (\"initial_dictionary\", str(ini_dict)) # printing final dictionaryprint (\"final_dictionary\", str(nest_dict(ini_dict)))", "e": 2173, "s": 1282, "text": null }, { "code": null, "e": 2212, "s": 2173, "text": " Method #3: Using reduce and getitem " }, { "code": null, "e": 2220, "s": 2212, "text": "Python3" }, { "code": "# Python code to demonstrate# conversion of flattened dictionary# into nested dictionary from collections import defaultdictfrom functools import reducefrom operator import getitem def getFromDict(dataDict, mapList): # Iterate nested dictionary return reduce(getitem, mapList, dataDict) # instantiate nested defaultdict of defaultdictstree = lambda: defaultdict(tree)d = tree() # converting default_dict_to regular dictdef default_to_regular(d): \"\"\"Convert nested defaultdict to regular dict of dicts.\"\"\" if isinstance(d, defaultdict): d = {k: default_to_regular(v) for k, v in d.items()} return d # initialising_dictionaryini_dict = {'Geeks_for_for':1,'Geeks_for_geeks':4, 'for_geeks_Geeks':3,'geeks_Geeks_for':7} # printing initial dictionaryprint (\"initial_dictionary\", str(ini_dict)) # code to convert ini_dict to nested dictionary# iterating_over_dictfor k, v in ini_dict.items(): # splitting keys * keys, final_key = k.split('_') getFromDict(d, keys)[final_key] = v # printing final dictionaryprint (\"final_dictionary\", str(default_to_regular(d)))", "e": 3345, "s": 2220, "text": null }, { "code": null, "e": 3358, "s": 3345, "text": "simmytarika5" }, { "code": null, "e": 3375, "s": 3358, "text": "arorakashish0911" }, { "code": null, "e": 3394, "s": 3375, "text": "surindertarika1234" }, { "code": null, "e": 3421, "s": 3394, "text": "Python dictionary-programs" }, { "code": null, "e": 3446, "s": 3421, "text": "Python-nested-dictionary" }, { "code": null, "e": 3453, "s": 3446, "text": "Python" }, { "code": null, "e": 3469, "s": 3453, "text": "Python Programs" }, { "code": null, "e": 3567, "s": 3469, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3599, "s": 3567, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3626, "s": 3599, "text": "Python Classes and Objects" }, { "code": null, "e": 3647, "s": 3626, "text": "Python OOPs Concepts" }, { "code": null, "e": 3670, "s": 3647, "text": "Introduction To PYTHON" }, { "code": null, "e": 3726, "s": 3670, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 3748, "s": 3726, "text": "Defaultdict in Python" }, { "code": null, "e": 3787, "s": 3748, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 3825, "s": 3787, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 3874, "s": 3825, "text": "Python | Convert string dictionary to dictionary" } ]
Python – Closest Pair to Kth index element in Tuple
10 Jun, 2020 Sometimes, while working with Python records, we can have a problem in which we need to find the tuple nearest to certain tuple, query on a particular index. This kind of problem can have application in data domains such as web development. Let’s discuss certain ways in which this task can be performed. Input :test_list = [(3, 4), (78, 76), (2, 3), (9, 8), (19, 23)]tup = (17, 23)K = 2 Output : (19, 23)Input :test_list = [(3, 4, 9), (5, 6, 7)]tup = (1, 2, 5)K = 3Output : (5, 6, 7) Method #1 : Using enumerate() + loopThe combination of above functions offer brute force way to solve this problem. In this, we use enumerate() to monitor index and abs() to keep the minimum difference updated checked for each element over a loop. # Python3 code to demonstrate working of # Closest Pair to Kth index element in Tuple# Using enumerate() + loop # initializing listtest_list = [(3, 4), (78, 76), (2, 3), (9, 8), (19, 23)] # printing original listprint("The original list is : " + str(test_list)) # initializing tupletup = (17, 23) # initializing K K = 1 # Closest Pair to Kth index element in Tuple# Using enumerate() + loopmin_dif, res = 999999999, Nonefor idx, val in enumerate(test_list): dif = abs(tup[K - 1] - val[K - 1]) if dif < min_dif: min_dif, res = dif, idx # printing result print("The nearest tuple to Kth index element is : " + str(test_list[res])) The original list is : [(3, 4), (78, 76), (2, 3), (9, 8), (19, 23)] The nearest tuple to Kth index element is : (19, 23) Method #2 : Using min() + lambdaThe combination of above functions offer shorthand to solve this problem. In this, we use min() to find minimum element difference and lambda function is used to perform iterations and computations. # Python3 code to demonstrate working of # Closest Pair to Kth index element in Tuple# Using min() + lambda # initializing listtest_list = [(3, 4), (78, 76), (2, 3), (9, 8), (19, 23)] # printing original listprint("The original list is : " + str(test_list)) # initializing tupletup = (17, 23) # initializing K K = 1 # Closest Pair to Kth index element in Tuple# Using min() + lambdares = min(range(len(test_list)), key = lambda sub: abs(test_list[sub][K - 1] - tup[K - 1])) # printing result print("The nearest tuple to Kth index element is : " + str(test_list[res])) The original list is : [(3, 4), (78, 76), (2, 3), (9, 8), (19, 23)] The nearest tuple to Kth index element is : (19, 23) Python tuple-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n10 Jun, 2020" }, { "code": null, "e": 359, "s": 54, "text": "Sometimes, while working with Python records, we can have a problem in which we need to find the tuple nearest to certain tuple, query on a particular index. This kind of problem can have application in data domains such as web development. Let’s discuss certain ways in which this task can be performed." }, { "code": null, "e": 442, "s": 359, "text": "Input :test_list = [(3, 4), (78, 76), (2, 3), (9, 8), (19, 23)]tup = (17, 23)K = 2" }, { "code": null, "e": 539, "s": 442, "text": "Output : (19, 23)Input :test_list = [(3, 4, 9), (5, 6, 7)]tup = (1, 2, 5)K = 3Output : (5, 6, 7)" }, { "code": null, "e": 787, "s": 539, "text": "Method #1 : Using enumerate() + loopThe combination of above functions offer brute force way to solve this problem. In this, we use enumerate() to monitor index and abs() to keep the minimum difference updated checked for each element over a loop." }, { "code": "# Python3 code to demonstrate working of # Closest Pair to Kth index element in Tuple# Using enumerate() + loop # initializing listtest_list = [(3, 4), (78, 76), (2, 3), (9, 8), (19, 23)] # printing original listprint(\"The original list is : \" + str(test_list)) # initializing tupletup = (17, 23) # initializing K K = 1 # Closest Pair to Kth index element in Tuple# Using enumerate() + loopmin_dif, res = 999999999, Nonefor idx, val in enumerate(test_list): dif = abs(tup[K - 1] - val[K - 1]) if dif < min_dif: min_dif, res = dif, idx # printing result print(\"The nearest tuple to Kth index element is : \" + str(test_list[res])) ", "e": 1436, "s": 787, "text": null }, { "code": null, "e": 1558, "s": 1436, "text": "The original list is : [(3, 4), (78, 76), (2, 3), (9, 8), (19, 23)]\nThe nearest tuple to Kth index element is : (19, 23)\n" }, { "code": null, "e": 1791, "s": 1560, "text": "Method #2 : Using min() + lambdaThe combination of above functions offer shorthand to solve this problem. In this, we use min() to find minimum element difference and lambda function is used to perform iterations and computations." }, { "code": "# Python3 code to demonstrate working of # Closest Pair to Kth index element in Tuple# Using min() + lambda # initializing listtest_list = [(3, 4), (78, 76), (2, 3), (9, 8), (19, 23)] # printing original listprint(\"The original list is : \" + str(test_list)) # initializing tupletup = (17, 23) # initializing K K = 1 # Closest Pair to Kth index element in Tuple# Using min() + lambdares = min(range(len(test_list)), key = lambda sub: abs(test_list[sub][K - 1] - tup[K - 1])) # printing result print(\"The nearest tuple to Kth index element is : \" + str(test_list[res])) ", "e": 2366, "s": 1791, "text": null }, { "code": null, "e": 2488, "s": 2366, "text": "The original list is : [(3, 4), (78, 76), (2, 3), (9, 8), (19, 23)]\nThe nearest tuple to Kth index element is : (19, 23)\n" }, { "code": null, "e": 2510, "s": 2488, "text": "Python tuple-programs" }, { "code": null, "e": 2517, "s": 2510, "text": "Python" }, { "code": null, "e": 2533, "s": 2517, "text": "Python Programs" } ]
Sum 2D array in Python using map() function
In this tutorial, we are going to find the sum of a 2D array using map function in Python. The map function takes two arguments i.e., function and iterable. It passes every element of the iterable to the function and stores the result in map object. We can covert the map object into an iterable. Let's see how to find the sum of the 2D array using the map function. Initialize the 2D array using lists. Initialize the 2D array using lists. Pass the function sum and 2D array to the map function. Pass the function sum and 2D array to the map function. Find the sum of resultant map object and print it. Find the sum of resultant map object and print it. See the code below. Live Demo # initializing the 2D array array = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] # passing the sum, array to function result = list(map(sum, array)) # see the result values # it contains sum of every sub array print(result) If you run the above code, you will get the following output. [6, 15, 24] Now, find the sum of the result using the same sum function. # finding the sum of result print(sum(result)) If you add the above code snippet the above program and run it, you will get the following output. 45 If you have any doubts in the tutorial, mention them in the comment section.
[ { "code": null, "e": 1278, "s": 1187, "text": "In this tutorial, we are going to find the sum of a 2D array using map function in Python." }, { "code": null, "e": 1484, "s": 1278, "text": "The map function takes two arguments i.e., function and iterable. It passes every element of the iterable to the function and stores the result in map object. We can covert the map object into an iterable." }, { "code": null, "e": 1554, "s": 1484, "text": "Let's see how to find the sum of the 2D array using the map function." }, { "code": null, "e": 1591, "s": 1554, "text": "Initialize the 2D array using lists." }, { "code": null, "e": 1628, "s": 1591, "text": "Initialize the 2D array using lists." }, { "code": null, "e": 1684, "s": 1628, "text": "Pass the function sum and 2D array to the map function." }, { "code": null, "e": 1740, "s": 1684, "text": "Pass the function sum and 2D array to the map function." }, { "code": null, "e": 1791, "s": 1740, "text": "Find the sum of resultant map object and print it." }, { "code": null, "e": 1842, "s": 1791, "text": "Find the sum of resultant map object and print it." }, { "code": null, "e": 1862, "s": 1842, "text": "See the code below." }, { "code": null, "e": 1873, "s": 1862, "text": " Live Demo" }, { "code": null, "e": 2097, "s": 1873, "text": "# initializing the 2D array\narray = [\n [1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]\n]\n# passing the sum, array to function\nresult = list(map(sum, array))\n# see the result values\n# it contains sum of every sub array\nprint(result)" }, { "code": null, "e": 2159, "s": 2097, "text": "If you run the above code, you will get the following output." }, { "code": null, "e": 2171, "s": 2159, "text": "[6, 15, 24]" }, { "code": null, "e": 2232, "s": 2171, "text": "Now, find the sum of the result using the same sum function." }, { "code": null, "e": 2279, "s": 2232, "text": "# finding the sum of result\nprint(sum(result))" }, { "code": null, "e": 2378, "s": 2279, "text": "If you add the above code snippet the above program and run it, you will get the following output." }, { "code": null, "e": 2381, "s": 2378, "text": "45" }, { "code": null, "e": 2458, "s": 2381, "text": "If you have any doubts in the tutorial, mention them in the comment section." } ]
Number of non-decreasing sub-arrays of length K
03 Mar, 2022 Given an array arr[] of length N, the task is to find the number of non-decreasing sub-arrays of length K.Examples: Input: arr[] = {1, 2, 3, 2, 5}, K = 2 Output: 3 {1, 2}, {2, 3} and {2, 5} are the increasing subarrays of length 2.Input: arr[] = {1, 2, 3, 2, 5}, K = 1 Output: 5 Naive approach Generate all the sub-arrays of length K and then check whether the sub-array satisfies the condition. Thus, the time complexity of the approach will be O(N * K).Better approach: A better approach will be using two-pointer technique. Let’s say the current index is i. Find the largest index j, such that the sub-array arr[i...j] is non-decreasing. This can be achieved by simply incrementing the value of j starting from i + 1 and checking whether arr[j] is greater than arr[j – 1]. Let’s say the length of the sub-array found in the previous step is L. The number of sub-arrays of length K contained in it will be max(L – K + 1, 0). Now, update i = j and repeat the above steps while i is in the index range. 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; // Function to return the count of// increasing subarrays of length kint cntSubArrays(int* arr, int n, int k){ // To store the final result int res = 0; int i = 0; // Two pointer loop while (i < n) { // Initialising j int j = i + 1; // Looping till the subarray increases while (j < n and arr[j] >= arr[j - 1]) j++; // Updating the required count res += max(j - i - k + 1, 0); // Updating i i = j; } // Returning res return res;} // Driver codeint main(){ int arr[] = { 1, 2, 3, 2, 5 }; int n = sizeof(arr) / sizeof(int); int k = 2; cout << cntSubArrays(arr, n, k); return 0;} // Java implementation of the approachclass GFG{ // Function to return the count of// increasing subarrays of length kstatic int cntSubArrays(int []arr, int n, int k){ // To store the final result int res = 0; int i = 0; // Two pointer loop while (i < n) { // Initialising j int j = i + 1; // Looping till the subarray increases while (j < n && arr[j] >= arr[j - 1]) j++; // Updating the required count res += Math.max(j - i - k + 1, 0); // Updating i i = j; } // Returning res return res;} // Driver codepublic static void main(String []args){ int arr[] = { 1, 2, 3, 2, 5 }; int n = arr.length; int k = 2; System.out.println(cntSubArrays(arr, n, k));}} // This code is contributed by PrinciRaj1992 # Python3 implementation of the approach # Function to return the count of# increasing subarrays of length kdef cntSubArrays(arr, n, k) : # To store the final result res = 0; i = 0; # Two pointer loop while (i < n) : # Initialising j j = i + 1; # Looping till the subarray increases while (j < n and arr[j] >= arr[j - 1]) : j += 1; # Updating the required count res += max(j - i - k + 1, 0); # Updating i i = j; # Returning res return res; # Driver codeif __name__ == "__main__" : arr = [ 1, 2, 3, 2, 5 ]; n = len(arr); k = 2; print(cntSubArrays(arr, n, k)); # This code is contributed by AnkitRai01 // C# implementation of the approachusing System; class GFG{ // Function to return the count of// increasing subarrays of length kstatic int cntSubArrays(int []arr, int n, int k){ // To store the final result int res = 0; int i = 0; // Two pointer loop while (i < n) { // Initialising j int j = i + 1; // Looping till the subarray increases while (j < n && arr[j] >= arr[j - 1]) j++; // Updating the required count res += Math.Max(j - i - k + 1, 0); // Updating i i = j; } // Returning res return res;} // Driver codepublic static void Main(String []args){ int []arr = { 1, 2, 3, 2, 5 }; int n = arr.Length; int k = 2; Console.WriteLine(cntSubArrays(arr, n, k));}} // This code is contributed by Rajput-Ji <script> // Javascript implementation of the approach // Function to return the count of// increasing subarrays of length kfunction cntSubArrays(arr, n, k){ // To store the final result var res = 0; var i = 0; // Two pointer loop while (i < n) { // Initialising j var j = i + 1; // Looping till the subarray increases while (j < n && arr[j] >= arr[j - 1]) j++; // Updating the required count res += Math.max(j - i - k + 1, 0); // Updating i i = j; } // Returning res return res;} // Driver codevar arr = [ 1, 2, 3, 2, 5 ];var n = arr.length;var k = 2;document.write( cntSubArrays(arr, n, k)); </script> 3 Time Complexity: O(n)Auxiliary Space: O(1) ankthon princiraj1992 Rajput-Ji noob2000 singhh3010 subarray two-pointer-algorithm Arrays Mathematical two-pointer-algorithm Arrays Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n03 Mar, 2022" }, { "code": null, "e": 172, "s": 54, "text": "Given an array arr[] of length N, the task is to find the number of non-decreasing sub-arrays of length K.Examples: " }, { "code": null, "e": 337, "s": 172, "text": "Input: arr[] = {1, 2, 3, 2, 5}, K = 2 Output: 3 {1, 2}, {2, 3} and {2, 5} are the increasing subarrays of length 2.Input: arr[] = {1, 2, 3, 2, 5}, K = 1 Output: 5 " }, { "code": null, "e": 623, "s": 339, "text": "Naive approach Generate all the sub-arrays of length K and then check whether the sub-array satisfies the condition. Thus, the time complexity of the approach will be O(N * K).Better approach: A better approach will be using two-pointer technique. Let’s say the current index is i. " }, { "code": null, "e": 838, "s": 623, "text": "Find the largest index j, such that the sub-array arr[i...j] is non-decreasing. This can be achieved by simply incrementing the value of j starting from i + 1 and checking whether arr[j] is greater than arr[j – 1]." }, { "code": null, "e": 989, "s": 838, "text": "Let’s say the length of the sub-array found in the previous step is L. The number of sub-arrays of length K contained in it will be max(L – K + 1, 0)." }, { "code": null, "e": 1065, "s": 989, "text": "Now, update i = j and repeat the above steps while i is in the index range." }, { "code": null, "e": 1118, "s": 1065, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 1122, "s": 1118, "text": "C++" }, { "code": null, "e": 1127, "s": 1122, "text": "Java" }, { "code": null, "e": 1135, "s": 1127, "text": "Python3" }, { "code": null, "e": 1138, "s": 1135, "text": "C#" }, { "code": null, "e": 1149, "s": 1138, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the count of// increasing subarrays of length kint cntSubArrays(int* arr, int n, int k){ // To store the final result int res = 0; int i = 0; // Two pointer loop while (i < n) { // Initialising j int j = i + 1; // Looping till the subarray increases while (j < n and arr[j] >= arr[j - 1]) j++; // Updating the required count res += max(j - i - k + 1, 0); // Updating i i = j; } // Returning res return res;} // Driver codeint main(){ int arr[] = { 1, 2, 3, 2, 5 }; int n = sizeof(arr) / sizeof(int); int k = 2; cout << cntSubArrays(arr, n, k); return 0;}", "e": 1922, "s": 1149, "text": null }, { "code": "// Java implementation of the approachclass GFG{ // Function to return the count of// increasing subarrays of length kstatic int cntSubArrays(int []arr, int n, int k){ // To store the final result int res = 0; int i = 0; // Two pointer loop while (i < n) { // Initialising j int j = i + 1; // Looping till the subarray increases while (j < n && arr[j] >= arr[j - 1]) j++; // Updating the required count res += Math.max(j - i - k + 1, 0); // Updating i i = j; } // Returning res return res;} // Driver codepublic static void main(String []args){ int arr[] = { 1, 2, 3, 2, 5 }; int n = arr.length; int k = 2; System.out.println(cntSubArrays(arr, n, k));}} // This code is contributed by PrinciRaj1992", "e": 2739, "s": 1922, "text": null }, { "code": "# Python3 implementation of the approach # Function to return the count of# increasing subarrays of length kdef cntSubArrays(arr, n, k) : # To store the final result res = 0; i = 0; # Two pointer loop while (i < n) : # Initialising j j = i + 1; # Looping till the subarray increases while (j < n and arr[j] >= arr[j - 1]) : j += 1; # Updating the required count res += max(j - i - k + 1, 0); # Updating i i = j; # Returning res return res; # Driver codeif __name__ == \"__main__\" : arr = [ 1, 2, 3, 2, 5 ]; n = len(arr); k = 2; print(cntSubArrays(arr, n, k)); # This code is contributed by AnkitRai01", "e": 3461, "s": 2739, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ // Function to return the count of// increasing subarrays of length kstatic int cntSubArrays(int []arr, int n, int k){ // To store the final result int res = 0; int i = 0; // Two pointer loop while (i < n) { // Initialising j int j = i + 1; // Looping till the subarray increases while (j < n && arr[j] >= arr[j - 1]) j++; // Updating the required count res += Math.Max(j - i - k + 1, 0); // Updating i i = j; } // Returning res return res;} // Driver codepublic static void Main(String []args){ int []arr = { 1, 2, 3, 2, 5 }; int n = arr.Length; int k = 2; Console.WriteLine(cntSubArrays(arr, n, k));}} // This code is contributed by Rajput-Ji", "e": 4289, "s": 3461, "text": null }, { "code": "<script> // Javascript implementation of the approach // Function to return the count of// increasing subarrays of length kfunction cntSubArrays(arr, n, k){ // To store the final result var res = 0; var i = 0; // Two pointer loop while (i < n) { // Initialising j var j = i + 1; // Looping till the subarray increases while (j < n && arr[j] >= arr[j - 1]) j++; // Updating the required count res += Math.max(j - i - k + 1, 0); // Updating i i = j; } // Returning res return res;} // Driver codevar arr = [ 1, 2, 3, 2, 5 ];var n = arr.length;var k = 2;document.write( cntSubArrays(arr, n, k)); </script>", "e": 4989, "s": 4289, "text": null }, { "code": null, "e": 4991, "s": 4989, "text": "3" }, { "code": null, "e": 5037, "s": 4993, "text": "Time Complexity: O(n)Auxiliary Space: O(1) " }, { "code": null, "e": 5045, "s": 5037, "text": "ankthon" }, { "code": null, "e": 5059, "s": 5045, "text": "princiraj1992" }, { "code": null, "e": 5069, "s": 5059, "text": "Rajput-Ji" }, { "code": null, "e": 5078, "s": 5069, "text": "noob2000" }, { "code": null, "e": 5089, "s": 5078, "text": "singhh3010" }, { "code": null, "e": 5098, "s": 5089, "text": "subarray" }, { "code": null, "e": 5120, "s": 5098, "text": "two-pointer-algorithm" }, { "code": null, "e": 5127, "s": 5120, "text": "Arrays" }, { "code": null, "e": 5140, "s": 5127, "text": "Mathematical" }, { "code": null, "e": 5162, "s": 5140, "text": "two-pointer-algorithm" }, { "code": null, "e": 5169, "s": 5162, "text": "Arrays" }, { "code": null, "e": 5182, "s": 5169, "text": "Mathematical" } ]
Program for Celsius To Fahrenheit conversion
24 May, 2022 Given a Temperature ‘n’ in Celsius scale, your task is to convert it into Fahrenheit scale.Examples: Input : 0 Output : 32 Input : -40 Output : -40 Formula for converting Celsius scale to Fahrenheit scale T(°F) = T(°C) × 9/5 + 32 C C++ Java Python3 C# PHP Javascript /* Program to convert temperature from Celsius to Fahrenheit*/#include <stdio.h> //function for conversionfloat celsius_to_fahrenheit(float c){ return ((c * 9.0 / 5.0) + 32.0);} int main() { float c = 20.0; // passing parameter to function and printing the value printf("Temperature in Fahrenheit : %0.2f",celsius_to_fahrenheit(c)); return 0;} // CPP program to convert Celsius// scale to Fahrenheit scale#include <bits/stdc++.h>using namespace std; // function to convert Celsius// scale to Fahrenheit scalefloat Cel_To_Fah(float n){ return ((n * 9.0 / 5.0) + 32.0);} // driver codeint main(){ float n = 20.0; cout << Cel_To_Fah(n); return 0;} // Java program to convert Celsius// scale to Fahrenheit scaleclass GFG{// function to convert Celsius// scale to Fahrenheit scalestatic float Cel_To_Fah(float n){ return ((n * 9.0f / 5.0f) + 32.0f);} // Driver codepublic static void main(String[] args) { float n = 20.0f; System.out.println(Cel_To_Fah(n));}} // This code is contributed by Anant Agarwal. # Python code to convert Celsius scale# to Fahrenheit scaledef Cel_To_Fah(n): # Used the formula return (n*1.8)+32 # Driver Coden = 20print(int(Cel_To_Fah(n))) # This code is contributed by Chinmoy Lenka // C# program to convert Celsius// scale to Fahrenheit scaleusing System; class GFG { // function to convert Celsius// scale to Fahrenheit scalestatic float Cel_To_Fah(float n){ return ((n * 9.0f / 5.0f) + 32.0f);} // Driver codepublic static void Main(){ float n = 20.0f; Console.Write(Cel_To_Fah(n));}} // This code is contributed by Nitin Mittal. <?php// PHP program to convert Celsius// scale to Fahrenheit scale // function to convert Celsius// scale to Fahrenheit scalefunction Cel_To_Fah($n){ return (($n * 9.0 / 5.0) + 32.0);} // Driver Code $n = 20.0; echo Cel_To_Fah($n); // This code is contributed by nitin mittal?> <script> // Javascript program to convert Celsius// scale to Fahrenheit scale // function to convert Celsius// scale to Fahrenheit scalefunction Cel_To_Fah(n){ return ((n * 9.0 / 5.0) + 32.0);} // driver code let n = 20.0; document.write(Cel_To_Fah(n)); // This code is contributed by Mayank Tyagi </script> Output: 68 Time Complexity: O(1), as we are not using any loops. Auxiliary Space: O(1), as we are not using any extra space. nitin mittal mayanktyagi1709 sonawanejaydeep11 rkbhola5 rohitsingh07052 Mathematical School Programming Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Operators in C / C++ Sieve of Eratosthenes Prime Numbers Program to find GCD or HCF of two numbers Python Dictionary Reverse a string in Java Arrays in C/C++ Introduction To PYTHON Interfaces in Java
[ { "code": null, "e": 52, "s": 24, "text": "\n24 May, 2022" }, { "code": null, "e": 154, "s": 52, "text": "Given a Temperature ‘n’ in Celsius scale, your task is to convert it into Fahrenheit scale.Examples: " }, { "code": null, "e": 202, "s": 154, "text": "Input : 0\nOutput : 32\n\nInput : -40\nOutput : -40" }, { "code": null, "e": 260, "s": 202, "text": "Formula for converting Celsius scale to Fahrenheit scale " }, { "code": null, "e": 286, "s": 260, "text": " T(°F) = T(°C) × 9/5 + 32" }, { "code": null, "e": 288, "s": 286, "text": "C" }, { "code": null, "e": 292, "s": 288, "text": "C++" }, { "code": null, "e": 297, "s": 292, "text": "Java" }, { "code": null, "e": 305, "s": 297, "text": "Python3" }, { "code": null, "e": 308, "s": 305, "text": "C#" }, { "code": null, "e": 312, "s": 308, "text": "PHP" }, { "code": null, "e": 323, "s": 312, "text": "Javascript" }, { "code": "/* Program to convert temperature from Celsius to Fahrenheit*/#include <stdio.h> //function for conversionfloat celsius_to_fahrenheit(float c){ return ((c * 9.0 / 5.0) + 32.0);} int main() { float c = 20.0; // passing parameter to function and printing the value printf(\"Temperature in Fahrenheit : %0.2f\",celsius_to_fahrenheit(c)); return 0;}", "e": 686, "s": 323, "text": null }, { "code": "// CPP program to convert Celsius// scale to Fahrenheit scale#include <bits/stdc++.h>using namespace std; // function to convert Celsius// scale to Fahrenheit scalefloat Cel_To_Fah(float n){ return ((n * 9.0 / 5.0) + 32.0);} // driver codeint main(){ float n = 20.0; cout << Cel_To_Fah(n); return 0;}", "e": 1000, "s": 686, "text": null }, { "code": "// Java program to convert Celsius// scale to Fahrenheit scaleclass GFG{// function to convert Celsius// scale to Fahrenheit scalestatic float Cel_To_Fah(float n){ return ((n * 9.0f / 5.0f) + 32.0f);} // Driver codepublic static void main(String[] args) { float n = 20.0f; System.out.println(Cel_To_Fah(n));}} // This code is contributed by Anant Agarwal.", "e": 1365, "s": 1000, "text": null }, { "code": "# Python code to convert Celsius scale# to Fahrenheit scaledef Cel_To_Fah(n): # Used the formula return (n*1.8)+32 # Driver Coden = 20print(int(Cel_To_Fah(n))) # This code is contributed by Chinmoy Lenka", "e": 1580, "s": 1365, "text": null }, { "code": "// C# program to convert Celsius// scale to Fahrenheit scaleusing System; class GFG { // function to convert Celsius// scale to Fahrenheit scalestatic float Cel_To_Fah(float n){ return ((n * 9.0f / 5.0f) + 32.0f);} // Driver codepublic static void Main(){ float n = 20.0f; Console.Write(Cel_To_Fah(n));}} // This code is contributed by Nitin Mittal.", "e": 1944, "s": 1580, "text": null }, { "code": "<?php// PHP program to convert Celsius// scale to Fahrenheit scale // function to convert Celsius// scale to Fahrenheit scalefunction Cel_To_Fah($n){ return (($n * 9.0 / 5.0) + 32.0);} // Driver Code $n = 20.0; echo Cel_To_Fah($n); // This code is contributed by nitin mittal?>", "e": 2239, "s": 1944, "text": null }, { "code": "<script> // Javascript program to convert Celsius// scale to Fahrenheit scale // function to convert Celsius// scale to Fahrenheit scalefunction Cel_To_Fah(n){ return ((n * 9.0 / 5.0) + 32.0);} // driver code let n = 20.0; document.write(Cel_To_Fah(n)); // This code is contributed by Mayank Tyagi </script>", "e": 2558, "s": 2239, "text": null }, { "code": null, "e": 2567, "s": 2558, "text": "Output: " }, { "code": null, "e": 2570, "s": 2567, "text": "68" }, { "code": null, "e": 2624, "s": 2570, "text": "Time Complexity: O(1), as we are not using any loops." }, { "code": null, "e": 2684, "s": 2624, "text": "Auxiliary Space: O(1), as we are not using any extra space." }, { "code": null, "e": 2697, "s": 2684, "text": "nitin mittal" }, { "code": null, "e": 2713, "s": 2697, "text": "mayanktyagi1709" }, { "code": null, "e": 2731, "s": 2713, "text": "sonawanejaydeep11" }, { "code": null, "e": 2740, "s": 2731, "text": "rkbhola5" }, { "code": null, "e": 2756, "s": 2740, "text": "rohitsingh07052" }, { "code": null, "e": 2769, "s": 2756, "text": "Mathematical" }, { "code": null, "e": 2788, "s": 2769, "text": "School Programming" }, { "code": null, "e": 2801, "s": 2788, "text": "Mathematical" }, { "code": null, "e": 2899, "s": 2801, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2923, "s": 2899, "text": "Merge two sorted arrays" }, { "code": null, "e": 2944, "s": 2923, "text": "Operators in C / C++" }, { "code": null, "e": 2966, "s": 2944, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 2980, "s": 2966, "text": "Prime Numbers" }, { "code": null, "e": 3022, "s": 2980, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 3040, "s": 3022, "text": "Python Dictionary" }, { "code": null, "e": 3065, "s": 3040, "text": "Reverse a string in Java" }, { "code": null, "e": 3081, "s": 3065, "text": "Arrays in C/C++" }, { "code": null, "e": 3104, "s": 3081, "text": "Introduction To PYTHON" } ]
Python set operations (union, intersection, difference and symmetric difference)
18 Dec, 2017 This article demonstrates different operations on Python sets.Examples: Input : A = {0, 2, 4, 6, 8} B = {1, 2, 3, 4, 5} Output : Union : [0, 1, 2, 3, 4, 5, 6, 8] Intersection : [2, 4] Difference : [8, 0, 6] Symmetric difference : [0, 1, 3, 5, 6, 8] In Python, below quick operands can be used for different operations. | for union.& for intersection.– for difference^ for symmetric difference # Program to perform different set operations# as we do in mathematics # sets are defineA = {0, 2, 4, 6, 8};B = {1, 2, 3, 4, 5}; # unionprint("Union :", A | B) # intersectionprint("Intersection :", A & B) # differenceprint("Difference :", A - B) # symmetric differenceprint("Symmetric difference :", A ^ B) Output: ('Union :', set([0, 1, 2, 3, 4, 5, 6, 8])) ('Intersection :', set([2, 4])) ('Difference :', set([8, 0, 6])) ('Symmetric difference :', set([0, 1, 3, 5, 6, 8])) python-set Python python-set Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n18 Dec, 2017" }, { "code": null, "e": 125, "s": 53, "text": "This article demonstrates different operations on Python sets.Examples:" }, { "code": null, "e": 308, "s": 125, "text": "Input :\nA = {0, 2, 4, 6, 8}\nB = {1, 2, 3, 4, 5}\n\nOutput :\n Union : [0, 1, 2, 3, 4, 5, 6, 8]\n Intersection : [2, 4]\n Difference : [8, 0, 6]\n Symmetric difference : [0, 1, 3, 5, 6, 8]\n" }, { "code": null, "e": 378, "s": 308, "text": "In Python, below quick operands can be used for different operations." }, { "code": null, "e": 452, "s": 378, "text": "| for union.& for intersection.– for difference^ for symmetric difference" }, { "code": "# Program to perform different set operations# as we do in mathematics # sets are defineA = {0, 2, 4, 6, 8};B = {1, 2, 3, 4, 5}; # unionprint(\"Union :\", A | B) # intersectionprint(\"Intersection :\", A & B) # differenceprint(\"Difference :\", A - B) # symmetric differenceprint(\"Symmetric difference :\", A ^ B)", "e": 765, "s": 452, "text": null }, { "code": null, "e": 773, "s": 765, "text": "Output:" }, { "code": null, "e": 934, "s": 773, "text": "('Union :', set([0, 1, 2, 3, 4, 5, 6, 8]))\n('Intersection :', set([2, 4]))\n('Difference :', set([8, 0, 6]))\n('Symmetric difference :', set([0, 1, 3, 5, 6, 8]))\n" }, { "code": null, "e": 945, "s": 934, "text": "python-set" }, { "code": null, "e": 952, "s": 945, "text": "Python" }, { "code": null, "e": 963, "s": 952, "text": "python-set" } ]
Python | Pandas Series.str.isdigit()
23 Aug, 2019 Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas str.isdigit() method is used to check if all characters in each string in series are digits. Whitespace or any other character occurrence in the string would return false. If the number is in decimal, then also false will be returned since this is a string method and ‘.’ is a special character and not a decimal in strings. Syntax: Series.str.isdigit() Return Type: Boolean series, Null values might be included too depending upon caller series. To download the CSV used in code, click here. In the following examples, the data frame used contains data on some NBA players. The image of data frame before any operations is attached below. Example:In this example, .isdigit() method is applied on the Age column. Before doing any operations, null rows are removed using .dropna() to avoid errors.Since the Age column is imported as Float dtype, it is first converted into string using .astype() method. After that the isdigit() is applied twice, first on the original series and after that ‘.’ is removed using str.replace() method to see the output after removing special characters. # importing pandas moduleimport pandas as pd # making data framedata = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv") # removing null values to avoid errorsdata.dropna(inplace = True) # converting dtype to stringdata["Age"]= data["Age"].astype(str) # removing '.'data["Age new"]= data["Age"].str.replace(".", "") # creating bool series with original columndata["bool_series1"]= data["Age"].str.isdigit() # creating bool series with new columndata["bool_series2"]= data["Age new"].str.isdigit() # displaydata.head(10) Output:As shown in output image, the Boolean series was false until decimal was present in string. After removing it, the new series has True for all values. Akanksha_Rai Python pandas-series Python pandas-series-methods Python-pandas Python-pandas-series-str Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Aug, 2019" }, { "code": null, "e": 242, "s": 28, "text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier." }, { "code": null, "e": 574, "s": 242, "text": "Pandas str.isdigit() method is used to check if all characters in each string in series are digits. Whitespace or any other character occurrence in the string would return false. If the number is in decimal, then also false will be returned since this is a string method and ‘.’ is a special character and not a decimal in strings." }, { "code": null, "e": 603, "s": 574, "text": "Syntax: Series.str.isdigit()" }, { "code": null, "e": 696, "s": 603, "text": "Return Type: Boolean series, Null values might be included too depending upon caller series." }, { "code": null, "e": 742, "s": 696, "text": "To download the CSV used in code, click here." }, { "code": null, "e": 889, "s": 742, "text": "In the following examples, the data frame used contains data on some NBA players. The image of data frame before any operations is attached below." }, { "code": null, "e": 1334, "s": 889, "text": "Example:In this example, .isdigit() method is applied on the Age column. Before doing any operations, null rows are removed using .dropna() to avoid errors.Since the Age column is imported as Float dtype, it is first converted into string using .astype() method. After that the isdigit() is applied twice, first on the original series and after that ‘.’ is removed using str.replace() method to see the output after removing special characters." }, { "code": "# importing pandas moduleimport pandas as pd # making data framedata = pd.read_csv(\"https://media.geeksforgeeks.org/wp-content/uploads/nba.csv\") # removing null values to avoid errorsdata.dropna(inplace = True) # converting dtype to stringdata[\"Age\"]= data[\"Age\"].astype(str) # removing '.'data[\"Age new\"]= data[\"Age\"].str.replace(\".\", \"\") # creating bool series with original columndata[\"bool_series1\"]= data[\"Age\"].str.isdigit() # creating bool series with new columndata[\"bool_series2\"]= data[\"Age new\"].str.isdigit() # displaydata.head(10)", "e": 1885, "s": 1334, "text": null }, { "code": null, "e": 2043, "s": 1885, "text": "Output:As shown in output image, the Boolean series was false until decimal was present in string. After removing it, the new series has True for all values." }, { "code": null, "e": 2056, "s": 2043, "text": "Akanksha_Rai" }, { "code": null, "e": 2077, "s": 2056, "text": "Python pandas-series" }, { "code": null, "e": 2106, "s": 2077, "text": "Python pandas-series-methods" }, { "code": null, "e": 2120, "s": 2106, "text": "Python-pandas" }, { "code": null, "e": 2145, "s": 2120, "text": "Python-pandas-series-str" }, { "code": null, "e": 2152, "s": 2145, "text": "Python" } ]
How to Embed Matplotlib Graph in PyQt5?
20 Jan, 2022 In this article, we will see how we can plot the graphs in the PyQt5 window using matplotlib.Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. It was introduced by John Hunter in the year 2002. PyQt5 is cross-platform GUI toolkit, a set of Python bindings for Qt v5. One can develop an interactive desktop application with so much ease because of the tools and simplicity provided by this library. A GUI application consists of Front-end and Back-end. In order to plot graphs using Matplotlib in PyQt5 we need FigureCanvasQTAgg and NavigationToolbar2QT these are similar to the PyQt5 widgets these are embedding. NavigationToolbar2QT : It will provide the tool bar for the graph, It can be imported with the help of command given below from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar FigureCanvasQTAgg : It will provide the canvas for the graph, It can be imported with the help of command given below from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas Below is how FigureCanvasQTAgg and NavigationToolbar2QT looks like – Below is the implementation Python3 # importing various librariesimport sysfrom PyQt5.QtWidgets import QDialog, QApplication, QPushButton, QVBoxLayoutfrom matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvasfrom matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbarimport matplotlib.pyplot as pltimport random # main window# which inherits QDialogclass Window(QDialog): # constructor def __init__(self, parent=None): super(Window, self).__init__(parent) # a figure instance to plot on self.figure = plt.figure() # this is the Canvas Widget that # displays the 'figure'it takes the # 'figure' instance as a parameter to __init__ self.canvas = FigureCanvas(self.figure) # this is the Navigation widget # it takes the Canvas widget and a parent self.toolbar = NavigationToolbar(self.canvas, self) # Just some button connected to 'plot' method self.button = QPushButton('Plot') # adding action to the button self.button.clicked.connect(self.plot) # creating a Vertical Box layout layout = QVBoxLayout() # adding tool bar to the layout layout.addWidget(self.toolbar) # adding canvas to the layout layout.addWidget(self.canvas) # adding push button to the layout layout.addWidget(self.button) # setting layout to the main window self.setLayout(layout) # action called by the push button def plot(self): # random data data = [random.random() for i in range(10)] # clearing old figure self.figure.clear() # create an axis ax = self.figure.add_subplot(111) # plot data ax.plot(data, '*-') # refresh canvas self.canvas.draw() # driver codeif __name__ == '__main__': # creating apyqt5 application app = QApplication(sys.argv) # creating a window object main = Window() # showing the window main.show() # loop sys.exit(app.exec_()) Output : surinderdawra388 Python-matplotlib Python-PyQt Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n20 Jan, 2022" }, { "code": null, "e": 667, "s": 52, "text": "In this article, we will see how we can plot the graphs in the PyQt5 window using matplotlib.Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. It was introduced by John Hunter in the year 2002. PyQt5 is cross-platform GUI toolkit, a set of Python bindings for Qt v5. One can develop an interactive desktop application with so much ease because of the tools and simplicity provided by this library. A GUI application consists of Front-end and Back-end. " }, { "code": null, "e": 830, "s": 667, "text": "In order to plot graphs using Matplotlib in PyQt5 we need FigureCanvasQTAgg and NavigationToolbar2QT these are similar to the PyQt5 widgets these are embedding. " }, { "code": null, "e": 954, "s": 830, "text": "NavigationToolbar2QT : It will provide the tool bar for the graph, It can be imported with the help of command given below " }, { "code": null, "e": 1043, "s": 954, "text": "from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar" }, { "code": null, "e": 1164, "s": 1045, "text": "FigureCanvasQTAgg : It will provide the canvas for the graph, It can be imported with the help of command given below " }, { "code": null, "e": 1245, "s": 1164, "text": "from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas" }, { "code": null, "e": 1319, "s": 1248, "text": "Below is how FigureCanvasQTAgg and NavigationToolbar2QT looks like – " }, { "code": null, "e": 1349, "s": 1319, "text": "Below is the implementation " }, { "code": null, "e": 1357, "s": 1349, "text": "Python3" }, { "code": "# importing various librariesimport sysfrom PyQt5.QtWidgets import QDialog, QApplication, QPushButton, QVBoxLayoutfrom matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvasfrom matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbarimport matplotlib.pyplot as pltimport random # main window# which inherits QDialogclass Window(QDialog): # constructor def __init__(self, parent=None): super(Window, self).__init__(parent) # a figure instance to plot on self.figure = plt.figure() # this is the Canvas Widget that # displays the 'figure'it takes the # 'figure' instance as a parameter to __init__ self.canvas = FigureCanvas(self.figure) # this is the Navigation widget # it takes the Canvas widget and a parent self.toolbar = NavigationToolbar(self.canvas, self) # Just some button connected to 'plot' method self.button = QPushButton('Plot') # adding action to the button self.button.clicked.connect(self.plot) # creating a Vertical Box layout layout = QVBoxLayout() # adding tool bar to the layout layout.addWidget(self.toolbar) # adding canvas to the layout layout.addWidget(self.canvas) # adding push button to the layout layout.addWidget(self.button) # setting layout to the main window self.setLayout(layout) # action called by the push button def plot(self): # random data data = [random.random() for i in range(10)] # clearing old figure self.figure.clear() # create an axis ax = self.figure.add_subplot(111) # plot data ax.plot(data, '*-') # refresh canvas self.canvas.draw() # driver codeif __name__ == '__main__': # creating apyqt5 application app = QApplication(sys.argv) # creating a window object main = Window() # showing the window main.show() # loop sys.exit(app.exec_())", "e": 3472, "s": 1357, "text": null }, { "code": null, "e": 3483, "s": 3472, "text": "Output : " }, { "code": null, "e": 3502, "s": 3485, "text": "surinderdawra388" }, { "code": null, "e": 3520, "s": 3502, "text": "Python-matplotlib" }, { "code": null, "e": 3532, "s": 3520, "text": "Python-PyQt" }, { "code": null, "e": 3539, "s": 3532, "text": "Python" } ]
turtle.width() function in Python
20 Jul, 2020 The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support. This method is used to set or return the line thickness. Set the line thickness to width or return it. If resizemode is set to “auto” and turtleshape is a polygon, that polygon is drawn with the same line thickness. If no argument is given, the current pensize is returned. Syntax : turtle.width(width=None) turtle.pensize(width=None) Note: This method has Aliases: pensize and width and requires only one argument “width — positive number”. Below is the implementation of the above method with some examples : Example 1 : Python3 # import packageimport turtle # forward turtle by 100turtle.forward(100) # set turtle width to 4turtle.width(4) # forward turtle by 100# in right directionturtle.right(90)turtle.forward(100) Output : Example 2 : Python3 # import packageimport turtle # loop for patternfor i in range(15): # set turtle width turtle.width(15-i) # motion for pattern turtle.forward(50+15*i) turtle.right(90) Output : In this above example, we decrease the size of the turtle at every move so the size of the line of the outer lines is smaller than that of the inner lines. Python-turtle Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to iterate through Excel rows in Python? Rotate axis tick labels in Seaborn and Matplotlib Deque in Python Queue in Python Defaultdict in Python Check if element exists in list in Python Python Classes and Objects Bar Plot in Matplotlib reduce() in Python Python | Get unique values from a list
[ { "code": null, "e": 28, "s": 0, "text": "\n20 Jul, 2020" }, { "code": null, "e": 245, "s": 28, "text": "The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support." }, { "code": null, "e": 519, "s": 245, "text": "This method is used to set or return the line thickness. Set the line thickness to width or return it. If resizemode is set to “auto” and turtleshape is a polygon, that polygon is drawn with the same line thickness. If no argument is given, the current pensize is returned." }, { "code": null, "e": 528, "s": 519, "text": "Syntax :" }, { "code": null, "e": 581, "s": 528, "text": "turtle.width(width=None)\nturtle.pensize(width=None)\n" }, { "code": null, "e": 688, "s": 581, "text": "Note: This method has Aliases: pensize and width and requires only one argument “width — positive number”." }, { "code": null, "e": 757, "s": 688, "text": "Below is the implementation of the above method with some examples :" }, { "code": null, "e": 769, "s": 757, "text": "Example 1 :" }, { "code": null, "e": 777, "s": 769, "text": "Python3" }, { "code": "# import packageimport turtle # forward turtle by 100turtle.forward(100) # set turtle width to 4turtle.width(4) # forward turtle by 100# in right directionturtle.right(90)turtle.forward(100)", "e": 974, "s": 777, "text": null }, { "code": null, "e": 983, "s": 974, "text": "Output :" }, { "code": null, "e": 995, "s": 983, "text": "Example 2 :" }, { "code": null, "e": 1003, "s": 995, "text": "Python3" }, { "code": "# import packageimport turtle # loop for patternfor i in range(15): # set turtle width turtle.width(15-i) # motion for pattern turtle.forward(50+15*i) turtle.right(90)", "e": 1186, "s": 1003, "text": null }, { "code": null, "e": 1195, "s": 1186, "text": "Output :" }, { "code": null, "e": 1351, "s": 1195, "text": "In this above example, we decrease the size of the turtle at every move so the size of the line of the outer lines is smaller than that of the inner lines." }, { "code": null, "e": 1365, "s": 1351, "text": "Python-turtle" }, { "code": null, "e": 1372, "s": 1365, "text": "Python" }, { "code": null, "e": 1470, "s": 1372, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1515, "s": 1470, "text": "How to iterate through Excel rows in Python?" }, { "code": null, "e": 1565, "s": 1515, "text": "Rotate axis tick labels in Seaborn and Matplotlib" }, { "code": null, "e": 1581, "s": 1565, "text": "Deque in Python" }, { "code": null, "e": 1597, "s": 1581, "text": "Queue in Python" }, { "code": null, "e": 1619, "s": 1597, "text": "Defaultdict in Python" }, { "code": null, "e": 1661, "s": 1619, "text": "Check if element exists in list in Python" }, { "code": null, "e": 1688, "s": 1661, "text": "Python Classes and Objects" }, { "code": null, "e": 1711, "s": 1688, "text": "Bar Plot in Matplotlib" }, { "code": null, "e": 1730, "s": 1711, "text": "reduce() in Python" } ]
numpy string operations | find() function
23 Jan, 2019 numpy.core.defchararray.find(arr, sub, start=0, end=None) is another function for doing string operations in numpy.It returns the lowest index in the string where substring sub is found for each element in arr within the range start to end.It returns -1 otherwise. Parameters:arr : array_like of str or unicode.sub : [str or unicode] The substring which to be searched.start : [ int, optional] The starting location in each string.end : [ int, optional] The ending location in each string. Returns : [ndarray] Output array of ints. Code #1 : # Python program explaining# numpy.char.find() method # importing numpy as geekimport numpy as geek # input arrays in_arr = geek.array(['aAaAaA', 'baA', 'abBABba'])print ("Input array : ", in_arr) # output arrays out_arr = geek.char.find(in_arr, sub ='A')print ("Output array: ", out_arr) Input array : ['aAaAaA' 'baA' 'abBABba'] Output array: [1 2 3] Code #2 : # Python program explaining# numpy.char.find() method # importing numpy as geekimport numpy as geek # input arrays in_arr = geek.array(['aAaAaA', 'aA', 'abBABba'])print ("Input array : ", in_arr) # output arrays out_arr = geek.char.find(in_arr, sub ='a', start = 3, end = 7)print ("Output array: ", out_arr) Input array : ['aAaAaA' 'aA' 'abBABba'] Output array: [ 4 -1 6] Python numpy-String Operation Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Jan, 2019" }, { "code": null, "e": 293, "s": 28, "text": "numpy.core.defchararray.find(arr, sub, start=0, end=None) is another function for doing string operations in numpy.It returns the lowest index in the string where substring sub is found for each element in arr within the range start to end.It returns -1 otherwise." }, { "code": null, "e": 518, "s": 293, "text": "Parameters:arr : array_like of str or unicode.sub : [str or unicode] The substring which to be searched.start : [ int, optional] The starting location in each string.end : [ int, optional] The ending location in each string." }, { "code": null, "e": 560, "s": 518, "text": "Returns : [ndarray] Output array of ints." }, { "code": null, "e": 570, "s": 560, "text": "Code #1 :" }, { "code": "# Python program explaining# numpy.char.find() method # importing numpy as geekimport numpy as geek # input arrays in_arr = geek.array(['aAaAaA', 'baA', 'abBABba'])print (\"Input array : \", in_arr) # output arrays out_arr = geek.char.find(in_arr, sub ='A')print (\"Output array: \", out_arr) ", "e": 866, "s": 570, "text": null }, { "code": null, "e": 933, "s": 866, "text": "Input array : ['aAaAaA' 'baA' 'abBABba']\nOutput array: [1 2 3]\n\n" }, { "code": null, "e": 944, "s": 933, "text": " Code #2 :" }, { "code": "# Python program explaining# numpy.char.find() method # importing numpy as geekimport numpy as geek # input arrays in_arr = geek.array(['aAaAaA', 'aA', 'abBABba'])print (\"Input array : \", in_arr) # output arrays out_arr = geek.char.find(in_arr, sub ='a', start = 3, end = 7)print (\"Output array: \", out_arr) ", "e": 1259, "s": 944, "text": null }, { "code": null, "e": 1327, "s": 1259, "text": "Input array : ['aAaAaA' 'aA' 'abBABba']\nOutput array: [ 4 -1 6]\n" }, { "code": null, "e": 1357, "s": 1327, "text": "Python numpy-String Operation" }, { "code": null, "e": 1370, "s": 1357, "text": "Python-numpy" }, { "code": null, "e": 1377, "s": 1370, "text": "Python" } ]
Stack elements() method in Java with Example
24 Dec, 2018 The Java.util.Stack.elements() method of Stack class in Java is used to get the enumeration of the values present in the Stack. Syntax: Enumeration enu = Stack.elements() Parameters: The method does not take any parameters. Return value: The method returns an enumeration of the values of the Stack. Below programs are used to illustrate the working of the java.util.Stack.elements() method: Program 1: // Java code to illustrate the elements() methodimport java.util.*; public class Stack_Demo { public static void main(String[] args) { // Creating an empty Stack Stack<String> stack = new Stack<String>(); // Inserting elements into the table stack.add("Geeks"); stack.add("4"); stack.add("Geeks"); stack.add("Welcomes"); stack.add("You"); // Displaying the Stack System.out.println("The Stack is: " + stack); // Creating an empty enumeration to store Enumeration enu = stack.elements(); System.out.println("The enumeration of values are:"); // Displaying the Enumeration while (enu.hasMoreElements()) { System.out.println(enu.nextElement()); } }} The Stack is: [Geeks, 4, Geeks, Welcomes, You] The enumeration of values are: Geeks 4 Geeks Welcomes You Program 2 : import java.util.*; public class Stack_Demo { public static void main(String[] args) { // Creating an empty Stack Stack<Integer> stack = new Stack<Integer>(); // Inserting elements into the table stack.add(10); stack.add(15); stack.add(20); stack.add(25); stack.add(30); // Displaying the Stack System.out.println("The Stack is: " + stack); // Creating an empty enumeration to store Enumeration enu = stack.elements(); System.out.println("The enumeration of values are:"); // Displaying the Enumeration while (enu.hasMoreElements()) { System.out.println(enu.nextElement()); } }} The Stack is: [10, 15, 20, 25, 30] The enumeration of values are: 10 15 20 25 30 Java - util package Java-Collections Java-Functions Java-Stack Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n24 Dec, 2018" }, { "code": null, "e": 181, "s": 53, "text": "The Java.util.Stack.elements() method of Stack class in Java is used to get the enumeration of the values present in the Stack." }, { "code": null, "e": 189, "s": 181, "text": "Syntax:" }, { "code": null, "e": 224, "s": 189, "text": "Enumeration enu = Stack.elements()" }, { "code": null, "e": 277, "s": 224, "text": "Parameters: The method does not take any parameters." }, { "code": null, "e": 353, "s": 277, "text": "Return value: The method returns an enumeration of the values of the Stack." }, { "code": null, "e": 445, "s": 353, "text": "Below programs are used to illustrate the working of the java.util.Stack.elements() method:" }, { "code": null, "e": 456, "s": 445, "text": "Program 1:" }, { "code": "// Java code to illustrate the elements() methodimport java.util.*; public class Stack_Demo { public static void main(String[] args) { // Creating an empty Stack Stack<String> stack = new Stack<String>(); // Inserting elements into the table stack.add(\"Geeks\"); stack.add(\"4\"); stack.add(\"Geeks\"); stack.add(\"Welcomes\"); stack.add(\"You\"); // Displaying the Stack System.out.println(\"The Stack is: \" + stack); // Creating an empty enumeration to store Enumeration enu = stack.elements(); System.out.println(\"The enumeration of values are:\"); // Displaying the Enumeration while (enu.hasMoreElements()) { System.out.println(enu.nextElement()); } }}", "e": 1248, "s": 456, "text": null }, { "code": null, "e": 1354, "s": 1248, "text": "The Stack is: [Geeks, 4, Geeks, Welcomes, You]\nThe enumeration of values are:\nGeeks\n4\nGeeks\nWelcomes\nYou\n" }, { "code": null, "e": 1366, "s": 1354, "text": "Program 2 :" }, { "code": "import java.util.*; public class Stack_Demo { public static void main(String[] args) { // Creating an empty Stack Stack<Integer> stack = new Stack<Integer>(); // Inserting elements into the table stack.add(10); stack.add(15); stack.add(20); stack.add(25); stack.add(30); // Displaying the Stack System.out.println(\"The Stack is: \" + stack); // Creating an empty enumeration to store Enumeration enu = stack.elements(); System.out.println(\"The enumeration of values are:\"); // Displaying the Enumeration while (enu.hasMoreElements()) { System.out.println(enu.nextElement()); } }}", "e": 2090, "s": 1366, "text": null }, { "code": null, "e": 2172, "s": 2090, "text": "The Stack is: [10, 15, 20, 25, 30]\nThe enumeration of values are:\n10\n15\n20\n25\n30\n" }, { "code": null, "e": 2192, "s": 2172, "text": "Java - util package" }, { "code": null, "e": 2209, "s": 2192, "text": "Java-Collections" }, { "code": null, "e": 2224, "s": 2209, "text": "Java-Functions" }, { "code": null, "e": 2235, "s": 2224, "text": "Java-Stack" }, { "code": null, "e": 2240, "s": 2235, "text": "Java" }, { "code": null, "e": 2245, "s": 2240, "text": "Java" }, { "code": null, "e": 2262, "s": 2245, "text": "Java-Collections" } ]
Python - Remote Procedure Call
Remote Procedure Call (RPC) system enables you to call a function available on a remote server using the same syntax which is used when calling a function in a local library. This is useful in two situations. You can utilize the processing power from multiple machines using rpc without changing the code for making the call to the programs located in the remote systems. The data needed for the processing is available only in the remote system. So in python we can treat one machine as a server and another machine as a client which will make a call to the server to run the remote procedure. In our example we will take the localhost and use it as both a server and client. The python language comes with an in-built server which we can run as a local server. The script to run this server is located under the bin folder of python installation and named as classic.py. We can run it in the python prompt and check its running as a local server. python bin/classic.py When we run the above program, we get the following output − INFO:SLAVE/18812:server started on [127.0.0.1]:18812 Next we run the client using the rpyc module to execute a remote procedure call. In the below example we execute the print function in the remote server. import rpyc conn = rpyc.classic.connect("localhost") conn.execute("print('Hello from Tutorialspoint')") When we run the above program, we get the following output − Hello from Tutorialspoint Using the above code examples we can use python’s in-built functions for execution and evaluation of expressions through rpc. import rpyc conn = rpyc.classic.connect("localhost") conn.execute('import math') conn.eval('2*math.pi') When we run the above program, we get the following output −
[ { "code": null, "e": 2669, "s": 2460, "text": "Remote Procedure Call (RPC) system enables you to call a function available on a remote server using the same syntax which is used when calling a function in a local library. This is useful in two situations." }, { "code": null, "e": 2832, "s": 2669, "text": "You can utilize the processing power from multiple machines using rpc without changing the code for making the call to the programs located in the remote systems." }, { "code": null, "e": 2907, "s": 2832, "text": "The data needed for the processing is available only in the remote system." }, { "code": null, "e": 3138, "s": 2907, "text": "So in python we can treat one machine as a server and another machine as a client which will make a call to the server to run the remote procedure. In our example we will take the localhost and use it as both a server and client. " }, { "code": null, "e": 3410, "s": 3138, "text": "The python language comes with an in-built server which we can run as a local server. The script to run this server is located under the bin folder of python installation and named as classic.py. We can run it in the python prompt and check its running as a local server." }, { "code": null, "e": 3432, "s": 3410, "text": "python bin/classic.py" }, { "code": null, "e": 3493, "s": 3432, "text": "When we run the above program, we get the following output −" }, { "code": null, "e": 3548, "s": 3493, "text": "INFO:SLAVE/18812:server started on [127.0.0.1]:18812\n\n" }, { "code": null, "e": 3703, "s": 3548, "text": " Next we run the client using the rpyc module to execute a remote procedure call. In the below example we execute the print function in the remote server." }, { "code": null, "e": 3807, "s": 3703, "text": "import rpyc\nconn = rpyc.classic.connect(\"localhost\")\nconn.execute(\"print('Hello from Tutorialspoint')\")" }, { "code": null, "e": 3868, "s": 3807, "text": "When we run the above program, we get the following output −" }, { "code": null, "e": 3895, "s": 3868, "text": "Hello from Tutorialspoint\n" }, { "code": null, "e": 4021, "s": 3895, "text": "Using the above code examples we can use python’s in-built functions for execution and evaluation of expressions through rpc." }, { "code": null, "e": 4125, "s": 4021, "text": "import rpyc\nconn = rpyc.classic.connect(\"localhost\")\nconn.execute('import math')\nconn.eval('2*math.pi')" } ]
expr command in Linux with examples
15 May, 2019 The expr command in Unix evaluates a given expression and displays its corresponding output. It is used for: Basic operations like addition, subtraction, multiplication, division, and modulus on integers. Evaluating regular expressions, string operations like substring, length of strings etc. Syntax: $expr expression Options: Option –version : It is used to show the version information.Syntax:$expr --version Example: Syntax: $expr --version Example: Option –help : It is used to show the help message and exit.Syntax:$expr --help Example: Syntax: $expr --help Example: Below are some examples to demonstrate the use of “expr” command: 1. Using expr for basic arithmetic operations : Example: Addition $expr 12 + 8 Example: Multiplication $expr 12 \* 2 Output Note:The multiplication operator * must be escaped when used in an arithmetic expression with expr. 2. Performing operations on variables inside a shell script Example: Adding two numbers in a script echo "Enter two numbers" read x read y sum=`expr $x + $y` echo "Sum = $sum" Output: Note: expr is an external program used by Bourne shell. It uses expr external program with the help of backtick. The backtick(`) is actually called command substitution. 3. Comparing two expressions Example: x=10 y=20 # matching numbers with '=' res=`expr $x = $y` echo $res # displays 1 when arg1 is less than arg2 res=`expr $x \< $y` echo $res # display 1 when arg1 is not equal to arg2 res=`expr $x \!= $y` echo $res Output: Example: Evaluating boolean expressions # OR operation $expr length "geekss" "<" 5 "|" 19 - 6 ">" 10 Output: # AND operation $expr length "geekss" "<" 5 "&" 19 - 6 ">" 10 Output: 4. For String operations Example: Finding length of a string x=geeks len=`expr length $x` echo $len Output: Example: Finding substring of a string x=geeks sub=`expr substr $x 2 3` #extract 3 characters starting from index 2 echo $sub Output: Example: Matching number of characters in two strings $ expr geeks : geek Output: linux-command Linux-Shell-Commands Picked Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. tar command in Linux with examples curl command in Linux with Examples SORT command in Linux/Unix with examples Conditional Statements | Shell Script 'crontab' in Linux with Examples TCP Server-Client implementation in C Tail command in Linux with examples Docker - COPY Instruction scp command in Linux with Examples UDP Server-Client implementation in C
[ { "code": null, "e": 54, "s": 26, "text": "\n15 May, 2019" }, { "code": null, "e": 163, "s": 54, "text": "The expr command in Unix evaluates a given expression and displays its corresponding output. It is used for:" }, { "code": null, "e": 259, "s": 163, "text": "Basic operations like addition, subtraction, multiplication, division, and modulus on integers." }, { "code": null, "e": 348, "s": 259, "text": "Evaluating regular expressions, string operations like substring, length of strings etc." }, { "code": null, "e": 356, "s": 348, "text": "Syntax:" }, { "code": null, "e": 374, "s": 356, "text": "$expr expression\n" }, { "code": null, "e": 383, "s": 374, "text": "Options:" }, { "code": null, "e": 476, "s": 383, "text": "Option –version : It is used to show the version information.Syntax:$expr --version\nExample:" }, { "code": null, "e": 484, "s": 476, "text": "Syntax:" }, { "code": null, "e": 501, "s": 484, "text": "$expr --version\n" }, { "code": null, "e": 510, "s": 501, "text": "Example:" }, { "code": null, "e": 599, "s": 510, "text": "Option –help : It is used to show the help message and exit.Syntax:$expr --help\nExample:" }, { "code": null, "e": 607, "s": 599, "text": "Syntax:" }, { "code": null, "e": 621, "s": 607, "text": "$expr --help\n" }, { "code": null, "e": 630, "s": 621, "text": "Example:" }, { "code": null, "e": 696, "s": 630, "text": "Below are some examples to demonstrate the use of “expr” command:" }, { "code": null, "e": 744, "s": 696, "text": "1. Using expr for basic arithmetic operations :" }, { "code": null, "e": 762, "s": 744, "text": "Example: Addition" }, { "code": null, "e": 777, "s": 762, "text": "$expr 12 + 8 \n" }, { "code": null, "e": 801, "s": 777, "text": "Example: Multiplication" }, { "code": null, "e": 816, "s": 801, "text": "$expr 12 \\* 2\n" }, { "code": null, "e": 823, "s": 816, "text": "Output" }, { "code": null, "e": 923, "s": 823, "text": "Note:The multiplication operator * must be escaped when used in an arithmetic expression with expr." }, { "code": null, "e": 983, "s": 923, "text": "2. Performing operations on variables inside a shell script" }, { "code": null, "e": 1023, "s": 983, "text": "Example: Adding two numbers in a script" }, { "code": null, "e": 1105, "s": 1023, "text": "echo \"Enter two numbers\"\n\nread x \n\nread y\n\nsum=`expr $x + $y`\n\necho \"Sum = $sum\"\n" }, { "code": null, "e": 1113, "s": 1105, "text": "Output:" }, { "code": null, "e": 1283, "s": 1113, "text": "Note: expr is an external program used by Bourne shell. It uses expr external program with the help of backtick. The backtick(`) is actually called command substitution." }, { "code": null, "e": 1312, "s": 1283, "text": "3. Comparing two expressions" }, { "code": null, "e": 1321, "s": 1312, "text": "Example:" }, { "code": null, "e": 1538, "s": 1321, "text": "x=10\n\ny=20\n\n# matching numbers with '='\nres=`expr $x = $y`\necho $res\n\n# displays 1 when arg1 is less than arg2\nres=`expr $x \\< $y`\necho $res\n\n# display 1 when arg1 is not equal to arg2\nres=`expr $x \\!= $y`\necho $res\n" }, { "code": null, "e": 1546, "s": 1538, "text": "Output:" }, { "code": null, "e": 1586, "s": 1546, "text": "Example: Evaluating boolean expressions" }, { "code": null, "e": 1657, "s": 1586, "text": "# OR operation\n$expr length \"geekss\" \"<\" 5 \"|\" 19 - 6 \">\" 10\n" }, { "code": null, "e": 1665, "s": 1657, "text": "Output:" }, { "code": null, "e": 1737, "s": 1665, "text": "# AND operation\n$expr length \"geekss\" \"<\" 5 \"&\" 19 - 6 \">\" 10\n" }, { "code": null, "e": 1745, "s": 1737, "text": "Output:" }, { "code": null, "e": 1770, "s": 1745, "text": "4. For String operations" }, { "code": null, "e": 1806, "s": 1770, "text": "Example: Finding length of a string" }, { "code": null, "e": 1848, "s": 1806, "text": "x=geeks\n\nlen=`expr length $x`\n\necho $len\n" }, { "code": null, "e": 1856, "s": 1848, "text": "Output:" }, { "code": null, "e": 1895, "s": 1856, "text": "Example: Finding substring of a string" }, { "code": null, "e": 1986, "s": 1895, "text": "x=geeks\n\nsub=`expr substr $x 2 3` \n#extract 3 characters starting from index 2\n\necho $sub\n" }, { "code": null, "e": 1994, "s": 1986, "text": "Output:" }, { "code": null, "e": 2048, "s": 1994, "text": "Example: Matching number of characters in two strings" }, { "code": null, "e": 2069, "s": 2048, "text": "$ expr geeks : geek\n" }, { "code": null, "e": 2077, "s": 2069, "text": "Output:" }, { "code": null, "e": 2091, "s": 2077, "text": "linux-command" }, { "code": null, "e": 2112, "s": 2091, "text": "Linux-Shell-Commands" }, { "code": null, "e": 2119, "s": 2112, "text": "Picked" }, { "code": null, "e": 2130, "s": 2119, "text": "Linux-Unix" }, { "code": null, "e": 2228, "s": 2130, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2263, "s": 2228, "text": "tar command in Linux with examples" }, { "code": null, "e": 2299, "s": 2263, "text": "curl command in Linux with Examples" }, { "code": null, "e": 2340, "s": 2299, "text": "SORT command in Linux/Unix with examples" }, { "code": null, "e": 2378, "s": 2340, "text": "Conditional Statements | Shell Script" }, { "code": null, "e": 2411, "s": 2378, "text": "'crontab' in Linux with Examples" }, { "code": null, "e": 2449, "s": 2411, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 2485, "s": 2449, "text": "Tail command in Linux with examples" }, { "code": null, "e": 2511, "s": 2485, "text": "Docker - COPY Instruction" }, { "code": null, "e": 2546, "s": 2511, "text": "scp command in Linux with Examples" } ]
How to create comma separated list from an array in PHP ?
31 Jul, 2021 The comma separated list can be created by using implode() function. The implode() is a builtin function in PHP and is used to join the elements of an array. implode() is an alias for PHP | join() function and works exactly same as that of join() function.If we have an array of elements, we can use the implode() function to join them all to form one string. We basically join array elements with a string. Just like join() function , implode() function also returns a string formed from the elements of an array. Syntax: string implode( separator, array ) Return Type: The return type of implode() function is string. It will return the joined string formed from the elements of array. Example 1: This example adds comma separator to the array elements. <?php // Declare an array and initialize it$Array = array( "GFG1", "GFG2", "GFG3" ); // Display the array elementsprint_r($Array); // Use implode() function to join// comma in the array$List = implode(', ', $Array); // Display the comma separated listprint_r($List); ?> Array ( [0] => GFG1 [1] => GFG2 [2] => GFG3 ) GFG1, GFG2, GFG3 Example 2: <?php // Declare an array and initialize it$Array = array(0, 1, 2, 3, 4, 5, 6, 7); // Display the array elementsprint_r($Array); // Use implode() function to join// comma in the array$List = implode(', ', $Array); // Display the comma separated listprint_r($List); ?> Array ( [0] => 0 [1] => 1 [2] => 2 [3] => 3 [4] => 4 [5] => 5 [6] => 6 [7] => 7 ) 0, 1, 2, 3, 4, 5, 6, 7 PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples. Picked PHP PHP Programs Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? How to Upload Image into Database and Display it using PHP ? How to check whether an array is empty using PHP? PHP | Converting string to Date and DateTime How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? How to Upload Image into Database and Display it using PHP ? How to check whether an array is empty using PHP? How to call PHP function on the click of a Button ?
[ { "code": null, "e": 28, "s": 0, "text": "\n31 Jul, 2021" }, { "code": null, "e": 543, "s": 28, "text": "The comma separated list can be created by using implode() function. The implode() is a builtin function in PHP and is used to join the elements of an array. implode() is an alias for PHP | join() function and works exactly same as that of join() function.If we have an array of elements, we can use the implode() function to join them all to form one string. We basically join array elements with a string. Just like join() function , implode() function also returns a string formed from the elements of an array." }, { "code": null, "e": 551, "s": 543, "text": "Syntax:" }, { "code": null, "e": 587, "s": 551, "text": "string implode( separator, array )\n" }, { "code": null, "e": 717, "s": 587, "text": "Return Type: The return type of implode() function is string. It will return the joined string formed from the elements of array." }, { "code": null, "e": 785, "s": 717, "text": "Example 1: This example adds comma separator to the array elements." }, { "code": "<?php // Declare an array and initialize it$Array = array( \"GFG1\", \"GFG2\", \"GFG3\" ); // Display the array elementsprint_r($Array); // Use implode() function to join// comma in the array$List = implode(', ', $Array); // Display the comma separated listprint_r($List); ?>", "e": 1060, "s": 785, "text": null }, { "code": null, "e": 1136, "s": 1060, "text": "Array\n(\n [0] => GFG1\n [1] => GFG2\n [2] => GFG3\n)\nGFG1, GFG2, GFG3\n" }, { "code": null, "e": 1147, "s": 1136, "text": "Example 2:" }, { "code": "<?php // Declare an array and initialize it$Array = array(0, 1, 2, 3, 4, 5, 6, 7); // Display the array elementsprint_r($Array); // Use implode() function to join// comma in the array$List = implode(', ', $Array); // Display the comma separated listprint_r($List); ?>", "e": 1420, "s": 1147, "text": null }, { "code": null, "e": 1558, "s": 1420, "text": "Array\n(\n [0] => 0\n [1] => 1\n [2] => 2\n [3] => 3\n [4] => 4\n [5] => 5\n [6] => 6\n [7] => 7\n)\n0, 1, 2, 3, 4, 5, 6, 7\n" }, { "code": null, "e": 1727, "s": 1558, "text": "PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples." }, { "code": null, "e": 1734, "s": 1727, "text": "Picked" }, { "code": null, "e": 1738, "s": 1734, "text": "PHP" }, { "code": null, "e": 1751, "s": 1738, "text": "PHP Programs" }, { "code": null, "e": 1768, "s": 1751, "text": "Web Technologies" }, { "code": null, "e": 1772, "s": 1768, "text": "PHP" }, { "code": null, "e": 1870, "s": 1772, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1920, "s": 1870, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 1960, "s": 1920, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 2021, "s": 1960, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 2071, "s": 2021, "text": "How to check whether an array is empty using PHP?" }, { "code": null, "e": 2116, "s": 2071, "text": "PHP | Converting string to Date and DateTime" }, { "code": null, "e": 2166, "s": 2116, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 2206, "s": 2166, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 2267, "s": 2206, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 2317, "s": 2267, "text": "How to check whether an array is empty using PHP?" } ]
Mongoose | updateMany() Function
20 May, 2020 The updateMany() function is same as update(), except MongoDB will update all documents that match the filter. It is used when the user wants to update all documents according to the condition. Installation of mongoose module: You can visit the link to Install mongoose module. You can install this package by using this command.npm install mongooseAfter installing mongoose module, you can check your mongoose version in command prompt using the command.npm version mongooseAfter that, you can just create a folder and add a file, for example index.js. To run this file you need to run the following command.node index.js You can visit the link to Install mongoose module. You can install this package by using this command.npm install mongoose npm install mongoose After installing mongoose module, you can check your mongoose version in command prompt using the command.npm version mongoose npm version mongoose After that, you can just create a folder and add a file, for example index.js. To run this file you need to run the following command.node index.js node index.js Filename: index.js const mongoose = require('mongoose'); // Database connectionmongoose.connect('mongodb://127.0.0.1:27017/geeksforgeeks', { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true, useFindAndModify: false}); // User modelconst User = mongoose.model('User', { name: { type: String }, age: { type: Number }}); // Find all documents matching the// condition(age>=5) and update all// This function has 4 parameters i.e.// filter, update, options, callbackUser.updateMany({age:{$gte:5}}, {name:"ABCD"}, function (err, docs) { if (err){ console.log(err) } else{ console.log("Updated Docs : ", docs); }}); Steps to run the program: The project structure will look like this:Make sure you have installed mongoose module using following command:npm install mongooseBelow is the sample data in the database before the function is executed, You can use any GUI tool or terminal to see the database, like we have used Robo3T GUI tool as shown below:Run index.js file using below command:node index.jsAfter the function is executed, You can see the database as shown below: The project structure will look like this: Make sure you have installed mongoose module using following command:npm install mongoose npm install mongoose Below is the sample data in the database before the function is executed, You can use any GUI tool or terminal to see the database, like we have used Robo3T GUI tool as shown below: Run index.js file using below command:node index.js node index.js After the function is executed, You can see the database as shown below: So this is how you can use the mongoose updateMany() function which is the same as update(), except MongoDB will update all documents that match the filter. Used when the user wants to update all documents according to the condition. Mongoose MongoDB Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Spring Boot JpaRepository with Example Mongoose Populate() Method MongoDB - db.collection.Find() Method Aggregation in MongoDB Upsert in MongoDB How to update Node.js and NPM to next version ? Installation of Node.js on Linux Node.js fs.readFileSync() Method Node.js fs.writeFile() Method How to install the previous version of node.js and npm ?
[ { "code": null, "e": 28, "s": 0, "text": "\n20 May, 2020" }, { "code": null, "e": 222, "s": 28, "text": "The updateMany() function is same as update(), except MongoDB will update all documents that match the filter. It is used when the user wants to update all documents according to the condition." }, { "code": null, "e": 255, "s": 222, "text": "Installation of mongoose module:" }, { "code": null, "e": 651, "s": 255, "text": "You can visit the link to Install mongoose module. You can install this package by using this command.npm install mongooseAfter installing mongoose module, you can check your mongoose version in command prompt using the command.npm version mongooseAfter that, you can just create a folder and add a file, for example index.js. To run this file you need to run the following command.node index.js" }, { "code": null, "e": 774, "s": 651, "text": "You can visit the link to Install mongoose module. You can install this package by using this command.npm install mongoose" }, { "code": null, "e": 795, "s": 774, "text": "npm install mongoose" }, { "code": null, "e": 922, "s": 795, "text": "After installing mongoose module, you can check your mongoose version in command prompt using the command.npm version mongoose" }, { "code": null, "e": 943, "s": 922, "text": "npm version mongoose" }, { "code": null, "e": 1091, "s": 943, "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": 1105, "s": 1091, "text": "node index.js" }, { "code": null, "e": 1124, "s": 1105, "text": "Filename: index.js" }, { "code": "const mongoose = require('mongoose'); // Database connectionmongoose.connect('mongodb://127.0.0.1:27017/geeksforgeeks', { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true, useFindAndModify: false}); // User modelconst User = mongoose.model('User', { name: { type: String }, age: { type: Number }}); // Find all documents matching the// condition(age>=5) and update all// This function has 4 parameters i.e.// filter, update, options, callbackUser.updateMany({age:{$gte:5}}, {name:\"ABCD\"}, function (err, docs) { if (err){ console.log(err) } else{ console.log(\"Updated Docs : \", docs); }});", "e": 1786, "s": 1124, "text": null }, { "code": null, "e": 1812, "s": 1786, "text": "Steps to run the program:" }, { "code": null, "e": 2248, "s": 1812, "text": "The project structure will look like this:Make sure you have installed mongoose module using following command:npm install mongooseBelow is the sample data in the database before the function is executed, You can use any GUI tool or terminal to see the database, like we have used Robo3T GUI tool as shown below:Run index.js file using below command:node index.jsAfter the function is executed, You can see the database as shown below:" }, { "code": null, "e": 2291, "s": 2248, "text": "The project structure will look like this:" }, { "code": null, "e": 2381, "s": 2291, "text": "Make sure you have installed mongoose module using following command:npm install mongoose" }, { "code": null, "e": 2402, "s": 2381, "text": "npm install mongoose" }, { "code": null, "e": 2584, "s": 2402, "text": "Below is the sample data in the database before the function is executed, You can use any GUI tool or terminal to see the database, like we have used Robo3T GUI tool as shown below:" }, { "code": null, "e": 2636, "s": 2584, "text": "Run index.js file using below command:node index.js" }, { "code": null, "e": 2650, "s": 2636, "text": "node index.js" }, { "code": null, "e": 2723, "s": 2650, "text": "After the function is executed, You can see the database as shown below:" }, { "code": null, "e": 2957, "s": 2723, "text": "So this is how you can use the mongoose updateMany() function which is the same as update(), except MongoDB will update all documents that match the filter. Used when the user wants to update all documents according to the condition." }, { "code": null, "e": 2966, "s": 2957, "text": "Mongoose" }, { "code": null, "e": 2974, "s": 2966, "text": "MongoDB" }, { "code": null, "e": 2982, "s": 2974, "text": "Node.js" }, { "code": null, "e": 2999, "s": 2982, "text": "Web Technologies" }, { "code": null, "e": 3097, "s": 2999, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3136, "s": 3097, "text": "Spring Boot JpaRepository with Example" }, { "code": null, "e": 3163, "s": 3136, "text": "Mongoose Populate() Method" }, { "code": null, "e": 3201, "s": 3163, "text": "MongoDB - db.collection.Find() Method" }, { "code": null, "e": 3224, "s": 3201, "text": "Aggregation in MongoDB" }, { "code": null, "e": 3242, "s": 3224, "text": "Upsert in MongoDB" }, { "code": null, "e": 3290, "s": 3242, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 3323, "s": 3290, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 3356, "s": 3323, "text": "Node.js fs.readFileSync() Method" }, { "code": null, "e": 3386, "s": 3356, "text": "Node.js fs.writeFile() Method" } ]
Program to reverse a string (Iterative and Recursive)
08 Jul, 2022 Given a string, write a recursive program to reverse it. Method 1 (Using Stack) C++ Java Python3 C# Javascript // C++ program to reverse a string using stack#include <bits/stdc++.h>using namespace std; void recursiveReverse(string &str){ stack<char> st; for (int i=0; i<str.length(); i++) st.push(str[i]); for (int i=0; i<str.length(); i++) { str[i] = st.top(); st.pop(); } } // Driver programint main(){ string str = "geeksforgeeks"; recursiveReverse(str); cout << str; return 0;} // Java program to reverse a string using stackimport java.util.*;class GFG{ public static String recursiveReverse(char []str) { Stack<Character> st = new Stack<>(); for(int i=0; i<str.length; i++) st.push(str[i]); for (int i=0; i<str.length; i++) { str[i] = st.peek(); st.pop(); } return String.valueOf(str);// converting character array to string } // Driver program public static void main(String []args) { String str = "geeksforgeeks"; str = recursiveReverse(str.toCharArray());// passing character array as parameter System.out.println(str); }}// This code is contributed by Adarsh_Verma # Python program to reverse a string using stack def recursiveReverse(str): # using as stack stack = [] for i in range(len(str)): stack.append(str[i]) for i in range(len(str)): str[i] = stack.pop() if __name__ == "__main__": str = "geeksforgeeks" # converting string to list # because strings do not support # item assignment str = list(str) recursiveReverse(str) # converting list to string str = ''.join(str) print(str) # This code is contributed by# sanjeev2552 // C# program to reverse a string using stackusing System;using System.Collections.Generic; class GFG{ public static String recursiveReverse(char []str) { Stack<char> st = new Stack<char>(); for(int i = 0; i < str.Length; i++) st.Push(str[i]); for (int i = 0; i < str.Length; i++) { str[i] = st.Peek(); st.Pop(); } // converting character array to string return String.Join("",str); } // Driver program public static void Main() { String str = "geeksforgeeks"; // passing character array as parameter str = recursiveReverse(str.ToCharArray()); Console.WriteLine(str); }} // This code is contributed by Rajput-Ji <script> // JavaScript program to reverse a string function recursiveReverse(str) { var revString = ""; for (var i = str.length - 1; i >= 0; i--) { revString += str[i]; } return revString; } // Driver program var str = "geeksforgeeks"; document.write(recursiveReverse(str)); // This code is contributed by rdtank. </script> Chapters descriptions off, selected captions settings, opens captions settings dialog captions off, selected English This is a modal window. Beginning of dialog window. Escape will cancel and close the window. End of dialog window. skeegrofskeeg Time complexity : O(n) Auxiliary Space : O(n) Method 2 (Iterative) C++ Java Python C# PHP Javascript // A Simple Iterative C++ program to reverse// a string#include <bits/stdc++.h>using namespace std; // Function to reverse a stringvoid reverseStr(string& str){ int n = str.length(); // Swap character starting from two // corners for (int i = 0; i < n / 2; i++) swap(str[i], str[n - i - 1]);} // Driver programint main(){ string str = "geeksforgeeks"; reverseStr(str); cout << str; return 0;} // A Simple Java program// to reverse a stringimport java.util.Scanner; public class reverseStr{// Function to reverse// a stringvoid stringReverse(){ String str = "geeksforgeeks"; int length = str.length(); StringBuffer revString = new StringBuffer(); for (int i = length - 1; i >= 0; i--) { revString.append(str.charAt(i)); } System.out.println(revString);} // Driver Codepublic static void main(String []args){ reverseStr s= new reverseStr(); s.stringReverse();}} // This code is contributed// by prabhat kumar singh # A Simple python program# to reverse a string # Function to# reverse a stringdef reverseStr(str): n = len(str) # initialising a empty # string 'str1' str1 = '' i = n - 1 while i >= 0: # copy str # to str1 str1 += str[i] i -= 1 print(str1) # Driver Codedef main(): str = "geeksforgeeks"; reverseStr(str); if __name__=="__main__": main() # This code is contributed# by prabhat kumar singh // A Simple Iterative C# program to reverse// a stringusing System; class GFG{ // Function to reverse a stringstatic String reverseStr(String str){ int n = str.Length; // Swap character starting from two // corners for (int i = 0; i < n / 2; i++) str = swap(str,i,n - i - 1); return str;}static String swap(String str, int i, int j){ char []ch = str.ToCharArray(); char temp = ch[i]; ch[i] = ch[j]; ch[j] = temp; return String.Join("",ch);} // Driver codepublic static void Main(String[] args){ string str = "geeksforgeeks"; str= reverseStr(str); Console.WriteLine(str);}} // This code is contributed by Princi Singh <?php// A Simple Iterative PHP// program to reverse// a string // Function to reverse a stringfunction reverseStr(&$str){ $n = strlen($str); // Swap character starting // from two corners for ($i = 0; $i < $n / 2; $i++) //swap the string list($str[$i], $str[$n - $i - 1]) = array($str[$n - $i - 1], $str[$i]);} // Driver Code$str = "geeksforgeeks"; reverseStr($str);echo $str; // This code is contributed by ajit?> <script> // A Simple Iterative Javascript program to reverse a string // Function to reverse a string function reverseStr(str) { let n = str.length; // Swap character starting from two // corners for (let i = 0; i < parseInt(n / 2, 10); i++) str = swap(str,i,n - i - 1); return str; } function swap(str, i, j) { let ch = str.split(''); let temp = ch[i]; ch[i] = ch[j]; ch[j] = temp; return ch.join(""); } let str = "geeksforgeeks"; str= reverseStr(str); document.write(str); </script> skeegrofskeeg Time complexity : O(n) Auxiliary Space : O(1) Method 3 (Iterative using two pointers) C++ Java Python3 C# PHP Javascript // A Simple Iterative C++ program to reverse// a string#include <bits/stdc++.h>using namespace std; // Function to reverse a stringvoid reverseStr(string& str){ int n = str.length(); // Swap character starting from two // corners for (int i=0, j=n-1; i<j; i++,j--) swap(str[i], str[j]); } // Driver programint main(){ string str = "geeksforgeeks"; reverseStr(str); cout << str; return 0;} //A Simple Iterative Java program to reverse//a stringclass GFG { //Function to reverse a string static void reverseStr(String str) { int n = str.length(); char []ch = str.toCharArray(); char temp; // Swap character starting from two // corners for (int i=0, j=n-1; i<j; i++,j--) { temp = ch[i]; ch[i] = ch[j]; ch[j] = temp; } System.out.println(ch); } //Driver program public static void main(String[] args) { String str = "geeksforgeeks"; reverseStr(str); }}// This code is contributed by Ita_c. # A Simple Iterative Python program to# reverse a string # Function to reverse a stringdef reverseStr(str): n = len(str) i, j = 0, n-1 # Swap character starting from # two corners while i < j: str[i], str[j] = str[j], str[i] i += 1 j -= 1 # Driver codeif __name__ == "__main__": str = "geeksforgeeks" # converting string to list # because strings do not support # item assignment str = list(str) reverseStr(str) # converting list to string str = ''.join(str) print(str) # This code is contributed by# sanjeev2552 // A Simple Iterative C# program // to reverse a stringusing System; class GFG{ //Function to reverse a string static void reverseStr(String str) { int n = str.Length; char []ch = str.ToCharArray(); char temp; // Swap character starting from two // corners for (int i=0, j=n-1; i<j; i++,j--) { temp = ch[i]; ch[i] = ch[j]; ch[j] = temp; } Console.WriteLine(ch); } //Driver program public static void Main(String[] args) { String str = "geeksforgeeks"; reverseStr(str); }} // This code is contributed by PrinciRaj1992 <?php// A Simple Iterative PHP// program to reverse a string // Function to reverse a stringfunction reverseStr (&$str){ $n = strlen($str); // Swap character starting // from two corners for ($i = 0, $j = $n - 1; $i < $j; $i++, $j--) //swap function list($str[$i], $str[$j]) = array($str[$j], $str[$i]);} // Driver Code$str = "geeksforgeeks";reverseStr($str);echo $str; // This code is contributed by ajit.?> <script>//A Simple Iterative Javascript program to reverse//a string //Function to reverse a stringfunction reverseStr(str){ let n = str.length; let ch = str.split(""); let temp; // Swap character starting from two // corners for (let i=0, j=n-1; i<j; i++,j--) { temp = ch[i]; ch[i] = ch[j]; ch[j] = temp; } document.write(ch.join("")+"<br>");} //Driver programlet str = "geeksforgeeks";reverseStr(str); // This code is contributed by rag2127</script> skeegrofskeeg Time complexity : O(n) Auxiliary Space : O(1) Method 4 (Recursive) C++ Java Python3 C# C++ Java Python C# PHP // Recursive C++ program to reverse a string#include <bits/stdc++.h>using namespace std; void recursiveReverse(string &str, int i = 0){ int n = str.length(); if (i == n / 2) return; swap(str[i], str[n - i - 1]); recursiveReverse(str, i + 1);} // Driver programint main(){ string str = "geeksforgeeks"; recursiveReverse(str); cout << str; return 0;} // Recursive Java program to reverse a stringclass GFG{ static void recursiveReverse(char[] str, int i){ int n = str.length; if (i == n / 2) return; swap(str,i,n - i - 1); recursiveReverse(str, i + 1);}static void swap(char []arr, int i, int j){ char temp= arr[i]; arr[i]=arr[j]; arr[j]=temp;} // Driver programpublic static void main(String[] args){ char[] str = "geeksforgeeks".toCharArray(); recursiveReverse(str,0); System.out.println(String.valueOf(str));}} // This code is contributed by 29AjayKumar # Recursive Python program to reverse a string def recursiveReverse(str, i = 0): n = len(str) if i == n // 2: return str[i], str[n-i-1] = str[n-i-1], str[i] recursiveReverse(str, i+1) if __name__ == "__main__": str = "geeksforgeeks" # converting string to list # because strings do not support # item assignment str = list(str) recursiveReverse(str) # converting list to string str = ''.join(str) print(str) # This code is contributed by# sanjeev2552 // Recursive C# program to reverse a stringusing System; public class GFG{ static void recursiveReverse(char[] str, int i){ int n = str.Length; if (i == n / 2) return; swap(str,i,n - i - 1); recursiveReverse(str, i + 1);}static char[] swap(char []arr, int i, int j){ char temp= arr[i]; arr[i]=arr[j]; arr[j]=temp; return arr;} // Driver programpublic static void Main(String[] args){ char[] str = "geeksforgeeks".ToCharArray(); recursiveReverse(str,0); Console.WriteLine(String.Join("",str));}}// This code is contributed by Princi Singh // A quickly written program for reversing a string// using reverse()#include<bits/stdc++.h>using namespace std;int main(){ string str = "geeksforgeeks"; // Reverse str[begin..end] reverse(str.begin(),str.end()); cout << str; return 0;} // A Simple Java program// to reverse a string class GFG{ public static void main(String[] args) { String str = "geeksforgeeks"; // Reverse str[begin..end] str = reverse(str); System.out.println(str); } static String reverse(String input) { char[] temparray = input.toCharArray(); int left, right = 0; right = temparray.length - 1; for (left = 0; left < right; left++, right--) { // Swap values of left and right char temp = temparray[left]; temparray[left] = temparray[right]; temparray[right] = temp; } return String.valueOf(temparray); }} // This code is contributed by 29AjayKumar # A Simple python program# to reverse a string # Function to# reverse a stringdef reverseStr(str): # print the string # from last print(str[::-1]) # Driver Codedef main(): str = "geeksforgeeks"; reverseStr(str); if __name__=="__main__": main() # This code is contributed# by prabhat kumar singh // A Simple C# program to reverse a stringusing System; class GFG{ public static void Main(String[] args) { String str = "geeksforgeeks"; // Reverse str[begin..end] str = reverse(str); Console.WriteLine(str); } static String reverse(String input) { char[] temparray = input.ToCharArray(); int left, right = 0; right = temparray.Length - 1; for (left = 0; left < right; left++, right--) { // Swap values of left and right char temp = temparray[left]; temparray[left] = temparray[right]; temparray[right] = temp; } return String.Join("",temparray); }} /* This code is contributed by PrinciRaj1992 */ <?php// A Simple PHP program// to reverse a string // Function to reverse a stringfunction reverseStr($str){ // print the string // from last echo strrev($str);} // Driver Code$str = "geeksforgeeks"; reverseStr($str); // This code is contributed// by Srathore?> skeegrofskeeg Time complexity: O(n) where n is length of string Auxiliary Space: O(n) Method 5: Using the inbuilt method ‘.reverse()’ of StringBuffer class in Java The idea is to initialise an object of the StringBuffer class using the given string which needs to be reversed and then invoke the .reverse() method. After doing so, you can convert the StringBuffer to a string by using the toString() function. Below is the implementation of the above idea: Java //Java program to reverse a string using StringBuffer class import java.io.*;import java.util.*; class GFG { //Driver Code public static void main (String[] args) { String str = "geeksforgeeks";//Input String //Step 1: Initialise an object of StringBuffer class StringBuffer sb = new StringBuffer(str); //Step 2: Invoke the .reverse() method sb.reverse(); //Step 3: Convert the StringBuffer to string by using toString() method System.out.println(sb.toString()); }} //This code is contributed by shruti456rawal skeegrofskeeg Time Complexity: O(n) jit_t prabhat kumar singh Adarsh_Verma ukasp Rajput-Ji 29AjayKumar princiraj1992 sapnasingh4991 sanjeev2552 princi singh rdtank divyesh072019 ferman rag2127 simmytarika5 shruti456rawal kumargaurav97520 cpp-stack cpp-string Recursion Strings Strings Recursion Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n08 Jul, 2022" }, { "code": null, "e": 110, "s": 52, "text": "Given a string, write a recursive program to reverse it. " }, { "code": null, "e": 137, "s": 112, "text": "Method 1 (Using Stack) " }, { "code": null, "e": 141, "s": 137, "text": "C++" }, { "code": null, "e": 146, "s": 141, "text": "Java" }, { "code": null, "e": 154, "s": 146, "text": "Python3" }, { "code": null, "e": 157, "s": 154, "text": "C#" }, { "code": null, "e": 168, "s": 157, "text": "Javascript" }, { "code": "// C++ program to reverse a string using stack#include <bits/stdc++.h>using namespace std; void recursiveReverse(string &str){ stack<char> st; for (int i=0; i<str.length(); i++) st.push(str[i]); for (int i=0; i<str.length(); i++) { str[i] = st.top(); st.pop(); } } // Driver programint main(){ string str = \"geeksforgeeks\"; recursiveReverse(str); cout << str; return 0;}", "e": 583, "s": 168, "text": null }, { "code": "// Java program to reverse a string using stackimport java.util.*;class GFG{ public static String recursiveReverse(char []str) { Stack<Character> st = new Stack<>(); for(int i=0; i<str.length; i++) st.push(str[i]); for (int i=0; i<str.length; i++) { str[i] = st.peek(); st.pop(); } return String.valueOf(str);// converting character array to string } // Driver program public static void main(String []args) { String str = \"geeksforgeeks\"; str = recursiveReverse(str.toCharArray());// passing character array as parameter System.out.println(str); }}// This code is contributed by Adarsh_Verma", "e": 1226, "s": 583, "text": null }, { "code": "# Python program to reverse a string using stack def recursiveReverse(str): # using as stack stack = [] for i in range(len(str)): stack.append(str[i]) for i in range(len(str)): str[i] = stack.pop() if __name__ == \"__main__\": str = \"geeksforgeeks\" # converting string to list # because strings do not support # item assignment str = list(str) recursiveReverse(str) # converting list to string str = ''.join(str) print(str) # This code is contributed by# sanjeev2552", "e": 1761, "s": 1226, "text": null }, { "code": "// C# program to reverse a string using stackusing System;using System.Collections.Generic; class GFG{ public static String recursiveReverse(char []str) { Stack<char> st = new Stack<char>(); for(int i = 0; i < str.Length; i++) st.Push(str[i]); for (int i = 0; i < str.Length; i++) { str[i] = st.Peek(); st.Pop(); } // converting character array to string return String.Join(\"\",str); } // Driver program public static void Main() { String str = \"geeksforgeeks\"; // passing character array as parameter str = recursiveReverse(str.ToCharArray()); Console.WriteLine(str); }} // This code is contributed by Rajput-Ji", "e": 2524, "s": 1761, "text": null }, { "code": "<script> // JavaScript program to reverse a string function recursiveReverse(str) { var revString = \"\"; for (var i = str.length - 1; i >= 0; i--) { revString += str[i]; } return revString; } // Driver program var str = \"geeksforgeeks\"; document.write(recursiveReverse(str)); // This code is contributed by rdtank. </script>", "e": 2946, "s": 2524, "text": null }, { "code": null, "e": 2955, "s": 2946, "text": "Chapters" }, { "code": null, "e": 2982, "s": 2955, "text": "descriptions off, selected" }, { "code": null, "e": 3032, "s": 2982, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 3055, "s": 3032, "text": "captions off, selected" }, { "code": null, "e": 3063, "s": 3055, "text": "English" }, { "code": null, "e": 3087, "s": 3063, "text": "This is a modal window." }, { "code": null, "e": 3156, "s": 3087, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 3178, "s": 3156, "text": "End of dialog window." }, { "code": null, "e": 3192, "s": 3178, "text": "skeegrofskeeg" }, { "code": null, "e": 3240, "s": 3194, "text": "Time complexity : O(n) Auxiliary Space : O(n)" }, { "code": null, "e": 3262, "s": 3240, "text": "Method 2 (Iterative) " }, { "code": null, "e": 3266, "s": 3262, "text": "C++" }, { "code": null, "e": 3271, "s": 3266, "text": "Java" }, { "code": null, "e": 3278, "s": 3271, "text": "Python" }, { "code": null, "e": 3281, "s": 3278, "text": "C#" }, { "code": null, "e": 3285, "s": 3281, "text": "PHP" }, { "code": null, "e": 3296, "s": 3285, "text": "Javascript" }, { "code": "// A Simple Iterative C++ program to reverse// a string#include <bits/stdc++.h>using namespace std; // Function to reverse a stringvoid reverseStr(string& str){ int n = str.length(); // Swap character starting from two // corners for (int i = 0; i < n / 2; i++) swap(str[i], str[n - i - 1]);} // Driver programint main(){ string str = \"geeksforgeeks\"; reverseStr(str); cout << str; return 0;}", "e": 3721, "s": 3296, "text": null }, { "code": "// A Simple Java program// to reverse a stringimport java.util.Scanner; public class reverseStr{// Function to reverse// a stringvoid stringReverse(){ String str = \"geeksforgeeks\"; int length = str.length(); StringBuffer revString = new StringBuffer(); for (int i = length - 1; i >= 0; i--) { revString.append(str.charAt(i)); } System.out.println(revString);} // Driver Codepublic static void main(String []args){ reverseStr s= new reverseStr(); s.stringReverse();}} // This code is contributed// by prabhat kumar singh", "e": 4287, "s": 3721, "text": null }, { "code": "# A Simple python program# to reverse a string # Function to# reverse a stringdef reverseStr(str): n = len(str) # initialising a empty # string 'str1' str1 = '' i = n - 1 while i >= 0: # copy str # to str1 str1 += str[i] i -= 1 print(str1) # Driver Codedef main(): str = \"geeksforgeeks\"; reverseStr(str); if __name__==\"__main__\": main() # This code is contributed# by prabhat kumar singh", "e": 4763, "s": 4287, "text": null }, { "code": "// A Simple Iterative C# program to reverse// a stringusing System; class GFG{ // Function to reverse a stringstatic String reverseStr(String str){ int n = str.Length; // Swap character starting from two // corners for (int i = 0; i < n / 2; i++) str = swap(str,i,n - i - 1); return str;}static String swap(String str, int i, int j){ char []ch = str.ToCharArray(); char temp = ch[i]; ch[i] = ch[j]; ch[j] = temp; return String.Join(\"\",ch);} // Driver codepublic static void Main(String[] args){ string str = \"geeksforgeeks\"; str= reverseStr(str); Console.WriteLine(str);}} // This code is contributed by Princi Singh", "e": 5427, "s": 4763, "text": null }, { "code": "<?php// A Simple Iterative PHP// program to reverse// a string // Function to reverse a stringfunction reverseStr(&$str){ $n = strlen($str); // Swap character starting // from two corners for ($i = 0; $i < $n / 2; $i++) //swap the string list($str[$i], $str[$n - $i - 1]) = array($str[$n - $i - 1], $str[$i]);} // Driver Code$str = \"geeksforgeeks\"; reverseStr($str);echo $str; // This code is contributed by ajit?>", "e": 5920, "s": 5427, "text": null }, { "code": "<script> // A Simple Iterative Javascript program to reverse a string // Function to reverse a string function reverseStr(str) { let n = str.length; // Swap character starting from two // corners for (let i = 0; i < parseInt(n / 2, 10); i++) str = swap(str,i,n - i - 1); return str; } function swap(str, i, j) { let ch = str.split(''); let temp = ch[i]; ch[i] = ch[j]; ch[j] = temp; return ch.join(\"\"); } let str = \"geeksforgeeks\"; str= reverseStr(str); document.write(str); </script>", "e": 6535, "s": 5920, "text": null }, { "code": null, "e": 6549, "s": 6535, "text": "skeegrofskeeg" }, { "code": null, "e": 6597, "s": 6551, "text": "Time complexity : O(n) Auxiliary Space : O(1)" }, { "code": null, "e": 6639, "s": 6597, "text": "Method 3 (Iterative using two pointers) " }, { "code": null, "e": 6643, "s": 6639, "text": "C++" }, { "code": null, "e": 6648, "s": 6643, "text": "Java" }, { "code": null, "e": 6656, "s": 6648, "text": "Python3" }, { "code": null, "e": 6659, "s": 6656, "text": "C#" }, { "code": null, "e": 6663, "s": 6659, "text": "PHP" }, { "code": null, "e": 6674, "s": 6663, "text": "Javascript" }, { "code": "// A Simple Iterative C++ program to reverse// a string#include <bits/stdc++.h>using namespace std; // Function to reverse a stringvoid reverseStr(string& str){ int n = str.length(); // Swap character starting from two // corners for (int i=0, j=n-1; i<j; i++,j--) swap(str[i], str[j]); } // Driver programint main(){ string str = \"geeksforgeeks\"; reverseStr(str); cout << str; return 0;}", "e": 7095, "s": 6674, "text": null }, { "code": "//A Simple Iterative Java program to reverse//a stringclass GFG { //Function to reverse a string static void reverseStr(String str) { int n = str.length(); char []ch = str.toCharArray(); char temp; // Swap character starting from two // corners for (int i=0, j=n-1; i<j; i++,j--) { temp = ch[i]; ch[i] = ch[j]; ch[j] = temp; } System.out.println(ch); } //Driver program public static void main(String[] args) { String str = \"geeksforgeeks\"; reverseStr(str); }}// This code is contributed by Ita_c.", "e": 7716, "s": 7095, "text": null }, { "code": "# A Simple Iterative Python program to# reverse a string # Function to reverse a stringdef reverseStr(str): n = len(str) i, j = 0, n-1 # Swap character starting from # two corners while i < j: str[i], str[j] = str[j], str[i] i += 1 j -= 1 # Driver codeif __name__ == \"__main__\": str = \"geeksforgeeks\" # converting string to list # because strings do not support # item assignment str = list(str) reverseStr(str) # converting list to string str = ''.join(str) print(str) # This code is contributed by# sanjeev2552", "e": 8299, "s": 7716, "text": null }, { "code": "// A Simple Iterative C# program // to reverse a stringusing System; class GFG{ //Function to reverse a string static void reverseStr(String str) { int n = str.Length; char []ch = str.ToCharArray(); char temp; // Swap character starting from two // corners for (int i=0, j=n-1; i<j; i++,j--) { temp = ch[i]; ch[i] = ch[j]; ch[j] = temp; } Console.WriteLine(ch); } //Driver program public static void Main(String[] args) { String str = \"geeksforgeeks\"; reverseStr(str); }} // This code is contributed by PrinciRaj1992", "e": 8953, "s": 8299, "text": null }, { "code": "<?php// A Simple Iterative PHP// program to reverse a string // Function to reverse a stringfunction reverseStr (&$str){ $n = strlen($str); // Swap character starting // from two corners for ($i = 0, $j = $n - 1; $i < $j; $i++, $j--) //swap function list($str[$i], $str[$j]) = array($str[$j], $str[$i]);} // Driver Code$str = \"geeksforgeeks\";reverseStr($str);echo $str; // This code is contributed by ajit.?>", "e": 9439, "s": 8953, "text": null }, { "code": "<script>//A Simple Iterative Javascript program to reverse//a string //Function to reverse a stringfunction reverseStr(str){ let n = str.length; let ch = str.split(\"\"); let temp; // Swap character starting from two // corners for (let i=0, j=n-1; i<j; i++,j--) { temp = ch[i]; ch[i] = ch[j]; ch[j] = temp; } document.write(ch.join(\"\")+\"<br>\");} //Driver programlet str = \"geeksforgeeks\";reverseStr(str); // This code is contributed by rag2127</script>", "e": 9969, "s": 9439, "text": null }, { "code": null, "e": 9983, "s": 9969, "text": "skeegrofskeeg" }, { "code": null, "e": 10031, "s": 9985, "text": "Time complexity : O(n) Auxiliary Space : O(1)" }, { "code": null, "e": 10054, "s": 10031, "text": "Method 4 (Recursive) " }, { "code": null, "e": 10058, "s": 10054, "text": "C++" }, { "code": null, "e": 10063, "s": 10058, "text": "Java" }, { "code": null, "e": 10071, "s": 10063, "text": "Python3" }, { "code": null, "e": 10074, "s": 10071, "text": "C#" }, { "code": null, "e": 10078, "s": 10074, "text": "C++" }, { "code": null, "e": 10083, "s": 10078, "text": "Java" }, { "code": null, "e": 10090, "s": 10083, "text": "Python" }, { "code": null, "e": 10093, "s": 10090, "text": "C#" }, { "code": null, "e": 10097, "s": 10093, "text": "PHP" }, { "code": "// Recursive C++ program to reverse a string#include <bits/stdc++.h>using namespace std; void recursiveReverse(string &str, int i = 0){ int n = str.length(); if (i == n / 2) return; swap(str[i], str[n - i - 1]); recursiveReverse(str, i + 1);} // Driver programint main(){ string str = \"geeksforgeeks\"; recursiveReverse(str); cout << str; return 0;}", "e": 10477, "s": 10097, "text": null }, { "code": "// Recursive Java program to reverse a stringclass GFG{ static void recursiveReverse(char[] str, int i){ int n = str.length; if (i == n / 2) return; swap(str,i,n - i - 1); recursiveReverse(str, i + 1);}static void swap(char []arr, int i, int j){ char temp= arr[i]; arr[i]=arr[j]; arr[j]=temp;} // Driver programpublic static void main(String[] args){ char[] str = \"geeksforgeeks\".toCharArray(); recursiveReverse(str,0); System.out.println(String.valueOf(str));}} // This code is contributed by 29AjayKumar", "e": 11020, "s": 10477, "text": null }, { "code": "# Recursive Python program to reverse a string def recursiveReverse(str, i = 0): n = len(str) if i == n // 2: return str[i], str[n-i-1] = str[n-i-1], str[i] recursiveReverse(str, i+1) if __name__ == \"__main__\": str = \"geeksforgeeks\" # converting string to list # because strings do not support # item assignment str = list(str) recursiveReverse(str) # converting list to string str = ''.join(str) print(str) # This code is contributed by# sanjeev2552", "e": 11526, "s": 11020, "text": null }, { "code": "// Recursive C# program to reverse a stringusing System; public class GFG{ static void recursiveReverse(char[] str, int i){ int n = str.Length; if (i == n / 2) return; swap(str,i,n - i - 1); recursiveReverse(str, i + 1);}static char[] swap(char []arr, int i, int j){ char temp= arr[i]; arr[i]=arr[j]; arr[j]=temp; return arr;} // Driver programpublic static void Main(String[] args){ char[] str = \"geeksforgeeks\".ToCharArray(); recursiveReverse(str,0); Console.WriteLine(String.Join(\"\",str));}}// This code is contributed by Princi Singh", "e": 12106, "s": 11526, "text": null }, { "code": "// A quickly written program for reversing a string// using reverse()#include<bits/stdc++.h>using namespace std;int main(){ string str = \"geeksforgeeks\"; // Reverse str[begin..end] reverse(str.begin(),str.end()); cout << str; return 0;}", "e": 12363, "s": 12106, "text": null }, { "code": "// A Simple Java program// to reverse a string class GFG{ public static void main(String[] args) { String str = \"geeksforgeeks\"; // Reverse str[begin..end] str = reverse(str); System.out.println(str); } static String reverse(String input) { char[] temparray = input.toCharArray(); int left, right = 0; right = temparray.length - 1; for (left = 0; left < right; left++, right--) { // Swap values of left and right char temp = temparray[left]; temparray[left] = temparray[right]; temparray[right] = temp; } return String.valueOf(temparray); }} // This code is contributed by 29AjayKumar", "e": 13100, "s": 12363, "text": null }, { "code": "# A Simple python program# to reverse a string # Function to# reverse a stringdef reverseStr(str): # print the string # from last print(str[::-1]) # Driver Codedef main(): str = \"geeksforgeeks\"; reverseStr(str); if __name__==\"__main__\": main() # This code is contributed# by prabhat kumar singh", "e": 13434, "s": 13100, "text": null }, { "code": "// A Simple C# program to reverse a stringusing System; class GFG{ public static void Main(String[] args) { String str = \"geeksforgeeks\"; // Reverse str[begin..end] str = reverse(str); Console.WriteLine(str); } static String reverse(String input) { char[] temparray = input.ToCharArray(); int left, right = 0; right = temparray.Length - 1; for (left = 0; left < right; left++, right--) { // Swap values of left and right char temp = temparray[left]; temparray[left] = temparray[right]; temparray[right] = temp; } return String.Join(\"\",temparray); }} /* This code is contributed by PrinciRaj1992 */", "e": 14188, "s": 13434, "text": null }, { "code": "<?php// A Simple PHP program// to reverse a string // Function to reverse a stringfunction reverseStr($str){ // print the string // from last echo strrev($str);} // Driver Code$str = \"geeksforgeeks\"; reverseStr($str); // This code is contributed// by Srathore?>", "e": 14460, "s": 14188, "text": null }, { "code": null, "e": 14474, "s": 14460, "text": "skeegrofskeeg" }, { "code": null, "e": 14526, "s": 14476, "text": "Time complexity: O(n) where n is length of string" }, { "code": null, "e": 14548, "s": 14526, "text": "Auxiliary Space: O(n)" }, { "code": null, "e": 14626, "s": 14548, "text": "Method 5: Using the inbuilt method ‘.reverse()’ of StringBuffer class in Java" }, { "code": null, "e": 14872, "s": 14626, "text": "The idea is to initialise an object of the StringBuffer class using the given string which needs to be reversed and then invoke the .reverse() method. After doing so, you can convert the StringBuffer to a string by using the toString() function." }, { "code": null, "e": 14919, "s": 14872, "text": "Below is the implementation of the above idea:" }, { "code": null, "e": 14924, "s": 14919, "text": "Java" }, { "code": "//Java program to reverse a string using StringBuffer class import java.io.*;import java.util.*; class GFG { //Driver Code public static void main (String[] args) { String str = \"geeksforgeeks\";//Input String //Step 1: Initialise an object of StringBuffer class StringBuffer sb = new StringBuffer(str); //Step 2: Invoke the .reverse() method sb.reverse(); //Step 3: Convert the StringBuffer to string by using toString() method System.out.println(sb.toString()); }} //This code is contributed by shruti456rawal", "e": 15534, "s": 14924, "text": null }, { "code": null, "e": 15548, "s": 15534, "text": "skeegrofskeeg" }, { "code": null, "e": 15570, "s": 15548, "text": "Time Complexity: O(n)" }, { "code": null, "e": 15576, "s": 15570, "text": "jit_t" }, { "code": null, "e": 15596, "s": 15576, "text": "prabhat kumar singh" }, { "code": null, "e": 15609, "s": 15596, "text": "Adarsh_Verma" }, { "code": null, "e": 15615, "s": 15609, "text": "ukasp" }, { "code": null, "e": 15625, "s": 15615, "text": "Rajput-Ji" }, { "code": null, "e": 15637, "s": 15625, "text": "29AjayKumar" }, { "code": null, "e": 15651, "s": 15637, "text": "princiraj1992" }, { "code": null, "e": 15666, "s": 15651, "text": "sapnasingh4991" }, { "code": null, "e": 15678, "s": 15666, "text": "sanjeev2552" }, { "code": null, "e": 15691, "s": 15678, "text": "princi singh" }, { "code": null, "e": 15698, "s": 15691, "text": "rdtank" }, { "code": null, "e": 15712, "s": 15698, "text": "divyesh072019" }, { "code": null, "e": 15719, "s": 15712, "text": "ferman" }, { "code": null, "e": 15727, "s": 15719, "text": "rag2127" }, { "code": null, "e": 15740, "s": 15727, "text": "simmytarika5" }, { "code": null, "e": 15755, "s": 15740, "text": "shruti456rawal" }, { "code": null, "e": 15772, "s": 15755, "text": "kumargaurav97520" }, { "code": null, "e": 15782, "s": 15772, "text": "cpp-stack" }, { "code": null, "e": 15793, "s": 15782, "text": "cpp-string" }, { "code": null, "e": 15803, "s": 15793, "text": "Recursion" }, { "code": null, "e": 15811, "s": 15803, "text": "Strings" }, { "code": null, "e": 15819, "s": 15811, "text": "Strings" }, { "code": null, "e": 15829, "s": 15819, "text": "Recursion" } ]
Using the super Keyword to Call a Base Class Constructor in Java
05 May, 2021 We prefer inheritance to reuse the code available in existing classes. In Java, Inheritance is the concept in which one class inherits the properties of another class. In the below example there are two classes Programming and DP while Programming is Parent class and DP is child class. From the main class, we have created an object of DP i.e. child class as it also allows us to access the methods from its parent class, but if we create an object of Parent class(Programming) then we cannot access the methods or objects from its child class. After creating an object of child class we have first called a method from child class and then called a method from the parent class. This doesn’t matter as we can call the objects in any order. Java // Java program to demonstrate inheritance properties class Programming { // Creating method m1 for class Programming public void m1() { System.out.println("Programming"); }}class DP extends Programming { // Creating method m2 for class DP public void m2() { System.out.println("DP"); }}public class GFG { public static void main(String[] args) { // Creating Obj for Class DP and // Calling both m1 from class programming // And calling m2 from class DP respectively. DP obj = new DP(); obj.m2(); obj.m1(); }} Output : DP Programming In the below example, we have created a parent and child class. Here, we have created an object of the child class, as the constructor will call itself on creating an object we need not mention anything. After creating an object of child class the constructor is expected to print the output from its own class, but from the output, we can identify that Parent class got executed and then child class got executed, this is because we have created a constructor for inherited class and every class contains a super() by default, as we are calling an inherited class it contains super() in its first line and calls the Parent class. Java // Java program to illustrate// the concept of Constructor// inheritance. // Base Classclass Programming { // Constructor for class Programming public Programming() { System.out.println("Programming"); }} // Child Class inherit the Base// Classclass DP extends Programming { // Constructor for class DP public DP() { System.out.println("DP"); }} // Main Classpublic class GFG { public static void main(String[] args) { // Creating obj for // class DP DP obj = new DP(); }} Programming DP In the below example we have used the constructor overloading concept, and we have created an object of child class and after calling the constructor of child class the first line in it is super(10, 20) which says that call the matching constructor from the parent class, if we do not mention that line, by default it calls the super() with no parameterized constructor from Parent class. Java // Java program to demonstrate// the concepts of constructor// overloading. // Base Classclass Programming { // Creating Constructor for // class Programming. public Programming() { System.out.println("Programming"); } // Parameterized Constructor public Programming(int i, int j) { System.out.println("Programming + +"); }} // Child Classclass DP extends Programming { public DP() { // Calling by using // Programming(int i,int j) // from class Programming. super(10, 20); System.out.println("DP"); } // Parameterized Constructor // for class DP public DP(int i, int j) { System.out.println("DP + +"); }} // Main Classpublic class GFG { public static void main(String[] args) { // Creating Object for class DP. DP obj = new DP(); }} Output: Programming + + DP Let’s look at the below snippet, In the below code we have created an object of the child class, and we are passing the value of 10 from the object line itself and after going to the specific constructor it first calls super() by default and prints “Programming” from the Parent class. The point to note is here we are calling a parameterized constructor from the object creation line but it will call super() by default as will be available by default. In child class, we can also give super() with parameters to call a specific constructor from Parent class. Java // Base Classclass Programming { // Default Constructor public Programming() { System.out.println("Programming"); } // parameterized Constructor public Programming(int i, int j) { System.out.println("Programming + +"); }}class DP extends Programming { public DP() { System.out.println("DP"); } // parameterized Constructor with // one parameter public DP(int i) { System.out.println("DP +"); } // parameterized Constructor with // two parameter i and j. public DP(int i, int j) { System.out.println("DP + +"); }} // Main Classpublic class GFG { public static void main(String[] args) { // Creating obj for DP // class which inherits the // properties of class programming DP obj = new DP(10); }} Output : Programming DP + simmytarika5 arorakashish0911 Java-Constructors java-inheritance Java-keyword Java 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 Functional Interfaces in Java Java Programming Examples Strings in Java Differences between JDK, JRE and JVM Abstraction in Java
[ { "code": null, "e": 54, "s": 26, "text": "\n05 May, 2021" }, { "code": null, "e": 600, "s": 54, "text": "We prefer inheritance to reuse the code available in existing classes. In Java, Inheritance is the concept in which one class inherits the properties of another class. In the below example there are two classes Programming and DP while Programming is Parent class and DP is child class. From the main class, we have created an object of DP i.e. child class as it also allows us to access the methods from its parent class, but if we create an object of Parent class(Programming) then we cannot access the methods or objects from its child class." }, { "code": null, "e": 796, "s": 600, "text": "After creating an object of child class we have first called a method from child class and then called a method from the parent class. This doesn’t matter as we can call the objects in any order." }, { "code": null, "e": 801, "s": 796, "text": "Java" }, { "code": "// Java program to demonstrate inheritance properties class Programming { // Creating method m1 for class Programming public void m1() { System.out.println(\"Programming\"); }}class DP extends Programming { // Creating method m2 for class DP public void m2() { System.out.println(\"DP\"); }}public class GFG { public static void main(String[] args) { // Creating Obj for Class DP and // Calling both m1 from class programming // And calling m2 from class DP respectively. DP obj = new DP(); obj.m2(); obj.m1(); }}", "e": 1405, "s": 801, "text": null }, { "code": null, "e": 1417, "s": 1408, "text": "Output :" }, { "code": null, "e": 1434, "s": 1419, "text": "DP\nProgramming" }, { "code": null, "e": 1638, "s": 1434, "text": "In the below example, we have created a parent and child class. Here, we have created an object of the child class, as the constructor will call itself on creating an object we need not mention anything." }, { "code": null, "e": 2067, "s": 1640, "text": "After creating an object of child class the constructor is expected to print the output from its own class, but from the output, we can identify that Parent class got executed and then child class got executed, this is because we have created a constructor for inherited class and every class contains a super() by default, as we are calling an inherited class it contains super() in its first line and calls the Parent class." }, { "code": null, "e": 2074, "s": 2069, "text": "Java" }, { "code": "// Java program to illustrate// the concept of Constructor// inheritance. // Base Classclass Programming { // Constructor for class Programming public Programming() { System.out.println(\"Programming\"); }} // Child Class inherit the Base// Classclass DP extends Programming { // Constructor for class DP public DP() { System.out.println(\"DP\"); }} // Main Classpublic class GFG { public static void main(String[] args) { // Creating obj for // class DP DP obj = new DP(); }}", "e": 2611, "s": 2074, "text": null }, { "code": null, "e": 2629, "s": 2614, "text": "Programming\nDP" }, { "code": null, "e": 3018, "s": 2629, "text": "In the below example we have used the constructor overloading concept, and we have created an object of child class and after calling the constructor of child class the first line in it is super(10, 20) which says that call the matching constructor from the parent class, if we do not mention that line, by default it calls the super() with no parameterized constructor from Parent class." }, { "code": null, "e": 3025, "s": 3020, "text": "Java" }, { "code": "// Java program to demonstrate// the concepts of constructor// overloading. // Base Classclass Programming { // Creating Constructor for // class Programming. public Programming() { System.out.println(\"Programming\"); } // Parameterized Constructor public Programming(int i, int j) { System.out.println(\"Programming + +\"); }} // Child Classclass DP extends Programming { public DP() { // Calling by using // Programming(int i,int j) // from class Programming. super(10, 20); System.out.println(\"DP\"); } // Parameterized Constructor // for class DP public DP(int i, int j) { System.out.println(\"DP + +\"); }} // Main Classpublic class GFG { public static void main(String[] args) { // Creating Object for class DP. DP obj = new DP(); }}", "e": 3897, "s": 3025, "text": null }, { "code": null, "e": 3908, "s": 3900, "text": "Output:" }, { "code": null, "e": 3929, "s": 3910, "text": "Programming + +\nDP" }, { "code": null, "e": 3962, "s": 3929, "text": "Let’s look at the below snippet," }, { "code": null, "e": 4217, "s": 3964, "text": "In the below code we have created an object of the child class, and we are passing the value of 10 from the object line itself and after going to the specific constructor it first calls super() by default and prints “Programming” from the Parent class." }, { "code": null, "e": 4385, "s": 4217, "text": "The point to note is here we are calling a parameterized constructor from the object creation line but it will call super() by default as will be available by default." }, { "code": null, "e": 4492, "s": 4385, "text": "In child class, we can also give super() with parameters to call a specific constructor from Parent class." }, { "code": null, "e": 4499, "s": 4494, "text": "Java" }, { "code": "// Base Classclass Programming { // Default Constructor public Programming() { System.out.println(\"Programming\"); } // parameterized Constructor public Programming(int i, int j) { System.out.println(\"Programming + +\"); }}class DP extends Programming { public DP() { System.out.println(\"DP\"); } // parameterized Constructor with // one parameter public DP(int i) { System.out.println(\"DP +\"); } // parameterized Constructor with // two parameter i and j. public DP(int i, int j) { System.out.println(\"DP + +\"); }} // Main Classpublic class GFG { public static void main(String[] args) { // Creating obj for DP // class which inherits the // properties of class programming DP obj = new DP(10); }}", "e": 5317, "s": 4499, "text": null }, { "code": null, "e": 5329, "s": 5320, "text": "Output :" }, { "code": null, "e": 5348, "s": 5331, "text": "Programming\nDP +" }, { "code": null, "e": 5363, "s": 5350, "text": "simmytarika5" }, { "code": null, "e": 5380, "s": 5363, "text": "arorakashish0911" }, { "code": null, "e": 5398, "s": 5380, "text": "Java-Constructors" }, { "code": null, "e": 5415, "s": 5398, "text": "java-inheritance" }, { "code": null, "e": 5428, "s": 5415, "text": "Java-keyword" }, { "code": null, "e": 5433, "s": 5428, "text": "Java" }, { "code": null, "e": 5438, "s": 5433, "text": "Java" }, { "code": null, "e": 5536, "s": 5438, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5551, "s": 5536, "text": "Stream In Java" }, { "code": null, "e": 5572, "s": 5551, "text": "Introduction to Java" }, { "code": null, "e": 5593, "s": 5572, "text": "Constructors in Java" }, { "code": null, "e": 5612, "s": 5593, "text": "Exceptions in Java" }, { "code": null, "e": 5629, "s": 5612, "text": "Generics in Java" }, { "code": null, "e": 5659, "s": 5629, "text": "Functional Interfaces in Java" }, { "code": null, "e": 5685, "s": 5659, "text": "Java Programming Examples" }, { "code": null, "e": 5701, "s": 5685, "text": "Strings in Java" }, { "code": null, "e": 5738, "s": 5701, "text": "Differences between JDK, JRE and JVM" } ]
Protractor - Core APIS(CONTD…)
In this chapter, let us learn some more core APIs of Protractor. Element is one of the global functions exposed by protractor. This function takes a locater and returns the following − ElementFinder, that finds a single element based on the locator. ElementArrayFinder, that finds an array of elements based on the locator. Both the above support chaining methods as discussed below. The Followings are the functions of ElementArrayFinder − element.all(locator).clone As the name suggests, this function will create a shallow copy of the array of the elements i.e. ElementArrayFinder. element.all(locator).all(locator) This function basically returns a new ElementArrayFinder which could be empty or contain the children elements. It can be used for selecting multiple elements as an array as follows Example element.all(locator).all(locator) elementArr.all(by.css(‘.childselector’)); // it will return another ElementFindArray as child element based on child locator. element.all(locator).filter(filterFn) As the name suggests, after applying filter function to each element within ElementArrayFinder, it returns a new ElementArrayFinder with all elements that pass the filter function. It is basically having two arguments, first is ElementFinder and second is index. It can also be used in page objects. Example View <ul class = "items"> <li class = "one">First</li> <li class = "two">Second</li> <li class = "three">Third</li> </ul> Code element.all(by.css('.items li')).filter(function(elem, index) { return elem.getText().then(function(text) { return text === 'Third'; }); }).first().click(); element.all(locator).get(index) With the help of this, we can get an element within the ElementArrayFinder by index. Note that the index starts at 0 and negative indices are wrapped. Example View <ul class = "items"> <li>First</li> <li>Second</li> <li>Third</li> </ul> Code let list = element.all(by.css('.items li')); expect(list.get(0).getText()).toBe('First'); expect(list.get(1).getText()).toBe('Second'); element.all(locator).first() As the name suggests, this will get the first element for ElementArrayFinder. It will not retrieve the underlying element. Example View <ul class = "items"> <li>First</li> <li>Second</li> <li>Third</li> </ul> Code let first = element.all(by.css('.items li')).first(); expect(first.getText()).toBe('First'); element.all(locator).last() As name suggest, this will get the last element for ElementArrayFinder. It will not retrieve the underlying element. Example View <ul class = "items"> <li>First</li> <li>Second</li> <li>Third</li> </ul> Code let first = element.all(by.css('.items li')).last(); expect(last.getText()).toBe('Third'); element.all(locator).all(selector) It is used to find an array of elements within a parent when calls to $$ may be chained. Example View <div class = "parent"> <ul> <li class = "one">First</li> <li class = "two">Second</li> <li class = "three">Third</li> </ul> </div> Code let items = element(by.css('.parent')).$$('li'); element.all(locator).count() As the name suggests, this will count the number of elements represented by ElementArrayFinder. It will not retrieve the underlying element. Example View <ul class = "items"> <li>First</li> <li>Second</li> <li>Third</li> </ul> Code let list = element.all(by.css('.items li')); expect(list.count()).toBe(3); element.all(locator).isPresent() It will match the elements with the finder. It can return true or false. True, if there are any elements present that match the finder and False otherwise. Example expect($('.item').isPresent()).toBeTruthy(); element.all(locator).locator As the name suggests, it will return the most relevant locator. Example $('#ID1').locator(); // returns by.css('#ID1') $('#ID1').$('#ID2').locator(); // returns by.css('#ID2') $$('#ID1').filter(filterFn).get(0).click().locator(); // returns by.css('#ID1') element.all(locator).then(thenFunction) It will retrieve the elements represented by the ElementArrayFinder. Example View <ul class = "items"> <li>First</li> <li>Second</li> <li>Third</li> </ul> Code element.all(by.css('.items li')).then(function(arr) { expect(arr.length).toEqual(3); }); element.all(locator).each(eachFunction) As the name suggests, it will call the input function on each ElementFinder represented by the ElementArrayFinder. Example View <ul class = "items"> <li>First</li> <li>Second</li> <li>Third</li> </ul> Code element.all(by.css('.items li')).each(function(element, index) { // It will print First 0, Second 1 and Third 2. element.getText().then(function (text) { console.log(index, text); }); }); element.all(locator).map(mapFunction) As name suggest, it will apply a map function on each element within the ElementArrayFinder. It is having two arguments. First would be the ElementFinder and second would be the index. Example View <ul class = "items"> <li>First</li> <li>Second</li> <li>Third</li> </ul> Code let items = element.all(by.css('.items li')).map(function(elm, index) { return { index: index, text: elm.getText(), class: elm.getAttribute('class') }; }); expect(items).toEqual([ {index: 0, text: 'First', class: 'one'}, {index: 1, text: 'Second', class: 'two'}, {index: 2, text: 'Third', class: 'three'} ]); element.all(locator).reduce(reduceFn) As the name suggests, it will apply a reduce function against an accumulator and every element found using the locator. This function will reduce every element into a single value. Example View <ul class = "items"> <li>First</li> <li>Second</li> <li>Third</li> </ul> Code let value = element.all(by.css('.items li')).reduce(function(acc, elem) { return elem.getText().then(function(text) { return acc + text + ' '; }); }, ''); expect(value).toEqual('First Second Third '); element.all(locator).evaluate As the name suggests, it will evaluate the input whether it is in the scope of the current underlying elements or not. Example View <span class = "foo">{{letiableInScope}}</span> Code let value = element.all(by.css('.foo')).evaluate('letiableInScope'); element.all(locator).allowAnimations As name suggest, it will determine whether the animation is allowed on the current underlying elements or not. Example element(by.css('body')).allowAnimations(false); Chaining functions of ElementFinder and their descriptions − element(locator).clone As the name suggests, this function will create a shallow copy of the ElementFinder. element(locator).getWebElement() It will return the WebElement represented by this ElementFinder and a WebDriver error will be thrown if the element does not exist. Example View <div class="parent"> some text </div> Code // All the four following expressions are equivalent. $('.parent').getWebElement(); element(by.css('.parent')).getWebElement(); browser.driver.findElement(by.css('.parent')); browser.findElement(by.css('.parent')); element(locator).all(locator) It will find an array of elements within a parent. Example View <div class = "parent"> <ul> <li class = "one">First</li> <li class = "two">Second</li> <li class = "three">Third</li> </ul> </div> Code let items = element(by.css('.parent')).all(by.tagName('li')); element(locator).element(locator) It will find elements within a parent. Example View <div class = "parent"> <div class = "child"> Child text <div>{{person.phone}}</div> </div> </div> Code // Calls Chain 2 element. let child = element(by.css('.parent')). element(by.css('.child')); expect(child.getText()).toBe('Child text\n981-000-568'); // Calls Chain 3 element. let triple = element(by.css('.parent')). element(by.css('.child')). element(by.binding('person.phone')); expect(triple.getText()).toBe('981-000-568'); element(locator).all(selector) It will find an array of elements within a parent when calls to $$ may be chained. Example View <div class = "parent"> <ul> <li class = "one">First</li> <li class = "two">Second</li> <li class = "three">Third</li> </ul> </div> Code let items = element(by.css('.parent')).$$('li')); element(locator).$(locator) It will find elements within a parent when calls to $ may be chained. Example View <div class = "parent"> <div class = "child"> Child text <div>{{person.phone}}</div> </div> </div> Code // Calls Chain 2 element. let child = element(by.css('.parent')). $('.child')); expect(child.getText()).toBe('Child text\n981-000-568'); // Calls Chain 3 element. let triple = element(by.css('.parent')). $('.child')). element(by.binding('person.phone')); expect(triple.getText()).toBe('981-000-568'); element(locator).isPresent() It will determine whether the element is presented on page or not. Example View <span>{{person.name}}</span> Code expect(element(by.binding('person.name')).isPresent()).toBe(true); // will check for the existence of element expect(element(by.binding('notPresent')).isPresent()).toBe(false); // will check for the non-existence of element element(locator).isElementPresent() It is same as element(locator).isPresent(). The only difference is that it will check whether the element identified by sublocator is present rather than the current element finder. element.all(locator).evaluate As the name suggests, it will evaluate the input whether it is on the scope of the current underlying elements or not. Example View <span id = "foo">{{letiableInScope}}</span> Code let value = element(by.id('.foo')).evaluate('letiableInScope'); element(locator).allowAnimations As the name suggests, it will determine whether the animation is allowed on the current underlying elements or not. Example element(by.css('body')).allowAnimations(false); element(locator).equals As the name suggests, it will compare an element for equality. It is basically a collection of element locator strategies that provides ways of finding elements in Angular applications by binding, model etc. Functions and their descriptions The functions of ProtractorLocators API are as follows − by.addLocator(locatorName,fuctionOrScript) It will add a locator to this instance of ProtrcatorBy which further can be used with element(by.locatorName(args)). Example View <button ng-click = "doAddition()">Go!</button> Code // Adding the custom locator. by.addLocator('buttonTextSimple', function(buttonText, opt_parentElement, opt_rootSelector) { var using = opt_parentElement || document, buttons = using.querySelectorAll('button'); return Array.prototype.filter.call(buttons, function(button) { return button.textContent === buttonText; }); }); element(by.buttonTextSimple('Go!')).click();// Using the custom locator. by.binding As the name suggests, it will find an element by text binding. A partial match will be done so that any elements bound to the variables containing the input string will be returned. Example View <span>{{person.name}}</span> <span ng-bind = "person.email"></span> Code var span1 = element(by.binding('person.name')); expect(span1.getText()).toBe('Foo'); var span2 = element(by.binding('person.email')); expect(span2.getText()).toBe('foo@bar.com'); by.exactbinding As the name suggests, it will find an element by exact binding. Example View <spangt;{{ person.name }}</spangt; <span ng-bind = "person-email"gt;</spangt; <spangt;{{person_phone|uppercase}}</span> Code expect(element(by.exactBinding('person.name')).isPresent()).toBe(true); expect(element(by.exactBinding('person-email')).isPresent()).toBe(true); expect(element(by.exactBinding('person')).isPresent()).toBe(false); expect(element(by.exactBinding('person_phone')).isPresent()).toBe(true); expect(element(by.exactBinding('person_phone|uppercase')).isPresent()).toBe(true); expect(element(by.exactBinding('phone')).isPresent()).toBe(false); by.model(modelName) As the name suggests, it will find an element by ng-model expression. Example View <input type = "text" ng-model = "person.name"> Code var input = element(by.model('person.name')); input.sendKeys('123'); expect(input.getAttribute('value')).toBe('Foo123'); by.buttonText As the name suggests, it will find a button by text. Example View <button>Save</button> Code element(by.buttonText('Save')); by.partialButtonText As the name suggests, it will find a button by partial text. Example View <button>Save my file</button> Code element(by.partialButtonText('Save')); by.repeater As the name suggests, it will find an element inside an ng-repeat. Example View <div ng-repeat = "cat in pets"> <span>{{cat.name}}</span> <span>{{cat.age}}</span> <</div> <div class = "book-img" ng-repeat-start="book in library"> <span>{{$index}}</span> </div> <div class = "book-info" ng-repeat-end> <h4>{{book.name}}</h4> <p>{{book.blurb}}</p> </div> Code var secondCat = element(by.repeater('cat in pets').row(1)); // It will return the DIV for the second cat. var firstCatName = element(by.repeater('cat in pets'). row(0).column('cat.name')); // It will return the SPAN for the first cat's name. by.exactRepeater As the name suggests, it will find an element by exact repeater. Example View <li ng-repeat = "person in peopleWithRedHair"></li> <li ng-repeat = "car in cars | orderBy:year"></li> Code expect(element(by.exactRepeater('person in peopleWithRedHair')).isPresent()) .toBe(true); expect(element(by.exactRepeater('person in people')).isPresent()).toBe(false); expect(element(by.exactRepeater('car in cars')).isPresent()).toBe(true); by.cssContainingText As name suggest, it will find the elements, containing exact string, by CSS Example View <ul> <li class = "pet">Dog</li> <li class = "pet">Cat</li> </ul> Code var dog = element(by.cssContainingText('.pet', 'Dog')); // It will return the li for the dog, but not for the cat. by.options(optionsDescriptor) As the name suggests, it will find an element by ng-options expression. Example View <select ng-model = "color" ng-options = "c for c in colors"> <option value = "0" selected = "selected">red</option> <option value = "1">green</option> </select> Code var allOptions = element.all(by.options('c for c in colors')); expect(allOptions.count()).toEqual(2); var firstOption = allOptions.first(); expect(firstOption.getText()).toEqual('red'); by.deepCSS(selector) As name suggest, it will find an element by CSS selector within the shadow DOM. Example View <div> <span id = "outerspan"> <"shadow tree"> <span id = "span1"></span> <"shadow tree"> <span id = "span2"></span> </> </> </div> Code var spans = element.all(by.deepCss('span')); expect(spans.count()).toEqual(3); 35 Lectures 3.5 hours SAYANTAN TARAFDAR 18 Lectures 3 hours LuckyTrainings Print Add Notes Bookmark this page
[ { "code": null, "e": 1956, "s": 1891, "text": "In this chapter, let us learn some more core APIs of Protractor." }, { "code": null, "e": 2076, "s": 1956, "text": "Element is one of the global functions exposed by protractor. This function takes a locater and returns the following −" }, { "code": null, "e": 2141, "s": 2076, "text": "ElementFinder, that finds a single element based on the locator." }, { "code": null, "e": 2215, "s": 2141, "text": "ElementArrayFinder, that finds an array of elements based on the locator." }, { "code": null, "e": 2275, "s": 2215, "text": "Both the above support chaining methods as discussed below." }, { "code": null, "e": 2332, "s": 2275, "text": "The Followings are the functions of ElementArrayFinder −" }, { "code": null, "e": 2359, "s": 2332, "text": "element.all(locator).clone" }, { "code": null, "e": 2476, "s": 2359, "text": "As the name suggests, this function will create a shallow copy of the array of the elements i.e. ElementArrayFinder." }, { "code": null, "e": 2510, "s": 2476, "text": "element.all(locator).all(locator)" }, { "code": null, "e": 2692, "s": 2510, "text": "This function basically returns a new ElementArrayFinder which could be empty or contain the children elements. It can be used for selecting multiple elements as an array as follows" }, { "code": null, "e": 2700, "s": 2692, "text": "Example" }, { "code": null, "e": 2860, "s": 2700, "text": "element.all(locator).all(locator)\nelementArr.all(by.css(‘.childselector’));\n// it will return another ElementFindArray as child element based on child locator." }, { "code": null, "e": 2898, "s": 2860, "text": "element.all(locator).filter(filterFn)" }, { "code": null, "e": 3198, "s": 2898, "text": "As the name suggests, after applying filter function to each element within ElementArrayFinder, it returns a new ElementArrayFinder with all elements that pass the filter function. It is basically having two arguments, first is ElementFinder and second is index. It can also be used in page objects." }, { "code": null, "e": 3206, "s": 3198, "text": "Example" }, { "code": null, "e": 3211, "s": 3206, "text": "View" }, { "code": null, "e": 3337, "s": 3211, "text": "<ul class = \"items\">\n <li class = \"one\">First</li>\n <li class = \"two\">Second</li>\n <li class = \"three\">Third</li>\n</ul>" }, { "code": null, "e": 3342, "s": 3337, "text": "Code" }, { "code": null, "e": 3511, "s": 3342, "text": "element.all(by.css('.items li')).filter(function(elem, index) {\n return elem.getText().then(function(text) {\n return text === 'Third';\n });\n}).first().click();" }, { "code": null, "e": 3543, "s": 3511, "text": "element.all(locator).get(index)" }, { "code": null, "e": 3694, "s": 3543, "text": "With the help of this, we can get an element within the ElementArrayFinder by index. Note that the index starts at 0 and negative indices are wrapped." }, { "code": null, "e": 3702, "s": 3694, "text": "Example" }, { "code": null, "e": 3707, "s": 3702, "text": "View" }, { "code": null, "e": 3789, "s": 3707, "text": "<ul class = \"items\">\n <li>First</li>\n <li>Second</li>\n <li>Third</li>\n</ul>" }, { "code": null, "e": 3794, "s": 3789, "text": "Code" }, { "code": null, "e": 3930, "s": 3794, "text": "let list = element.all(by.css('.items li'));\nexpect(list.get(0).getText()).toBe('First');\nexpect(list.get(1).getText()).toBe('Second');" }, { "code": null, "e": 3959, "s": 3930, "text": "element.all(locator).first()" }, { "code": null, "e": 4082, "s": 3959, "text": "As the name suggests, this will get the first element for ElementArrayFinder. It will not retrieve the underlying element." }, { "code": null, "e": 4090, "s": 4082, "text": "Example" }, { "code": null, "e": 4095, "s": 4090, "text": "View" }, { "code": null, "e": 4178, "s": 4095, "text": "<ul class = \"items\">\n <li>First</li>\n <li>Second</li>\n <li>Third</li>\n</ul>\n" }, { "code": null, "e": 4183, "s": 4178, "text": "Code" }, { "code": null, "e": 4276, "s": 4183, "text": "let first = element.all(by.css('.items li')).first();\nexpect(first.getText()).toBe('First');" }, { "code": null, "e": 4304, "s": 4276, "text": "element.all(locator).last()" }, { "code": null, "e": 4421, "s": 4304, "text": "As name suggest, this will get the last element for ElementArrayFinder. It will not retrieve the underlying element." }, { "code": null, "e": 4429, "s": 4421, "text": "Example" }, { "code": null, "e": 4434, "s": 4429, "text": "View" }, { "code": null, "e": 4516, "s": 4434, "text": "<ul class = \"items\">\n <li>First</li>\n <li>Second</li>\n <li>Third</li>\n</ul>" }, { "code": null, "e": 4521, "s": 4516, "text": "Code" }, { "code": null, "e": 4612, "s": 4521, "text": "let first = element.all(by.css('.items li')).last();\nexpect(last.getText()).toBe('Third');" }, { "code": null, "e": 4647, "s": 4612, "text": "element.all(locator).all(selector)" }, { "code": null, "e": 4736, "s": 4647, "text": "It is used to find an array of elements within a parent when calls to $$ may be chained." }, { "code": null, "e": 4744, "s": 4736, "text": "Example" }, { "code": null, "e": 4749, "s": 4744, "text": "View" }, { "code": null, "e": 4904, "s": 4749, "text": "<div class = \"parent\">\n <ul>\n <li class = \"one\">First</li>\n <li class = \"two\">Second</li>\n <li class = \"three\">Third</li>\n </ul>\n</div>" }, { "code": null, "e": 4909, "s": 4904, "text": "Code" }, { "code": null, "e": 4958, "s": 4909, "text": "let items = element(by.css('.parent')).$$('li');" }, { "code": null, "e": 4987, "s": 4958, "text": "element.all(locator).count()" }, { "code": null, "e": 5128, "s": 4987, "text": "As the name suggests, this will count the number of elements represented by ElementArrayFinder. It will not retrieve the underlying element." }, { "code": null, "e": 5136, "s": 5128, "text": "Example" }, { "code": null, "e": 5141, "s": 5136, "text": "View" }, { "code": null, "e": 5223, "s": 5141, "text": "<ul class = \"items\">\n <li>First</li>\n <li>Second</li>\n <li>Third</li>\n</ul>" }, { "code": null, "e": 5228, "s": 5223, "text": "Code" }, { "code": null, "e": 5303, "s": 5228, "text": "let list = element.all(by.css('.items li'));\nexpect(list.count()).toBe(3);" }, { "code": null, "e": 5336, "s": 5303, "text": "element.all(locator).isPresent()" }, { "code": null, "e": 5492, "s": 5336, "text": "It will match the elements with the finder. It can return true or false. True, if there are any elements present that match the finder and False otherwise." }, { "code": null, "e": 5500, "s": 5492, "text": "Example" }, { "code": null, "e": 5545, "s": 5500, "text": "expect($('.item').isPresent()).toBeTruthy();" }, { "code": null, "e": 5574, "s": 5545, "text": "element.all(locator).locator" }, { "code": null, "e": 5638, "s": 5574, "text": "As the name suggests, it will return the most relevant locator." }, { "code": null, "e": 5646, "s": 5638, "text": "Example" }, { "code": null, "e": 5830, "s": 5646, "text": "$('#ID1').locator();\n// returns by.css('#ID1')\n$('#ID1').$('#ID2').locator();\n// returns by.css('#ID2')\n$$('#ID1').filter(filterFn).get(0).click().locator();\n// returns by.css('#ID1')" }, { "code": null, "e": 5870, "s": 5830, "text": "element.all(locator).then(thenFunction)" }, { "code": null, "e": 5939, "s": 5870, "text": "It will retrieve the elements represented by the ElementArrayFinder." }, { "code": null, "e": 5947, "s": 5939, "text": "Example" }, { "code": null, "e": 5952, "s": 5947, "text": "View" }, { "code": null, "e": 6034, "s": 5952, "text": "<ul class = \"items\">\n <li>First</li>\n <li>Second</li>\n <li>Third</li>\n</ul>" }, { "code": null, "e": 6039, "s": 6034, "text": "Code" }, { "code": null, "e": 6131, "s": 6039, "text": "element.all(by.css('.items li')).then(function(arr) {\n expect(arr.length).toEqual(3);\n});" }, { "code": null, "e": 6171, "s": 6131, "text": "element.all(locator).each(eachFunction)" }, { "code": null, "e": 6286, "s": 6171, "text": "As the name suggests, it will call the input function on each ElementFinder represented by the ElementArrayFinder." }, { "code": null, "e": 6294, "s": 6286, "text": "Example" }, { "code": null, "e": 6299, "s": 6294, "text": "View" }, { "code": null, "e": 6381, "s": 6299, "text": "<ul class = \"items\">\n <li>First</li>\n <li>Second</li>\n <li>Third</li>\n</ul>" }, { "code": null, "e": 6386, "s": 6381, "text": "Code" }, { "code": null, "e": 6589, "s": 6386, "text": "element.all(by.css('.items li')).each(function(element, index) {\n // It will print First 0, Second 1 and Third 2.\n element.getText().then(function (text) {\n console.log(index, text);\n });\n});" }, { "code": null, "e": 6627, "s": 6589, "text": "element.all(locator).map(mapFunction)" }, { "code": null, "e": 6812, "s": 6627, "text": "As name suggest, it will apply a map function on each element within the ElementArrayFinder. It is having two arguments. First would be the ElementFinder and second would be the index." }, { "code": null, "e": 6820, "s": 6812, "text": "Example" }, { "code": null, "e": 6825, "s": 6820, "text": "View" }, { "code": null, "e": 6907, "s": 6825, "text": "<ul class = \"items\">\n <li>First</li>\n <li>Second</li>\n <li>Third</li>\n</ul>" }, { "code": null, "e": 6912, "s": 6907, "text": "Code" }, { "code": null, "e": 7254, "s": 6912, "text": "let items = element.all(by.css('.items li')).map(function(elm, index) {\n return {\n index: index,\n text: elm.getText(),\n class: elm.getAttribute('class')\n };\n});\nexpect(items).toEqual([\n {index: 0, text: 'First', class: 'one'},\n {index: 1, text: 'Second', class: 'two'},\n {index: 2, text: 'Third', class: 'three'}\n]);" }, { "code": null, "e": 7292, "s": 7254, "text": "element.all(locator).reduce(reduceFn)" }, { "code": null, "e": 7473, "s": 7292, "text": "As the name suggests, it will apply a reduce function against an accumulator and every element found using the locator. This function will reduce every element into a single value." }, { "code": null, "e": 7481, "s": 7473, "text": "Example" }, { "code": null, "e": 7486, "s": 7481, "text": "View" }, { "code": null, "e": 7569, "s": 7486, "text": "<ul class = \"items\">\n <li>First</li>\n <li>Second</li>\n <li>Third</li>\n</ul>\n" }, { "code": null, "e": 7574, "s": 7569, "text": "Code" }, { "code": null, "e": 7788, "s": 7574, "text": "let value = element.all(by.css('.items li')).reduce(function(acc, elem) {\n return elem.getText().then(function(text) {\n return acc + text + ' ';\n });\n}, '');\n\nexpect(value).toEqual('First Second Third ');" }, { "code": null, "e": 7818, "s": 7788, "text": "element.all(locator).evaluate" }, { "code": null, "e": 7937, "s": 7818, "text": "As the name suggests, it will evaluate the input whether it is in the scope of the current underlying elements or not." }, { "code": null, "e": 7945, "s": 7937, "text": "Example" }, { "code": null, "e": 7950, "s": 7945, "text": "View" }, { "code": null, "e": 7997, "s": 7950, "text": "<span class = \"foo\">{{letiableInScope}}</span>" }, { "code": null, "e": 8002, "s": 7997, "text": "Code" }, { "code": null, "e": 8072, "s": 8002, "text": "let value = \nelement.all(by.css('.foo')).evaluate('letiableInScope');" }, { "code": null, "e": 8109, "s": 8072, "text": "element.all(locator).allowAnimations" }, { "code": null, "e": 8220, "s": 8109, "text": "As name suggest, it will determine whether the animation is allowed on the current underlying elements or not." }, { "code": null, "e": 8228, "s": 8220, "text": "Example" }, { "code": null, "e": 8276, "s": 8228, "text": "element(by.css('body')).allowAnimations(false);" }, { "code": null, "e": 8337, "s": 8276, "text": "Chaining functions of ElementFinder and their descriptions −" }, { "code": null, "e": 8360, "s": 8337, "text": "element(locator).clone" }, { "code": null, "e": 8445, "s": 8360, "text": "As the name suggests, this function will create a shallow copy of the ElementFinder." }, { "code": null, "e": 8478, "s": 8445, "text": "element(locator).getWebElement()" }, { "code": null, "e": 8610, "s": 8478, "text": "It will return the WebElement represented by this ElementFinder and a WebDriver error will be thrown if the element does not exist." }, { "code": null, "e": 8618, "s": 8610, "text": "Example" }, { "code": null, "e": 8623, "s": 8618, "text": "View" }, { "code": null, "e": 8664, "s": 8623, "text": "<div class=\"parent\">\n some text\n</div>" }, { "code": null, "e": 8669, "s": 8664, "text": "Code" }, { "code": null, "e": 8884, "s": 8669, "text": "// All the four following expressions are equivalent.\n$('.parent').getWebElement();\nelement(by.css('.parent')).getWebElement();\nbrowser.driver.findElement(by.css('.parent'));\nbrowser.findElement(by.css('.parent'));" }, { "code": null, "e": 8914, "s": 8884, "text": "element(locator).all(locator)" }, { "code": null, "e": 8965, "s": 8914, "text": "It will find an array of elements within a parent." }, { "code": null, "e": 8973, "s": 8965, "text": "Example" }, { "code": null, "e": 8978, "s": 8973, "text": "View" }, { "code": null, "e": 9133, "s": 8978, "text": "<div class = \"parent\">\n <ul>\n <li class = \"one\">First</li>\n <li class = \"two\">Second</li>\n <li class = \"three\">Third</li>\n </ul>\n</div>" }, { "code": null, "e": 9138, "s": 9133, "text": "Code" }, { "code": null, "e": 9200, "s": 9138, "text": "let items = element(by.css('.parent')).all(by.tagName('li'));" }, { "code": null, "e": 9234, "s": 9200, "text": "element(locator).element(locator)" }, { "code": null, "e": 9273, "s": 9234, "text": "It will find elements within a parent." }, { "code": null, "e": 9281, "s": 9273, "text": "Example" }, { "code": null, "e": 9286, "s": 9281, "text": "View" }, { "code": null, "e": 9403, "s": 9286, "text": "<div class = \"parent\">\n <div class = \"child\">\n Child text\n <div>{{person.phone}}</div>\n </div>\n</div>\n" }, { "code": null, "e": 9408, "s": 9403, "text": "Code" }, { "code": null, "e": 9745, "s": 9408, "text": "// Calls Chain 2 element.\nlet child = element(by.css('.parent')).\n element(by.css('.child'));\nexpect(child.getText()).toBe('Child text\\n981-000-568');\n\n// Calls Chain 3 element.\nlet triple = element(by.css('.parent')).\n element(by.css('.child')).\n element(by.binding('person.phone'));\nexpect(triple.getText()).toBe('981-000-568');" }, { "code": null, "e": 9776, "s": 9745, "text": "element(locator).all(selector)" }, { "code": null, "e": 9859, "s": 9776, "text": "It will find an array of elements within a parent when calls to $$ may be chained." }, { "code": null, "e": 9867, "s": 9859, "text": "Example" }, { "code": null, "e": 9872, "s": 9867, "text": "View" }, { "code": null, "e": 10027, "s": 9872, "text": "<div class = \"parent\">\n <ul>\n <li class = \"one\">First</li>\n <li class = \"two\">Second</li>\n <li class = \"three\">Third</li>\n </ul>\n</div>" }, { "code": null, "e": 10032, "s": 10027, "text": "Code" }, { "code": null, "e": 10082, "s": 10032, "text": "let items = element(by.css('.parent')).$$('li'));" }, { "code": null, "e": 10110, "s": 10082, "text": "element(locator).$(locator)" }, { "code": null, "e": 10180, "s": 10110, "text": "It will find elements within a parent when calls to $ may be chained." }, { "code": null, "e": 10188, "s": 10180, "text": "Example" }, { "code": null, "e": 10193, "s": 10188, "text": "View" }, { "code": null, "e": 10308, "s": 10193, "text": "<div class = \"parent\">\n <div class = \"child\">\n Child text\n <div>{{person.phone}}</div>\n </div>\n</div>" }, { "code": null, "e": 10313, "s": 10308, "text": "Code" }, { "code": null, "e": 10624, "s": 10313, "text": "// Calls Chain 2 element.\nlet child = element(by.css('.parent')).\n $('.child'));\nexpect(child.getText()).toBe('Child text\\n981-000-568');\n\n// Calls Chain 3 element.\nlet triple = element(by.css('.parent')).\n $('.child')).\n element(by.binding('person.phone'));\nexpect(triple.getText()).toBe('981-000-568');" }, { "code": null, "e": 10653, "s": 10624, "text": "element(locator).isPresent()" }, { "code": null, "e": 10720, "s": 10653, "text": "It will determine whether the element is presented on page or not." }, { "code": null, "e": 10728, "s": 10720, "text": "Example" }, { "code": null, "e": 10733, "s": 10728, "text": "View" }, { "code": null, "e": 10762, "s": 10733, "text": "<span>{{person.name}}</span>" }, { "code": null, "e": 10767, "s": 10762, "text": "Code" }, { "code": null, "e": 10993, "s": 10767, "text": "expect(element(by.binding('person.name')).isPresent()).toBe(true);\n// will check for the existence of element\n\nexpect(element(by.binding('notPresent')).isPresent()).toBe(false); \n// will check for the non-existence of element" }, { "code": null, "e": 11029, "s": 10993, "text": "element(locator).isElementPresent()" }, { "code": null, "e": 11211, "s": 11029, "text": "It is same as element(locator).isPresent(). The only difference is that it will check whether the element identified by sublocator is present rather than the current element finder." }, { "code": null, "e": 11241, "s": 11211, "text": "element.all(locator).evaluate" }, { "code": null, "e": 11360, "s": 11241, "text": "As the name suggests, it will evaluate the input whether it is on the scope of the current underlying elements or not." }, { "code": null, "e": 11368, "s": 11360, "text": "Example" }, { "code": null, "e": 11373, "s": 11368, "text": "View" }, { "code": null, "e": 11418, "s": 11373, "text": "<span id = \"foo\">{{letiableInScope}}</span>\n" }, { "code": null, "e": 11423, "s": 11418, "text": "Code" }, { "code": null, "e": 11487, "s": 11423, "text": "let value = element(by.id('.foo')).evaluate('letiableInScope');" }, { "code": null, "e": 11520, "s": 11487, "text": "element(locator).allowAnimations" }, { "code": null, "e": 11636, "s": 11520, "text": "As the name suggests, it will determine whether the animation is allowed on the current underlying elements or not." }, { "code": null, "e": 11644, "s": 11636, "text": "Example" }, { "code": null, "e": 11693, "s": 11644, "text": "element(by.css('body')).allowAnimations(false);\n" }, { "code": null, "e": 11717, "s": 11693, "text": "element(locator).equals" }, { "code": null, "e": 11780, "s": 11717, "text": "As the name suggests, it will compare an element for equality." }, { "code": null, "e": 11925, "s": 11780, "text": "It is basically a collection of element locator strategies that provides ways of finding elements in Angular applications by binding, model etc." }, { "code": null, "e": 11958, "s": 11925, "text": "Functions and their descriptions" }, { "code": null, "e": 12015, "s": 11958, "text": "The functions of ProtractorLocators API are as follows −" }, { "code": null, "e": 12058, "s": 12015, "text": "by.addLocator(locatorName,fuctionOrScript)" }, { "code": null, "e": 12175, "s": 12058, "text": "It will add a locator to this instance of ProtrcatorBy which further can be used with element(by.locatorName(args))." }, { "code": null, "e": 12183, "s": 12175, "text": "Example" }, { "code": null, "e": 12188, "s": 12183, "text": "View" }, { "code": null, "e": 12235, "s": 12188, "text": "<button ng-click = \"doAddition()\">Go!</button>" }, { "code": null, "e": 12240, "s": 12235, "text": "Code" }, { "code": null, "e": 12655, "s": 12240, "text": "// Adding the custom locator.\nby.addLocator('buttonTextSimple', function(buttonText, opt_parentElement, opt_rootSelector) {\n var using = opt_parentElement || document,\n buttons = using.querySelectorAll('button');\n return Array.prototype.filter.call(buttons, function(button) {\n return button.textContent === buttonText;\n });\n});\nelement(by.buttonTextSimple('Go!')).click();// Using the custom locator." }, { "code": null, "e": 12666, "s": 12655, "text": "by.binding" }, { "code": null, "e": 12848, "s": 12666, "text": "As the name suggests, it will find an element by text binding. A partial match will be done so that any elements bound to the variables containing the input string will be returned." }, { "code": null, "e": 12856, "s": 12848, "text": "Example" }, { "code": null, "e": 12861, "s": 12856, "text": "View" }, { "code": null, "e": 12929, "s": 12861, "text": "<span>{{person.name}}</span>\n<span ng-bind = \"person.email\"></span>" }, { "code": null, "e": 12934, "s": 12929, "text": "Code" }, { "code": null, "e": 13114, "s": 12934, "text": "var span1 = element(by.binding('person.name'));\nexpect(span1.getText()).toBe('Foo');\n\nvar span2 = element(by.binding('person.email'));\nexpect(span2.getText()).toBe('foo@bar.com');" }, { "code": null, "e": 13130, "s": 13114, "text": "by.exactbinding" }, { "code": null, "e": 13194, "s": 13130, "text": "As the name suggests, it will find an element by exact binding." }, { "code": null, "e": 13202, "s": 13194, "text": "Example" }, { "code": null, "e": 13207, "s": 13202, "text": "View" }, { "code": null, "e": 13327, "s": 13207, "text": "<spangt;{{ person.name }}</spangt;\n<span ng-bind = \"person-email\"gt;</spangt;\n<spangt;{{person_phone|uppercase}}</span>" }, { "code": null, "e": 13332, "s": 13327, "text": "Code" }, { "code": null, "e": 13768, "s": 13332, "text": "expect(element(by.exactBinding('person.name')).isPresent()).toBe(true);\nexpect(element(by.exactBinding('person-email')).isPresent()).toBe(true);\nexpect(element(by.exactBinding('person')).isPresent()).toBe(false);\nexpect(element(by.exactBinding('person_phone')).isPresent()).toBe(true);\nexpect(element(by.exactBinding('person_phone|uppercase')).isPresent()).toBe(true);\nexpect(element(by.exactBinding('phone')).isPresent()).toBe(false);" }, { "code": null, "e": 13788, "s": 13768, "text": "by.model(modelName)" }, { "code": null, "e": 13858, "s": 13788, "text": "As the name suggests, it will find an element by ng-model expression." }, { "code": null, "e": 13866, "s": 13858, "text": "Example" }, { "code": null, "e": 13871, "s": 13866, "text": "View" }, { "code": null, "e": 13918, "s": 13871, "text": "<input type = \"text\" ng-model = \"person.name\">" }, { "code": null, "e": 13923, "s": 13918, "text": "Code" }, { "code": null, "e": 14044, "s": 13923, "text": "var input = element(by.model('person.name'));\ninput.sendKeys('123');\nexpect(input.getAttribute('value')).toBe('Foo123');" }, { "code": null, "e": 14058, "s": 14044, "text": "by.buttonText" }, { "code": null, "e": 14111, "s": 14058, "text": "As the name suggests, it will find a button by text." }, { "code": null, "e": 14119, "s": 14111, "text": "Example" }, { "code": null, "e": 14124, "s": 14119, "text": "View" }, { "code": null, "e": 14147, "s": 14124, "text": "<button>Save</button>\n" }, { "code": null, "e": 14152, "s": 14147, "text": "Code" }, { "code": null, "e": 14184, "s": 14152, "text": "element(by.buttonText('Save'));" }, { "code": null, "e": 14205, "s": 14184, "text": "by.partialButtonText" }, { "code": null, "e": 14266, "s": 14205, "text": "As the name suggests, it will find a button by partial text." }, { "code": null, "e": 14274, "s": 14266, "text": "Example" }, { "code": null, "e": 14279, "s": 14274, "text": "View" }, { "code": null, "e": 14309, "s": 14279, "text": "<button>Save my file</button>" }, { "code": null, "e": 14314, "s": 14309, "text": "Code" }, { "code": null, "e": 14353, "s": 14314, "text": "element(by.partialButtonText('Save'));" }, { "code": null, "e": 14365, "s": 14353, "text": "by.repeater" }, { "code": null, "e": 14432, "s": 14365, "text": "As the name suggests, it will find an element inside an ng-repeat." }, { "code": null, "e": 14440, "s": 14432, "text": "Example" }, { "code": null, "e": 14445, "s": 14440, "text": "View" }, { "code": null, "e": 14733, "s": 14445, "text": "<div ng-repeat = \"cat in pets\">\n <span>{{cat.name}}</span>\n <span>{{cat.age}}</span>\n<</div>\n<div class = \"book-img\" ng-repeat-start=\"book in library\">\n <span>{{$index}}</span>\n</div>\n<div class = \"book-info\" ng-repeat-end>\n <h4>{{book.name}}</h4>\n <p>{{book.blurb}}</p>\n</div>" }, { "code": null, "e": 14738, "s": 14733, "text": "Code" }, { "code": null, "e": 14984, "s": 14738, "text": "var secondCat = element(by.repeater('cat in \npets').row(1)); // It will return the DIV for the second cat.\nvar firstCatName = element(by.repeater('cat in pets').\n row(0).column('cat.name')); // It will return the SPAN for the first cat's name." }, { "code": null, "e": 15001, "s": 14984, "text": "by.exactRepeater" }, { "code": null, "e": 15066, "s": 15001, "text": "As the name suggests, it will find an element by exact repeater." }, { "code": null, "e": 15074, "s": 15066, "text": "Example" }, { "code": null, "e": 15079, "s": 15074, "text": "View" }, { "code": null, "e": 15182, "s": 15079, "text": "<li ng-repeat = \"person in peopleWithRedHair\"></li>\n<li ng-repeat = \"car in cars | orderBy:year\"></li>" }, { "code": null, "e": 15187, "s": 15182, "text": "Code" }, { "code": null, "e": 15432, "s": 15187, "text": "expect(element(by.exactRepeater('person in\npeopleWithRedHair')).isPresent())\n .toBe(true);\nexpect(element(by.exactRepeater('person in\npeople')).isPresent()).toBe(false);\nexpect(element(by.exactRepeater('car in cars')).isPresent()).toBe(true);" }, { "code": null, "e": 15453, "s": 15432, "text": "by.cssContainingText" }, { "code": null, "e": 15529, "s": 15453, "text": "As name suggest, it will find the elements, containing exact string, by CSS" }, { "code": null, "e": 15537, "s": 15529, "text": "Example" }, { "code": null, "e": 15542, "s": 15537, "text": "View" }, { "code": null, "e": 15607, "s": 15542, "text": "<ul>\n<li class = \"pet\">Dog</li>\n<li class = \"pet\">Cat</li>\n</ul>" }, { "code": null, "e": 15612, "s": 15607, "text": "Code" }, { "code": null, "e": 15728, "s": 15612, "text": "var dog = element(by.cssContainingText('.pet', 'Dog')); \n// It will return the li for the dog, but not for the cat." }, { "code": null, "e": 15758, "s": 15728, "text": "by.options(optionsDescriptor)" }, { "code": null, "e": 15830, "s": 15758, "text": "As the name suggests, it will find an element by ng-options expression." }, { "code": null, "e": 15838, "s": 15830, "text": "Example" }, { "code": null, "e": 15843, "s": 15838, "text": "View" }, { "code": null, "e": 16010, "s": 15843, "text": "<select ng-model = \"color\" ng-options = \"c for c in colors\">\n <option value = \"0\" selected = \"selected\">red</option>\n <option value = \"1\">green</option>\n</select>" }, { "code": null, "e": 16015, "s": 16010, "text": "Code" }, { "code": null, "e": 16201, "s": 16015, "text": "var allOptions = element.all(by.options('c for c in colors'));\nexpect(allOptions.count()).toEqual(2);\nvar firstOption = allOptions.first();\nexpect(firstOption.getText()).toEqual('red');" }, { "code": null, "e": 16222, "s": 16201, "text": "by.deepCSS(selector)" }, { "code": null, "e": 16302, "s": 16222, "text": "As name suggest, it will find an element by CSS selector within the shadow DOM." }, { "code": null, "e": 16310, "s": 16302, "text": "Example" }, { "code": null, "e": 16315, "s": 16310, "text": "View" }, { "code": null, "e": 16482, "s": 16315, "text": "<div>\n <span id = \"outerspan\">\n <\"shadow tree\">\n <span id = \"span1\"></span>\n <\"shadow tree\">\n <span id = \"span2\"></span>\n </>\n </>\n</div>" }, { "code": null, "e": 16487, "s": 16482, "text": "Code" }, { "code": null, "e": 16566, "s": 16487, "text": "var spans = element.all(by.deepCss('span'));\nexpect(spans.count()).toEqual(3);" }, { "code": null, "e": 16601, "s": 16566, "text": "\n 35 Lectures \n 3.5 hours \n" }, { "code": null, "e": 16620, "s": 16601, "text": " SAYANTAN TARAFDAR" }, { "code": null, "e": 16653, "s": 16620, "text": "\n 18 Lectures \n 3 hours \n" }, { "code": null, "e": 16669, "s": 16653, "text": " LuckyTrainings" }, { "code": null, "e": 16676, "s": 16669, "text": " Print" }, { "code": null, "e": 16687, "s": 16676, "text": " Add Notes" } ]
Check if a string has all characters with same frequency with one variation allowed
05 Jul, 2022 Given a string of lowercase alphabets, find if it can be converted to a Valid String by removing 1 or 0 characters. A “valid” string is string str such that for all distinct characters in str each such character occurs the same number of times in it. Examples : Input : string str = "abbca" Output : Yes We can make it valid by removing "c" Input : string str = "aabbcd" Output : No We need to remove at least two characters to make it valid. Input : string str = "abbccd" Output : No We are allowed to traverse string only once. The idea is to use a frequency array that stores frequencies of all characters. Once we have frequencies of all characters in an array, we check if count of total different and non-zero values are not more than 2. Also, one of the counts of two allowed different frequencies must be less than or equal to 2. Below is the implementation of idea. Implementation: C++ C Java Python3 C# Javascript // C++ program to check if a string can be made// valid by removing at most 1 character.#include <bits/stdc++.h>using namespace std; // Assuming only lower case charactersconst int CHARS = 26; // To check a string S can be converted to a “valid” string// by removing less than or equal to one character.bool isValidString(string str){ int freq[CHARS] = { 0 }; // freq[] : stores the frequency of each character of a // string for (int i = 0; i < str.length(); i++) freq[str[i] - 'a']++; // Find first character with non-zero frequency int i, freq1 = 0, count_freq1 = 0; for (i = 0; i < CHARS; i++) { if (freq[i] != 0) { freq1 = freq[i]; count_freq1 = 1; break; } } // Find a character with frequency different from freq1. int j, freq2 = 0, count_freq2 = 0; for (j = i + 1; j < CHARS; j++) { if (freq[j] != 0) { if (freq[j] == freq1) count_freq1++; else { count_freq2 = 1; freq2 = freq[j]; break; } } } // If we find a third non-zero frequency or count of // both frequencies become more than 1, then return // false for (int k = j + 1; k < CHARS; k++) { if (freq[k] != 0) { if (freq[k] == freq1) count_freq1++; if (freq[k] == freq2) count_freq2++; else // If we find a third non-zero freq return false; } // If counts of both frequencies is more than 1 if (count_freq1 > 1 && count_freq2 > 1) return false; } // Return true if we reach here return true;} // Driver codeint main(){ char str[] = "abcbc"; if (isValidString(str)) cout << "YES" << endl; else cout << "NO" << endl; return 0;} // This code is contributed by Aditya Kumar (adityakumar129) // C program to check if a string can be made// valid by removing at most 1 character.#include <stdbool.h>#include <stdio.h>#include <string.h> // Assuming only lower case charactersconst int CHARS = 26; // To check a string S can be converted to a “valid” string// by removing less than or equal to one character.bool isValidString(char str[]){ int freq[CHARS]; for (int i = 0; i < CHARS; i++) freq[i] = 0; // freq[] : stores the frequency of each character of a // string for (int i = 0; i < strlen(str); i++) freq[str[i] - 'a']++; // Find first character with non-zero frequency int i, freq1 = 0, count_freq1 = 0; for (i = 0; i < CHARS; i++) { if (freq[i] != 0) { freq1 = freq[i]; count_freq1 = 1; break; } } // Find a character with frequency different from freq1. int j, freq2 = 0, count_freq2 = 0; for (j = i + 1; j < CHARS; j++) { if (freq[j] != 0) { if (freq[j] == freq1) count_freq1++; else { count_freq2 = 1; freq2 = freq[j]; break; } } } // If we find a third non-zero frequency or count of // both frequencies become more than 1, then return // false for (int k = j + 1; k < CHARS; k++) { if (freq[k] != 0) { if (freq[k] == freq1) count_freq1++; if (freq[k] == freq2) count_freq2++; else // If we find a third non-zero freq return false; } // If counts of both frequencies is more than 1 if (count_freq1 > 1 && count_freq2 > 1) return false; } // Return true if we reach here return true;} // Driver codeint main(){ char str[] = "abcbc"; if (isValidString(str)) printf("YES\n"); else printf("NO\n"); return 0;} // This code is contributed by Aditya Kumar (adityakumar129) // Java program to check if a string can be made// valid by removing at most 1 character.public class GFG { // Assuming only lower case characters static int CHARS = 26; /* To check a string S can be converted to a “valid” string by removing less than or equal to one character. */ static boolean isValidString(String str) { int freq[] = new int[CHARS]; // freq[] : stores the frequency of each // character of a string for (int i = 0; i < str.length(); i++) { freq[str.charAt(i) - 'a']++; } // Find first character with non-zero frequency int i, freq1 = 0, count_freq1 = 0; for (i = 0; i < CHARS; i++) { if (freq[i] != 0) { freq1 = freq[i]; count_freq1 = 1; break; } } // Find a character with frequency different // from freq1. int j, freq2 = 0, count_freq2 = 0; for (j = i + 1; j < CHARS; j++) { if (freq[j] != 0) { if (freq[j] == freq1) { count_freq1++; } else { count_freq2 = 1; freq2 = freq[j]; break; } } } // If we find a third non-zero frequency // or count of both frequencies become more // than 1, then return false for (int k = j + 1; k < CHARS; k++) { if (freq[k] != 0) { if (freq[k] == freq1) { count_freq1++; } if (freq[k] == freq2) { count_freq2++; } else // If we find a third non-zero freq { return false; } } // If counts of both frequencies is more than 1 if (count_freq1 > 1 && count_freq2 > 1) { return false; } } // Return true if we reach here return true; } // Driver code public static void main(String[] args) { String str = "abcbc"; if (isValidString(str)) { System.out.println("YES"); } else { System.out.println("NO"); } }}// This code is contributed by Aditya Kumar (adityakumar129) # Python 3 program to check if# a string can be made# valid by removing at most 1 character. # Assuming only lower case charactersCHARS = 26 # To check a string S can be converted to a “valid”# string by removing less than or equal to one# character. def isValidString(str): freq = [0]*CHARS # freq[] : stores the frequency of each # character of a string for i in range(len(str)): freq[ord(str[i])-ord('a')] += 1 # Find first character with non-zero frequency freq1 = 0 count_freq1 = 0 for i in range(CHARS): if (freq[i] != 0): freq1 = freq[i] count_freq1 = 1 break # Find a character with frequency different # from freq1. freq2 = 0 count_freq2 = 0 for j in range(i+1,CHARS): if (freq[j] != 0): if (freq[j] == freq1): count_freq1 += 1 else: count_freq2 = 1 freq2 = freq[j] break # If we find a third non-zero frequency # or count of both frequencies become more # than 1, then return false for k in range(j+1,CHARS): if (freq[k] != 0): if (freq[k] == freq1): count_freq1 += 1 if (freq[k] == freq2): count_freq2 += 1 # If we find a third non-zero freq else: return False # If counts of both frequencies is more than 1 if (count_freq1 > 1 and count_freq2 > 1): return False # Return true if we reach here return True # Driver codeif __name__ == "__main__": str= "abcbc" if (isValidString(str)): print("YES") else: print("NO") # this code is contributed by# ChitraNayal // C# program to check if a string can be made// valid by removing at most 1 character.using System;public class GFG { // Assuming only lower case characters static int CHARS = 26; /* To check a string S can be converted to a “valid”string by removing less than or equal to onecharacter. */ static bool isValidString(String str) { int []freq = new int[CHARS]; int i=0; // freq[] : stores the frequency of each // character of a string for ( i= 0; i < str.Length; i++) { freq[str[i] - 'a']++; } // Find first character with non-zero frequency int freq1 = 0, count_freq1 = 0; for (i = 0; i < CHARS; i++) { if (freq[i] != 0) { freq1 = freq[i]; count_freq1 = 1; break; } } // Find a character with frequency different // from freq1. int j, freq2 = 0, count_freq2 = 0; for (j = i + 1; j < CHARS; j++) { if (freq[j] != 0) { if (freq[j] == freq1) { count_freq1++; } else { count_freq2 = 1; freq2 = freq[j]; break; } } } // If we find a third non-zero frequency // or count of both frequencies become more // than 1, then return false for (int k = j + 1; k < CHARS; k++) { if (freq[k] != 0) { if (freq[k] == freq1) { count_freq1++; } if (freq[k] == freq2) { count_freq2++; } else // If we find a third non-zero freq { return false; } } // If counts of both frequencies is more than 1 if (count_freq1 > 1 && count_freq2 > 1) { return false; } } // Return true if we reach here return true; } // Driver code public static void Main() { String str = "abcbc"; if (isValidString(str)) { Console.WriteLine("YES"); } else { Console.WriteLine("NO"); } }} // This code is contributed by 29AjayKumar <script> // JavaScript program to check if a string can be made// valid by removing at most 1 character. // Assuming only lower case characterslet CHARS = 26; /* To check a string S can be converted to a “valid” string by removing less than or equal to one character. */function isValidString(str){ let freq = new Array(CHARS); for(let i=0;i<CHARS;i++) { freq[i]=0; } // freq[] : stores the frequency of each // character of a string for (let i = 0; i < str.length; i++) { freq[str[i].charCodeAt(0) - 'a'.charCodeAt(0)]++; } // Find first character with non-zero frequency let i, freq1 = 0, count_freq1 = 0; for (i = 0; i < CHARS; i++) { if (freq[i] != 0) { freq1 = freq[i]; count_freq1 = 1; break; } } // Find a character with frequency different // from freq1. let j, freq2 = 0, count_freq2 = 0; for (j = i + 1; j < CHARS; j++) { if (freq[j] != 0) { if (freq[j] == freq1) { count_freq1++; } else { count_freq2 = 1; freq2 = freq[j]; break; } } } // If we find a third non-zero frequency // or count of both frequencies become more // than 1, then return false for (let k = j + 1; k < CHARS; k++) { if (freq[k] != 0) { if (freq[k] == freq1) { count_freq1++; } if (freq[k] == freq2) { count_freq2++; } else // If we find a third non-zero freq { return false; } } // If counts of both frequencies is more than 1 if (count_freq1 > 1 && count_freq2 > 1) { return false; } } // Return true if we reach here return true;} // Driver codelet str = "abcbc"; if (isValidString(str)) { document.write("YES"); } else { document.write("NO"); } // This code is contributed by ab2127 </script> YES Time Complexity: O(N), where N is the length of the given string.Auxiliary Space: O(1), no other extra space is required, so it is a constant. We traverse string only once. Also the three loops after the first loop run CHARS times in total. Another method: (Using HashMap) Below is the implementation. C++ Java Python3 C# Javascript // C++ program to check if a string can be made// valid by removing at most 1 character using hashmap.#include <bits/stdc++.h>using namespace std; // To check a string S can be converted to a variation// string bool checkForVariation(string str){ if(str.empty() || str.length() != 0) { return true; } map<char, int> mapp; // Run loop form 0 to length of string for(int i = 0; i < str.length(); i++) { mapp[str[i]]++; } // declaration of variables bool first = true, second = true; int val1 = 0, val2 = 0; int countOfVal1 = 0, countOfVal2 = 0; map<char, int>::iterator itr; for (itr = mapp.begin(); itr != mapp.end(); ++itr) { int i = itr->first; // if first is true than countOfVal1 increase if(first) { val1 = i; first = false; countOfVal1++; continue; } if(i == val1) { countOfVal1++; continue; } // if second is true than countOfVal2 increase if(second) { val2 = i; countOfVal2++; second = false; continue; } if(i == val2) { countOfVal2++; continue; } return false; } if(countOfVal1 > 1 && countOfVal2 > 1) { return false; } else { return true; } } // Driver codeint main() { if(checkForVariation("abcbcvf")) cout << "true" << endl; else cout << "false" << endl; return 0;} // This code is contributed by avanitrachhadiya2155 // Java program to check if a string can be made// valid by removing at most 1 character using hashmap.import java.util.HashMap;import java.util.Iterator;import java.util.Map; public class AllCharsWithSameFrequencyWithOneVarAllowed { // To check a string S can be converted to a variation // string public static boolean checkForVariation(String str) { if(str == null || str.isEmpty()) { return true; } Map<Character, Integer> map = new HashMap<>(); // Run loop form 0 to length of string for(int i = 0; i < str.length(); i++) { map.put(str.charAt(i), map.getOrDefault(str.charAt(i), 0) + 1); } Iterator<Integer> itr = map.values().iterator(); // declaration of variables boolean first = true, second = true; int val1 = 0, val2 = 0; int countOfVal1 = 0, countOfVal2 = 0; while(itr.hasNext()) { int i = itr.next(); // if first is true than countOfVal1 increase if(first) { val1 = i; first = false; countOfVal1++; continue; } if(i == val1) { countOfVal1++; continue; } // if second is true than countOfVal2 increase if(second) { val2 = i; countOfVal2++; second = false; continue; } if(i == val2) { countOfVal2++; continue; } return false; } if(countOfVal1 > 1 && countOfVal2 > 1) { return false; }else { return true; } } // Driver code public static void main(String[] args) { System.out.println(checkForVariation("abcbc")); }} # Python program to check if a string can be made# valid by removing at most 1 character using hashmap. # To check a string S can be converted to a variation# stringdef checkForVariation(strr): if(len(strr) == 0): return True mapp = {} # Run loop form 0 to length of string for i in range(len(strr)): if strr[i] in mapp: mapp[strr[i]] += 1 else: mapp[strr[i]] = 1 # declaration of variables first = True second = True val1 = 0 val2 = 0 countOfVal1 = 0 countOfVal2 = 0 for itr in mapp: i = itr # if first is true than countOfVal1 increase if(first): val1 = i first = False countOfVal1 += 1 continue if(i == val1): countOfVal1 += 1 continue # if second is true than countOfVal2 increase if(second): val2 = i countOfVal2 += 1 second = False continue if(i == val2): countOfVal2 += 1 continue if(countOfVal1 > 1 and countOfVal2 > 1): return False else: return True # Driver codeprint(checkForVariation("abcbc")) # This code is contributed by rag2127 // C# program to check if a string can be made// valid by removing at most 1 character using hashmap.using System;using System.Collections.Generic; public class AllCharsWithSameFrequencyWithOneVarAllowed{ // To check a string S can be converted to a variation // string public static bool checkForVariation(String str) { if(str == null || str.Length != 0) { return true; } Dictionary<char, int> map = new Dictionary<char, int>(); // Run loop form 0 to length of string for(int i = 0; i < str.Length; i++) { if(map.ContainsKey(str[i])) map[str[i]] = map[str[i]]+1; else map.Add(str[i], 1); } // declaration of variables bool first = true, second = true; int val1 = 0, val2 = 0; int countOfVal1 = 0, countOfVal2 = 0; foreach(KeyValuePair<char, int> itr in map) { int i = itr.Key; // if first is true than countOfVal1 increase if(first) { val1 = i; first = false; countOfVal1++; continue; } if(i == val1) { countOfVal1++; continue; } // if second is true than countOfVal2 increase if(second) { val2 = i; countOfVal2++; second = false; continue; } if(i == val2) { countOfVal2++; continue; } return false; } if(countOfVal1 > 1 && countOfVal2 > 1) { return false; } else { return true; } } // Driver code public static void Main(String[] args) { Console.WriteLine(checkForVariation("abcbc")); }} // This code is contributed by 29AjayKumar <script> // JavaScript program to check if a string can be made// valid by removing at most 1 character using hashmap. // To check a string S can be converted to a variation // stringfunction checkForVariation(str){ if(str == null || str.length==0) { return true; } let map = new Map(); // Run loop form 0 to length of string for(let i = 0; i < str.length; i++) { if(!map.has(str[i])) map.set(str[i],0); map.set(str[i], map.get(str[i]) + 1); } // declaration of variables let first = true, second = true; let val1 = 0, val2 = 0; let countOfVal1 = 0, countOfVal2 = 0; for(let [key, value] of map.entries()) { let i = value; // if first is true than countOfVal1 increase if(first) { val1 = i; first = false; countOfVal1++; continue; } if(i == val1) { countOfVal1++; continue; } // if second is true than countOfVal2 increase if(second) { val2 = i; countOfVal2++; second = false; continue; } if(i == val2) { countOfVal2++; continue; } return false; } if(countOfVal1 > 1 && countOfVal2 > 1) { return false; }else { return true; }} // Driver codedocument.write(checkForVariation("abcbc")); // This code is contributed by patel2127 </script> true Time Complexity: O(NlogN), where N is the length of the given string.Auxiliary Space: O(N) Calculate the frequencies of all characters using Counter() function. Convert these frequencies to the list. Calculate again the frequencies of this list using Counter. If the length of Counter is 1 then return true. If the length of Counter is 2 if min value is 1 then return true. Else return False. Below is the implementation: Python3 # Python programfrom collections import Counter # To check a string S can be# converted to a variation# stringdef checkForVariation(strr): freq = Counter(strr) # Converting these values to list valuelist = list(freq.values()) # Counting frequencies again ValueCounter = Counter(valuelist) if(len(ValueCounter) == 1): return True elif(len(ValueCounter) == 2 and min(ValueCounter.values()) == 1): return True # If no conditions satisfied return false return False # Driver codestring = "abcbc" # passing string to checkForVariation Functionprint(checkForVariation(string)) # This code is contributed by vikkycirus True Time Complexity: O(n)Space Complexity: O(n) This article is contributed by Nishant_singh(pintu). 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. Harsh Bansal 2 Arun Kumar 1 ukasp princiraj1992 29AjayKumar avanitrachhadiya2155 rag2127 vikkycirus ab2127 patel2127 surinderdawra388 adityakumar129 samim2000 hardikkoriintern Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python program to check if a string is palindrome or not KMP Algorithm for Pattern Searching Longest Palindromic Substring | Set 1 Length of the longest substring without repeating characters Top 50 String Coding Problems for Interviews Check whether two strings are anagram of each other Reverse words in a given string Convert string to char array in C++ What is Data Structure: Types, Classifications and Applications Print all the duplicates in the input string
[ { "code": null, "e": 54, "s": 26, "text": "\n05 Jul, 2022" }, { "code": null, "e": 305, "s": 54, "text": "Given a string of lowercase alphabets, find if it can be converted to a Valid String by removing 1 or 0 characters. A “valid” string is string str such that for all distinct characters in str each such character occurs the same number of times in it." }, { "code": null, "e": 317, "s": 305, "text": "Examples : " }, { "code": null, "e": 542, "s": 317, "text": "Input : string str = \"abbca\"\nOutput : Yes\nWe can make it valid by removing \"c\"\n\nInput : string str = \"aabbcd\"\nOutput : No\nWe need to remove at least two characters\nto make it valid.\n\nInput : string str = \"abbccd\"\nOutput : No" }, { "code": null, "e": 588, "s": 542, "text": "We are allowed to traverse string only once. " }, { "code": null, "e": 934, "s": 588, "text": "The idea is to use a frequency array that stores frequencies of all characters. Once we have frequencies of all characters in an array, we check if count of total different and non-zero values are not more than 2. Also, one of the counts of two allowed different frequencies must be less than or equal to 2. Below is the implementation of idea. " }, { "code": null, "e": 950, "s": 934, "text": "Implementation:" }, { "code": null, "e": 954, "s": 950, "text": "C++" }, { "code": null, "e": 956, "s": 954, "text": "C" }, { "code": null, "e": 961, "s": 956, "text": "Java" }, { "code": null, "e": 969, "s": 961, "text": "Python3" }, { "code": null, "e": 972, "s": 969, "text": "C#" }, { "code": null, "e": 983, "s": 972, "text": "Javascript" }, { "code": "// C++ program to check if a string can be made// valid by removing at most 1 character.#include <bits/stdc++.h>using namespace std; // Assuming only lower case charactersconst int CHARS = 26; // To check a string S can be converted to a “valid” string// by removing less than or equal to one character.bool isValidString(string str){ int freq[CHARS] = { 0 }; // freq[] : stores the frequency of each character of a // string for (int i = 0; i < str.length(); i++) freq[str[i] - 'a']++; // Find first character with non-zero frequency int i, freq1 = 0, count_freq1 = 0; for (i = 0; i < CHARS; i++) { if (freq[i] != 0) { freq1 = freq[i]; count_freq1 = 1; break; } } // Find a character with frequency different from freq1. int j, freq2 = 0, count_freq2 = 0; for (j = i + 1; j < CHARS; j++) { if (freq[j] != 0) { if (freq[j] == freq1) count_freq1++; else { count_freq2 = 1; freq2 = freq[j]; break; } } } // If we find a third non-zero frequency or count of // both frequencies become more than 1, then return // false for (int k = j + 1; k < CHARS; k++) { if (freq[k] != 0) { if (freq[k] == freq1) count_freq1++; if (freq[k] == freq2) count_freq2++; else // If we find a third non-zero freq return false; } // If counts of both frequencies is more than 1 if (count_freq1 > 1 && count_freq2 > 1) return false; } // Return true if we reach here return true;} // Driver codeint main(){ char str[] = \"abcbc\"; if (isValidString(str)) cout << \"YES\" << endl; else cout << \"NO\" << endl; return 0;} // This code is contributed by Aditya Kumar (adityakumar129)", "e": 2901, "s": 983, "text": null }, { "code": "// C program to check if a string can be made// valid by removing at most 1 character.#include <stdbool.h>#include <stdio.h>#include <string.h> // Assuming only lower case charactersconst int CHARS = 26; // To check a string S can be converted to a “valid” string// by removing less than or equal to one character.bool isValidString(char str[]){ int freq[CHARS]; for (int i = 0; i < CHARS; i++) freq[i] = 0; // freq[] : stores the frequency of each character of a // string for (int i = 0; i < strlen(str); i++) freq[str[i] - 'a']++; // Find first character with non-zero frequency int i, freq1 = 0, count_freq1 = 0; for (i = 0; i < CHARS; i++) { if (freq[i] != 0) { freq1 = freq[i]; count_freq1 = 1; break; } } // Find a character with frequency different from freq1. int j, freq2 = 0, count_freq2 = 0; for (j = i + 1; j < CHARS; j++) { if (freq[j] != 0) { if (freq[j] == freq1) count_freq1++; else { count_freq2 = 1; freq2 = freq[j]; break; } } } // If we find a third non-zero frequency or count of // both frequencies become more than 1, then return // false for (int k = j + 1; k < CHARS; k++) { if (freq[k] != 0) { if (freq[k] == freq1) count_freq1++; if (freq[k] == freq2) count_freq2++; else // If we find a third non-zero freq return false; } // If counts of both frequencies is more than 1 if (count_freq1 > 1 && count_freq2 > 1) return false; } // Return true if we reach here return true;} // Driver codeint main(){ char str[] = \"abcbc\"; if (isValidString(str)) printf(\"YES\\n\"); else printf(\"NO\\n\"); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)", "e": 4864, "s": 2901, "text": null }, { "code": "// Java program to check if a string can be made// valid by removing at most 1 character.public class GFG { // Assuming only lower case characters static int CHARS = 26; /* To check a string S can be converted to a “valid” string by removing less than or equal to one character. */ static boolean isValidString(String str) { int freq[] = new int[CHARS]; // freq[] : stores the frequency of each // character of a string for (int i = 0; i < str.length(); i++) { freq[str.charAt(i) - 'a']++; } // Find first character with non-zero frequency int i, freq1 = 0, count_freq1 = 0; for (i = 0; i < CHARS; i++) { if (freq[i] != 0) { freq1 = freq[i]; count_freq1 = 1; break; } } // Find a character with frequency different // from freq1. int j, freq2 = 0, count_freq2 = 0; for (j = i + 1; j < CHARS; j++) { if (freq[j] != 0) { if (freq[j] == freq1) { count_freq1++; } else { count_freq2 = 1; freq2 = freq[j]; break; } } } // If we find a third non-zero frequency // or count of both frequencies become more // than 1, then return false for (int k = j + 1; k < CHARS; k++) { if (freq[k] != 0) { if (freq[k] == freq1) { count_freq1++; } if (freq[k] == freq2) { count_freq2++; } else // If we find a third non-zero freq { return false; } } // If counts of both frequencies is more than 1 if (count_freq1 > 1 && count_freq2 > 1) { return false; } } // Return true if we reach here return true; } // Driver code public static void main(String[] args) { String str = \"abcbc\"; if (isValidString(str)) { System.out.println(\"YES\"); } else { System.out.println(\"NO\"); } }}// This code is contributed by Aditya Kumar (adityakumar129)", "e": 7196, "s": 4864, "text": null }, { "code": "# Python 3 program to check if# a string can be made# valid by removing at most 1 character. # Assuming only lower case charactersCHARS = 26 # To check a string S can be converted to a “valid”# string by removing less than or equal to one# character. def isValidString(str): freq = [0]*CHARS # freq[] : stores the frequency of each # character of a string for i in range(len(str)): freq[ord(str[i])-ord('a')] += 1 # Find first character with non-zero frequency freq1 = 0 count_freq1 = 0 for i in range(CHARS): if (freq[i] != 0): freq1 = freq[i] count_freq1 = 1 break # Find a character with frequency different # from freq1. freq2 = 0 count_freq2 = 0 for j in range(i+1,CHARS): if (freq[j] != 0): if (freq[j] == freq1): count_freq1 += 1 else: count_freq2 = 1 freq2 = freq[j] break # If we find a third non-zero frequency # or count of both frequencies become more # than 1, then return false for k in range(j+1,CHARS): if (freq[k] != 0): if (freq[k] == freq1): count_freq1 += 1 if (freq[k] == freq2): count_freq2 += 1 # If we find a third non-zero freq else: return False # If counts of both frequencies is more than 1 if (count_freq1 > 1 and count_freq2 > 1): return False # Return true if we reach here return True # Driver codeif __name__ == \"__main__\": str= \"abcbc\" if (isValidString(str)): print(\"YES\") else: print(\"NO\") # this code is contributed by# ChitraNayal", "e": 8974, "s": 7196, "text": null }, { "code": "// C# program to check if a string can be made// valid by removing at most 1 character.using System;public class GFG { // Assuming only lower case characters static int CHARS = 26; /* To check a string S can be converted to a “valid”string by removing less than or equal to onecharacter. */ static bool isValidString(String str) { int []freq = new int[CHARS]; int i=0; // freq[] : stores the frequency of each // character of a string for ( i= 0; i < str.Length; i++) { freq[str[i] - 'a']++; } // Find first character with non-zero frequency int freq1 = 0, count_freq1 = 0; for (i = 0; i < CHARS; i++) { if (freq[i] != 0) { freq1 = freq[i]; count_freq1 = 1; break; } } // Find a character with frequency different // from freq1. int j, freq2 = 0, count_freq2 = 0; for (j = i + 1; j < CHARS; j++) { if (freq[j] != 0) { if (freq[j] == freq1) { count_freq1++; } else { count_freq2 = 1; freq2 = freq[j]; break; } } } // If we find a third non-zero frequency // or count of both frequencies become more // than 1, then return false for (int k = j + 1; k < CHARS; k++) { if (freq[k] != 0) { if (freq[k] == freq1) { count_freq1++; } if (freq[k] == freq2) { count_freq2++; } else // If we find a third non-zero freq { return false; } } // If counts of both frequencies is more than 1 if (count_freq1 > 1 && count_freq2 > 1) { return false; } } // Return true if we reach here return true; } // Driver code public static void Main() { String str = \"abcbc\"; if (isValidString(str)) { Console.WriteLine(\"YES\"); } else { Console.WriteLine(\"NO\"); } }} // This code is contributed by 29AjayKumar", "e": 11223, "s": 8974, "text": null }, { "code": "<script> // JavaScript program to check if a string can be made// valid by removing at most 1 character. // Assuming only lower case characterslet CHARS = 26; /* To check a string S can be converted to a “valid” string by removing less than or equal to one character. */function isValidString(str){ let freq = new Array(CHARS); for(let i=0;i<CHARS;i++) { freq[i]=0; } // freq[] : stores the frequency of each // character of a string for (let i = 0; i < str.length; i++) { freq[str[i].charCodeAt(0) - 'a'.charCodeAt(0)]++; } // Find first character with non-zero frequency let i, freq1 = 0, count_freq1 = 0; for (i = 0; i < CHARS; i++) { if (freq[i] != 0) { freq1 = freq[i]; count_freq1 = 1; break; } } // Find a character with frequency different // from freq1. let j, freq2 = 0, count_freq2 = 0; for (j = i + 1; j < CHARS; j++) { if (freq[j] != 0) { if (freq[j] == freq1) { count_freq1++; } else { count_freq2 = 1; freq2 = freq[j]; break; } } } // If we find a third non-zero frequency // or count of both frequencies become more // than 1, then return false for (let k = j + 1; k < CHARS; k++) { if (freq[k] != 0) { if (freq[k] == freq1) { count_freq1++; } if (freq[k] == freq2) { count_freq2++; } else // If we find a third non-zero freq { return false; } } // If counts of both frequencies is more than 1 if (count_freq1 > 1 && count_freq2 > 1) { return false; } } // Return true if we reach here return true;} // Driver codelet str = \"abcbc\"; if (isValidString(str)) { document.write(\"YES\"); } else { document.write(\"NO\"); } // This code is contributed by ab2127 </script>", "e": 13461, "s": 11223, "text": null }, { "code": null, "e": 13465, "s": 13461, "text": "YES" }, { "code": null, "e": 13608, "s": 13465, "text": "Time Complexity: O(N), where N is the length of the given string.Auxiliary Space: O(1), no other extra space is required, so it is a constant." }, { "code": null, "e": 13707, "s": 13608, "text": "We traverse string only once. Also the three loops after the first loop run CHARS times in total. " }, { "code": null, "e": 13740, "s": 13707, "text": "Another method: (Using HashMap) " }, { "code": null, "e": 13771, "s": 13740, "text": "Below is the implementation. " }, { "code": null, "e": 13775, "s": 13771, "text": "C++" }, { "code": null, "e": 13780, "s": 13775, "text": "Java" }, { "code": null, "e": 13788, "s": 13780, "text": "Python3" }, { "code": null, "e": 13791, "s": 13788, "text": "C#" }, { "code": null, "e": 13802, "s": 13791, "text": "Javascript" }, { "code": "// C++ program to check if a string can be made// valid by removing at most 1 character using hashmap.#include <bits/stdc++.h>using namespace std; // To check a string S can be converted to a variation// string bool checkForVariation(string str){ if(str.empty() || str.length() != 0) { return true; } map<char, int> mapp; // Run loop form 0 to length of string for(int i = 0; i < str.length(); i++) { mapp[str[i]]++; } // declaration of variables bool first = true, second = true; int val1 = 0, val2 = 0; int countOfVal1 = 0, countOfVal2 = 0; map<char, int>::iterator itr; for (itr = mapp.begin(); itr != mapp.end(); ++itr) { int i = itr->first; // if first is true than countOfVal1 increase if(first) { val1 = i; first = false; countOfVal1++; continue; } if(i == val1) { countOfVal1++; continue; } // if second is true than countOfVal2 increase if(second) { val2 = i; countOfVal2++; second = false; continue; } if(i == val2) { countOfVal2++; continue; } return false; } if(countOfVal1 > 1 && countOfVal2 > 1) { return false; } else { return true; } } // Driver codeint main() { if(checkForVariation(\"abcbcvf\")) cout << \"true\" << endl; else cout << \"false\" << endl; return 0;} // This code is contributed by avanitrachhadiya2155", "e": 15467, "s": 13802, "text": null }, { "code": "// Java program to check if a string can be made// valid by removing at most 1 character using hashmap.import java.util.HashMap;import java.util.Iterator;import java.util.Map; public class AllCharsWithSameFrequencyWithOneVarAllowed { // To check a string S can be converted to a variation // string public static boolean checkForVariation(String str) { if(str == null || str.isEmpty()) { return true; } Map<Character, Integer> map = new HashMap<>(); // Run loop form 0 to length of string for(int i = 0; i < str.length(); i++) { map.put(str.charAt(i), map.getOrDefault(str.charAt(i), 0) + 1); } Iterator<Integer> itr = map.values().iterator(); // declaration of variables boolean first = true, second = true; int val1 = 0, val2 = 0; int countOfVal1 = 0, countOfVal2 = 0; while(itr.hasNext()) { int i = itr.next(); // if first is true than countOfVal1 increase if(first) { val1 = i; first = false; countOfVal1++; continue; } if(i == val1) { countOfVal1++; continue; } // if second is true than countOfVal2 increase if(second) { val2 = i; countOfVal2++; second = false; continue; } if(i == val2) { countOfVal2++; continue; } return false; } if(countOfVal1 > 1 && countOfVal2 > 1) { return false; }else { return true; } } // Driver code public static void main(String[] args) { System.out.println(checkForVariation(\"abcbc\")); }}", "e": 17434, "s": 15467, "text": null }, { "code": "# Python program to check if a string can be made# valid by removing at most 1 character using hashmap. # To check a string S can be converted to a variation# stringdef checkForVariation(strr): if(len(strr) == 0): return True mapp = {} # Run loop form 0 to length of string for i in range(len(strr)): if strr[i] in mapp: mapp[strr[i]] += 1 else: mapp[strr[i]] = 1 # declaration of variables first = True second = True val1 = 0 val2 = 0 countOfVal1 = 0 countOfVal2 = 0 for itr in mapp: i = itr # if first is true than countOfVal1 increase if(first): val1 = i first = False countOfVal1 += 1 continue if(i == val1): countOfVal1 += 1 continue # if second is true than countOfVal2 increase if(second): val2 = i countOfVal2 += 1 second = False continue if(i == val2): countOfVal2 += 1 continue if(countOfVal1 > 1 and countOfVal2 > 1): return False else: return True # Driver codeprint(checkForVariation(\"abcbc\")) # This code is contributed by rag2127", "e": 18723, "s": 17434, "text": null }, { "code": "// C# program to check if a string can be made// valid by removing at most 1 character using hashmap.using System;using System.Collections.Generic; public class AllCharsWithSameFrequencyWithOneVarAllowed{ // To check a string S can be converted to a variation // string public static bool checkForVariation(String str) { if(str == null || str.Length != 0) { return true; } Dictionary<char, int> map = new Dictionary<char, int>(); // Run loop form 0 to length of string for(int i = 0; i < str.Length; i++) { if(map.ContainsKey(str[i])) map[str[i]] = map[str[i]]+1; else map.Add(str[i], 1); } // declaration of variables bool first = true, second = true; int val1 = 0, val2 = 0; int countOfVal1 = 0, countOfVal2 = 0; foreach(KeyValuePair<char, int> itr in map) { int i = itr.Key; // if first is true than countOfVal1 increase if(first) { val1 = i; first = false; countOfVal1++; continue; } if(i == val1) { countOfVal1++; continue; } // if second is true than countOfVal2 increase if(second) { val2 = i; countOfVal2++; second = false; continue; } if(i == val2) { countOfVal2++; continue; } return false; } if(countOfVal1 > 1 && countOfVal2 > 1) { return false; } else { return true; } } // Driver code public static void Main(String[] args) { Console.WriteLine(checkForVariation(\"abcbc\")); }} // This code is contributed by 29AjayKumar", "e": 20812, "s": 18723, "text": null }, { "code": "<script> // JavaScript program to check if a string can be made// valid by removing at most 1 character using hashmap. // To check a string S can be converted to a variation // stringfunction checkForVariation(str){ if(str == null || str.length==0) { return true; } let map = new Map(); // Run loop form 0 to length of string for(let i = 0; i < str.length; i++) { if(!map.has(str[i])) map.set(str[i],0); map.set(str[i], map.get(str[i]) + 1); } // declaration of variables let first = true, second = true; let val1 = 0, val2 = 0; let countOfVal1 = 0, countOfVal2 = 0; for(let [key, value] of map.entries()) { let i = value; // if first is true than countOfVal1 increase if(first) { val1 = i; first = false; countOfVal1++; continue; } if(i == val1) { countOfVal1++; continue; } // if second is true than countOfVal2 increase if(second) { val2 = i; countOfVal2++; second = false; continue; } if(i == val2) { countOfVal2++; continue; } return false; } if(countOfVal1 > 1 && countOfVal2 > 1) { return false; }else { return true; }} // Driver codedocument.write(checkForVariation(\"abcbc\")); // This code is contributed by patel2127 </script>", "e": 22566, "s": 20812, "text": null }, { "code": null, "e": 22571, "s": 22566, "text": "true" }, { "code": null, "e": 22662, "s": 22571, "text": "Time Complexity: O(NlogN), where N is the length of the given string.Auxiliary Space: O(N)" }, { "code": null, "e": 22732, "s": 22662, "text": "Calculate the frequencies of all characters using Counter() function." }, { "code": null, "e": 22771, "s": 22732, "text": "Convert these frequencies to the list." }, { "code": null, "e": 22831, "s": 22771, "text": "Calculate again the frequencies of this list using Counter." }, { "code": null, "e": 22879, "s": 22831, "text": "If the length of Counter is 1 then return true." }, { "code": null, "e": 22946, "s": 22879, "text": "If the length of Counter is 2 if min value is 1 then return true." }, { "code": null, "e": 22965, "s": 22946, "text": "Else return False." }, { "code": null, "e": 22994, "s": 22965, "text": "Below is the implementation:" }, { "code": null, "e": 23002, "s": 22994, "text": "Python3" }, { "code": "# Python programfrom collections import Counter # To check a string S can be# converted to a variation# stringdef checkForVariation(strr): freq = Counter(strr) # Converting these values to list valuelist = list(freq.values()) # Counting frequencies again ValueCounter = Counter(valuelist) if(len(ValueCounter) == 1): return True elif(len(ValueCounter) == 2 and min(ValueCounter.values()) == 1): return True # If no conditions satisfied return false return False # Driver codestring = \"abcbc\" # passing string to checkForVariation Functionprint(checkForVariation(string)) # This code is contributed by vikkycirus", "e": 23684, "s": 23002, "text": null }, { "code": null, "e": 23689, "s": 23684, "text": "True" }, { "code": null, "e": 23733, "s": 23689, "text": "Time Complexity: O(n)Space Complexity: O(n)" }, { "code": null, "e": 24037, "s": 23733, "text": "This article is contributed by Nishant_singh(pintu). 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": 24052, "s": 24037, "text": "Harsh Bansal 2" }, { "code": null, "e": 24065, "s": 24052, "text": "Arun Kumar 1" }, { "code": null, "e": 24071, "s": 24065, "text": "ukasp" }, { "code": null, "e": 24085, "s": 24071, "text": "princiraj1992" }, { "code": null, "e": 24097, "s": 24085, "text": "29AjayKumar" }, { "code": null, "e": 24118, "s": 24097, "text": "avanitrachhadiya2155" }, { "code": null, "e": 24126, "s": 24118, "text": "rag2127" }, { "code": null, "e": 24137, "s": 24126, "text": "vikkycirus" }, { "code": null, "e": 24144, "s": 24137, "text": "ab2127" }, { "code": null, "e": 24154, "s": 24144, "text": "patel2127" }, { "code": null, "e": 24171, "s": 24154, "text": "surinderdawra388" }, { "code": null, "e": 24186, "s": 24171, "text": "adityakumar129" }, { "code": null, "e": 24196, "s": 24186, "text": "samim2000" }, { "code": null, "e": 24213, "s": 24196, "text": "hardikkoriintern" }, { "code": null, "e": 24221, "s": 24213, "text": "Strings" }, { "code": null, "e": 24229, "s": 24221, "text": "Strings" }, { "code": null, "e": 24327, "s": 24229, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 24384, "s": 24327, "text": "Python program to check if a string is palindrome or not" }, { "code": null, "e": 24420, "s": 24384, "text": "KMP Algorithm for Pattern Searching" }, { "code": null, "e": 24458, "s": 24420, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 24519, "s": 24458, "text": "Length of the longest substring without repeating characters" }, { "code": null, "e": 24564, "s": 24519, "text": "Top 50 String Coding Problems for Interviews" }, { "code": null, "e": 24616, "s": 24564, "text": "Check whether two strings are anagram of each other" }, { "code": null, "e": 24648, "s": 24616, "text": "Reverse words in a given string" }, { "code": null, "e": 24684, "s": 24648, "text": "Convert string to char array in C++" }, { "code": null, "e": 24748, "s": 24684, "text": "What is Data Structure: Types, Classifications and Applications" } ]
Wand shadow() function – Python
22 Aug, 2021 The shadow() function is an inbuilt function in the Python Wand ImageMagick library which is used to generates an image shadow. Syntax: shadow(alpha, sigma, x, y) Parameters: This function accepts four parameters as mentioned above and defined below: alpha: This parameter stores the ratio of the transparency. sigma: This parameter stores the sigma level of the sharpen image. x: This parameter stores the x-offset. y: This parameter stores the y-offset. Return Value: This function returns the Wand ImageMagick object. Original Image:Example 1: # Import library from Image from wand.image import Image # Import the imagewith Image(filename ='../geeksforgeeks.png') as image: # Clone the image in order to process with image.clone() as shadow: # Invoke shadow function shadow.shadow(0.8, 0.2, 10, 40) # Save the image shadow.save(filename ='shadow1.jpg') Output: Example 2: # Import libraries from the wand from wand.image import Imagefrom wand.drawing import Drawingfrom wand.color import Color with Drawing() as draw: # Set Stroke color the circle to black draw.stroke_color = Color('black') # Set Width of the circle to 2 draw.stroke_width = 1 # Set the fill color to 'White (# FFFFFF)' draw.fill_color = Color('white') # Invoke Circle function with center at 50, 50 and radius 25 draw.circle((200, 200), # Center point (100, 100)) # Perimeter point # Set the font style draw.font = '../Helvetica.ttf' # Set the font size draw.font_size = 30 with Image(width = 400, height = 400, background = Color('# 45ff33')) as pic: # Set the text and its location draw.text(int(pic.width / 3), int(pic.height / 2), 'GeeksForGeeks !') # Draw the picture draw(pic) # Invoke shadow function method pic.shadow(0.3, .1, 1, 2) # Save the image pic.save(filename ='shadow2.jpg') Output: sagartomar9927 Image-Processing Python-wand Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Aug, 2021" }, { "code": null, "e": 156, "s": 28, "text": "The shadow() function is an inbuilt function in the Python Wand ImageMagick library which is used to generates an image shadow." }, { "code": null, "e": 164, "s": 156, "text": "Syntax:" }, { "code": null, "e": 191, "s": 164, "text": "shadow(alpha, sigma, x, y)" }, { "code": null, "e": 279, "s": 191, "text": "Parameters: This function accepts four parameters as mentioned above and defined below:" }, { "code": null, "e": 339, "s": 279, "text": "alpha: This parameter stores the ratio of the transparency." }, { "code": null, "e": 406, "s": 339, "text": "sigma: This parameter stores the sigma level of the sharpen image." }, { "code": null, "e": 445, "s": 406, "text": "x: This parameter stores the x-offset." }, { "code": null, "e": 484, "s": 445, "text": "y: This parameter stores the y-offset." }, { "code": null, "e": 549, "s": 484, "text": "Return Value: This function returns the Wand ImageMagick object." }, { "code": null, "e": 575, "s": 549, "text": "Original Image:Example 1:" }, { "code": "# Import library from Image from wand.image import Image # Import the imagewith Image(filename ='../geeksforgeeks.png') as image: # Clone the image in order to process with image.clone() as shadow: # Invoke shadow function shadow.shadow(0.8, 0.2, 10, 40) # Save the image shadow.save(filename ='shadow1.jpg')", "e": 919, "s": 575, "text": null }, { "code": null, "e": 927, "s": 919, "text": "Output:" }, { "code": null, "e": 938, "s": 927, "text": "Example 2:" }, { "code": "# Import libraries from the wand from wand.image import Imagefrom wand.drawing import Drawingfrom wand.color import Color with Drawing() as draw: # Set Stroke color the circle to black draw.stroke_color = Color('black') # Set Width of the circle to 2 draw.stroke_width = 1 # Set the fill color to 'White (# FFFFFF)' draw.fill_color = Color('white') # Invoke Circle function with center at 50, 50 and radius 25 draw.circle((200, 200), # Center point (100, 100)) # Perimeter point # Set the font style draw.font = '../Helvetica.ttf' # Set the font size draw.font_size = 30 with Image(width = 400, height = 400, background = Color('# 45ff33')) as pic: # Set the text and its location draw.text(int(pic.width / 3), int(pic.height / 2), 'GeeksForGeeks !') # Draw the picture draw(pic) # Invoke shadow function method pic.shadow(0.3, .1, 1, 2) # Save the image pic.save(filename ='shadow2.jpg')", "e": 1951, "s": 938, "text": null }, { "code": null, "e": 1959, "s": 1951, "text": "Output:" }, { "code": null, "e": 1974, "s": 1959, "text": "sagartomar9927" }, { "code": null, "e": 1991, "s": 1974, "text": "Image-Processing" }, { "code": null, "e": 2003, "s": 1991, "text": "Python-wand" }, { "code": null, "e": 2010, "s": 2003, "text": "Python" } ]
Python Operators for Sets and Dictionaries
11 Oct, 2020 Following article mainly discusses operators used in Sets and Dictionaries. Operators help to combine the existing value to larger syntactic expressions by using various keywords and symbols. Sets: Set class is used to represent the collection of elements without duplicates, and without any inherent order to those elements. It is enclosed by the {} and each element is separated by the comma(,) and it is mutable. Sets: Set class is used to represent the collection of elements without duplicates, and without any inherent order to those elements. It is enclosed by the {} and each element is separated by the comma(,) and it is mutable. Example: Python3 # set of alphabetset = {'a', 'b', 'c', 'd', 'e'}print(set) Output: {'c', 'b', 'd', 'e', 'a'} 2. Frozensets: It is an immutable form of a set, used to form a set of the set. Sets and frozensets support the following operators: key in s: It is used to check that the given key is in the set or not. key not in s: it returns True if the key is not in the set. Example: Python3 s = {4, 5, 8, 6, 3, 2, 5}key = 3x = key in s # containment checky = key not in s # non-containment checkprint(x, y) Output: True False s1 == s2 : To check s1 is equivalent to s2. i.e. all elements of s1 are in s2 and vice versa . it return True if s1 is equivalent to s2. s1 != s2 : s1 is not equivalent to s2. i.e. at least one elements of s1 is not in s2. it return True if s1 is not equivalent to s2. Example: Python3 s1 = {'t', 3, 6, 5, 7, 8, 4, 9}s2 = {5, 7, 8, 9, 't', 4, 3, 6} # equivalent checkx = s1 == s2 # non-equivalent checky = s1 != s2print(x)print(y) Output: True False Comparison of sets is not lexicographic since sets don’t arrange their element in a proper order. Thus, s1 cannot be greater than or less than s2 and vice versa, rather, they can be subsets or supersets. s1 <= s2 : s1 is subset of s2. i.e. all elements of s1 are in s2, returns True if s1 is a subset of s2. s1 < s2 : s1 is proper subset of s2. i.e. all elements of s1 are in s2 but all element of s2 are not necessarily in s1, returns True if s1 is a proper subset of s2. s1 >= s2 : s1 is superset of s2. i.e. all elements of s2 are in s1, returns True if s1 is a superset of s2. s1 > s2 : s1 is proper superset of s2. i.e. all elements of s2 are in s1 but all element of s1 are not necessarily in s2, returns True if s1 is a proper superset of s2. Example : Python3 s1 = {2, 5, 3, 7, 'c', 'a', 8}s2 = {3, 7, 8, 'c'} # subset checkw = s1 <= s2 # proper subset checkx = s1 < s2 # superset checky = s1 >= s2 # proper superset checkz = s1 > s2print(w, x, y, z) Output: False False True True s1 | s2: union of s1 and s2, returns elements of both s1 and s2 without repetition. s1 & s2: intersection of s1 and s2, returns elements which are present in both sets. s1 − s2: set difference, returns elements which are in s1 but not in s2. s1 ˆ s2: the set of elements in precisely one of s1 or s2, returns elements which are in s1 but not in s2 and elements which in s2 but not in s1. Example: Python3 s1 = {2, 5, 3, 7, 'c', 'a', 8}s2 = {3, 7, 8, 'c', 9, 11, 'd'} # unionw = s1 | s2 # intersectionx = s1 & s2 # elements which are in s1 but not in s2# and elements which are in s2 but not in s1y = s1 ^ s2 # set differencez = s1-s2print(w)print(x)print(y)print(z) Output: {2, 3, 5, ‘a’, 7, 8, 9, 11, ‘d’, ‘c’} {8, ‘c’, 3, 7} {2, 5, 9, ‘d’, 11, ‘a’} {2, 5, ‘a’} 3. Dictionaries: It is a mapping of different keys to its associated values. We use curly brackets { } to create dictionaries too. Example: Python3 # Example of Dictionaryd = {'jupiter': 'planet', 'sun': 'star'}print(d) Output: {'jupiter': 'planet', 'sun': 'star'} Dictionaries support the following operators: d[key]: it is used to get the value associated with the given key from the dictionary. d[key] = value: it is used to set (or reset) the value associated with the given key from the dictionary. del d[key]: It is used to delete the key and its associated value from the dictionary. Example: Python3 dict = {'math': 45, 'english': 60, 'science': 65, 'computer science': 70} # retrieving value by using keyx = dict['science']print(x) # reassigning valuedict['english'] = 80print(dict) # deletingdel dict['math']print(dict) Output: 65{‘math’: 45, ‘english’: 80, ‘science’: 65, ‘computer science’: 70}{‘english’: 80, ‘science’: 65, ‘computer science’: 70} key in d: It is used to check whether a certain key is in the dictionary or not. also called containment check. It returns a boolean value. key not in d: It returns a boolean value, True if the key is not present in the dictionary, also called non-containment check Example: Python3 dict = {'math': 45, 'english': 60, 'science': 65, 'computer science': 70} # containment checkx = 'english' in dict # non-containment checky = 'hindi' not in dictprint(x)print(y) Output: True True d1 == d2: it compares key-value pair of both dictionaries, if found, returns True. d1 != d2: it compares key-value pair of both dictionaries, if found returns True. Example: Python3 d1 = {'a': 5, 'b': 7, 'c': 9, 'e': 3}d2 = {'c': 9, 'a': 5, 'b': 7, 'e': 3} x = d1 == d2y = d1 != d2 print(x)print(y) Output: True False Dictionaries are similar to sets. they also don’t have any elements in a definite order. The concept of subset and superset is not applicable on dictionaries. Thus, subset and superset operators are meaningless for it. python-dict python-set Python python-dict python-set Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n11 Oct, 2020" }, { "code": null, "e": 247, "s": 54, "text": "Following article mainly discusses operators used in Sets and Dictionaries. Operators help to combine the existing value to larger syntactic expressions by using various keywords and symbols." }, { "code": null, "e": 471, "s": 247, "text": "Sets: Set class is used to represent the collection of elements without duplicates, and without any inherent order to those elements. It is enclosed by the {} and each element is separated by the comma(,) and it is mutable." }, { "code": null, "e": 695, "s": 471, "text": "Sets: Set class is used to represent the collection of elements without duplicates, and without any inherent order to those elements. It is enclosed by the {} and each element is separated by the comma(,) and it is mutable." }, { "code": null, "e": 704, "s": 695, "text": "Example:" }, { "code": null, "e": 712, "s": 704, "text": "Python3" }, { "code": "# set of alphabetset = {'a', 'b', 'c', 'd', 'e'}print(set)", "e": 771, "s": 712, "text": null }, { "code": null, "e": 779, "s": 771, "text": "Output:" }, { "code": null, "e": 806, "s": 779, "text": "{'c', 'b', 'd', 'e', 'a'}\n" }, { "code": null, "e": 894, "s": 806, "text": " 2. Frozensets: It is an immutable form of a set, used to form a set of the set." }, { "code": null, "e": 956, "s": 894, "text": " Sets and frozensets support the following operators:" }, { "code": null, "e": 1027, "s": 956, "text": "key in s: It is used to check that the given key is in the set or not." }, { "code": null, "e": 1087, "s": 1027, "text": "key not in s: it returns True if the key is not in the set." }, { "code": null, "e": 1096, "s": 1087, "text": "Example:" }, { "code": null, "e": 1104, "s": 1096, "text": "Python3" }, { "code": "s = {4, 5, 8, 6, 3, 2, 5}key = 3x = key in s # containment checky = key not in s # non-containment checkprint(x, y)", "e": 1222, "s": 1104, "text": null }, { "code": null, "e": 1230, "s": 1222, "text": "Output:" }, { "code": null, "e": 1242, "s": 1230, "text": "True False\n" }, { "code": null, "e": 1381, "s": 1242, "text": "s1 == s2 : To check s1 is equivalent to s2. i.e. all elements of s1 are in s2 and vice versa . it return True if s1 is equivalent to s2." }, { "code": null, "e": 1516, "s": 1381, "text": "s1 != s2 : s1 is not equivalent to s2. i.e. at least one elements of s1 is not in s2. it return True if s1 is not equivalent to s2." }, { "code": null, "e": 1525, "s": 1516, "text": "Example:" }, { "code": null, "e": 1533, "s": 1525, "text": "Python3" }, { "code": "s1 = {'t', 3, 6, 5, 7, 8, 4, 9}s2 = {5, 7, 8, 9, 't', 4, 3, 6} # equivalent checkx = s1 == s2 # non-equivalent checky = s1 != s2print(x)print(y)", "e": 1680, "s": 1533, "text": null }, { "code": null, "e": 1688, "s": 1680, "text": "Output:" }, { "code": null, "e": 1700, "s": 1688, "text": "True\nFalse\n" }, { "code": null, "e": 1904, "s": 1700, "text": "Comparison of sets is not lexicographic since sets don’t arrange their element in a proper order. Thus, s1 cannot be greater than or less than s2 and vice versa, rather, they can be subsets or supersets." }, { "code": null, "e": 2010, "s": 1904, "text": "s1 <= s2 : s1 is subset of s2. i.e. all elements of s1 are in s2, returns True if s1 is a subset of s2." }, { "code": null, "e": 2181, "s": 2010, "text": "s1 < s2 : s1 is proper subset of s2. i.e. all elements of s1 are in s2 but all element of s2 are not necessarily in s1, returns True if s1 is a proper subset of s2." }, { "code": null, "e": 2290, "s": 2181, "text": "s1 >= s2 : s1 is superset of s2. i.e. all elements of s2 are in s1, returns True if s1 is a superset of s2." }, { "code": null, "e": 2461, "s": 2290, "text": "s1 > s2 : s1 is proper superset of s2. i.e. all elements of s2 are in s1 but all element of s1 are not necessarily in s2, returns True if s1 is a proper superset of s2." }, { "code": null, "e": 2471, "s": 2461, "text": "Example :" }, { "code": null, "e": 2479, "s": 2471, "text": "Python3" }, { "code": "s1 = {2, 5, 3, 7, 'c', 'a', 8}s2 = {3, 7, 8, 'c'} # subset checkw = s1 <= s2 # proper subset checkx = s1 < s2 # superset checky = s1 >= s2 # proper superset checkz = s1 > s2print(w, x, y, z)", "e": 2674, "s": 2479, "text": null }, { "code": null, "e": 2682, "s": 2674, "text": "Output:" }, { "code": null, "e": 2705, "s": 2682, "text": "False False True True\n" }, { "code": null, "e": 2789, "s": 2705, "text": "s1 | s2: union of s1 and s2, returns elements of both s1 and s2 without repetition." }, { "code": null, "e": 2874, "s": 2789, "text": "s1 & s2: intersection of s1 and s2, returns elements which are present in both sets." }, { "code": null, "e": 2948, "s": 2874, "text": "s1 − s2: set difference, returns elements which are in s1 but not in s2." }, { "code": null, "e": 3094, "s": 2948, "text": "s1 ˆ s2: the set of elements in precisely one of s1 or s2, returns elements which are in s1 but not in s2 and elements which in s2 but not in s1." }, { "code": null, "e": 3103, "s": 3094, "text": "Example:" }, { "code": null, "e": 3111, "s": 3103, "text": "Python3" }, { "code": "s1 = {2, 5, 3, 7, 'c', 'a', 8}s2 = {3, 7, 8, 'c', 9, 11, 'd'} # unionw = s1 | s2 # intersectionx = s1 & s2 # elements which are in s1 but not in s2# and elements which are in s2 but not in s1y = s1 ^ s2 # set differencez = s1-s2print(w)print(x)print(y)print(z)", "e": 3376, "s": 3111, "text": null }, { "code": null, "e": 3384, "s": 3376, "text": "Output:" }, { "code": null, "e": 3422, "s": 3384, "text": "{2, 3, 5, ‘a’, 7, 8, 9, 11, ‘d’, ‘c’}" }, { "code": null, "e": 3437, "s": 3422, "text": "{8, ‘c’, 3, 7}" }, { "code": null, "e": 3461, "s": 3437, "text": "{2, 5, 9, ‘d’, 11, ‘a’}" }, { "code": null, "e": 3473, "s": 3461, "text": "{2, 5, ‘a’}" }, { "code": null, "e": 3609, "s": 3473, "text": " 3. Dictionaries: It is a mapping of different keys to its associated values. We use curly brackets { } to create dictionaries too. " }, { "code": null, "e": 3618, "s": 3609, "text": "Example:" }, { "code": null, "e": 3626, "s": 3618, "text": "Python3" }, { "code": "# Example of Dictionaryd = {'jupiter': 'planet', 'sun': 'star'}print(d)", "e": 3698, "s": 3626, "text": null }, { "code": null, "e": 3706, "s": 3698, "text": "Output:" }, { "code": null, "e": 3744, "s": 3706, "text": "{'jupiter': 'planet', 'sun': 'star'}\n" }, { "code": null, "e": 3790, "s": 3744, "text": "Dictionaries support the following operators:" }, { "code": null, "e": 3877, "s": 3790, "text": "d[key]: it is used to get the value associated with the given key from the dictionary." }, { "code": null, "e": 3983, "s": 3877, "text": "d[key] = value: it is used to set (or reset) the value associated with the given key from the dictionary." }, { "code": null, "e": 4070, "s": 3983, "text": "del d[key]: It is used to delete the key and its associated value from the dictionary." }, { "code": null, "e": 4079, "s": 4070, "text": "Example:" }, { "code": null, "e": 4087, "s": 4079, "text": "Python3" }, { "code": "dict = {'math': 45, 'english': 60, 'science': 65, 'computer science': 70} # retrieving value by using keyx = dict['science']print(x) # reassigning valuedict['english'] = 80print(dict) # deletingdel dict['math']print(dict)", "e": 4320, "s": 4087, "text": null }, { "code": null, "e": 4328, "s": 4320, "text": "Output:" }, { "code": null, "e": 4451, "s": 4328, "text": "65{‘math’: 45, ‘english’: 80, ‘science’: 65, ‘computer science’: 70}{‘english’: 80, ‘science’: 65, ‘computer science’: 70}" }, { "code": null, "e": 4591, "s": 4451, "text": "key in d: It is used to check whether a certain key is in the dictionary or not. also called containment check. It returns a boolean value." }, { "code": null, "e": 4717, "s": 4591, "text": "key not in d: It returns a boolean value, True if the key is not present in the dictionary, also called non-containment check" }, { "code": null, "e": 4726, "s": 4717, "text": "Example:" }, { "code": null, "e": 4734, "s": 4726, "text": "Python3" }, { "code": "dict = {'math': 45, 'english': 60, 'science': 65, 'computer science': 70} # containment checkx = 'english' in dict # non-containment checky = 'hindi' not in dictprint(x)print(y)", "e": 4921, "s": 4734, "text": null }, { "code": null, "e": 4929, "s": 4921, "text": "Output:" }, { "code": null, "e": 4940, "s": 4929, "text": "True\nTrue\n" }, { "code": null, "e": 5024, "s": 4940, "text": "d1 == d2: it compares key-value pair of both dictionaries, if found, returns True." }, { "code": null, "e": 5106, "s": 5024, "text": "d1 != d2: it compares key-value pair of both dictionaries, if found returns True." }, { "code": null, "e": 5115, "s": 5106, "text": "Example:" }, { "code": null, "e": 5123, "s": 5115, "text": "Python3" }, { "code": "d1 = {'a': 5, 'b': 7, 'c': 9, 'e': 3}d2 = {'c': 9, 'a': 5, 'b': 7, 'e': 3} x = d1 == d2y = d1 != d2 print(x)print(y)", "e": 5242, "s": 5123, "text": null }, { "code": null, "e": 5250, "s": 5242, "text": "Output:" }, { "code": null, "e": 5262, "s": 5250, "text": "True\nFalse\n" }, { "code": null, "e": 5351, "s": 5262, "text": "Dictionaries are similar to sets. they also don’t have any elements in a definite order." }, { "code": null, "e": 5481, "s": 5351, "text": "The concept of subset and superset is not applicable on dictionaries. Thus, subset and superset operators are meaningless for it." }, { "code": null, "e": 5493, "s": 5481, "text": "python-dict" }, { "code": null, "e": 5504, "s": 5493, "text": "python-set" }, { "code": null, "e": 5511, "s": 5504, "text": "Python" }, { "code": null, "e": 5523, "s": 5511, "text": "python-dict" }, { "code": null, "e": 5534, "s": 5523, "text": "python-set" } ]
sciPy stats.sem() function | Python
18 Feb, 2019 scipy.stats.sem(arr, axis=0, ddof=0) function is used to compute the standard error of the mean of the input data. Parameters :arr : [array_like]Input array or object having the elements to calculate the standard error.axis : Axis along which the mean is to be computed. By default axis = 0.ddof : Degree of freedom correction for Standard Deviation. Results : standard error of the mean of the input data. Example: # stats.sem() method import numpy as npfrom scipy import stats arr1 = [[20, 2, 7, 1, 34], [50, 12, 12, 34, 4]] arr2 = [50, 12, 12, 34, 4] print ("\narr1 : ", arr1)print ("\narr2 : ", arr2) print ("\nsem ratio for arr1 : ", stats.sem(arr1, axis = 0, ddof = 0)) print ("\nsem ratio for arr1 : ", stats.sem(arr1, axis = 1, ddof = 0)) print ("\nsem ratio for arr1 : ", stats.sem(arr2, axis = 0, ddof = 0)) Output : arr1 : [[20, 2, 7, 1, 34], [50, 12, 12, 34, 4]] arr2 : [50, 12, 12, 34, 4] sem ratio for arr1 : [10.60660172 3.53553391 1.76776695 11.66726189 10.60660172] sem ratio for arr1 : [5.62423328 7.61892381] sem ratio for arr1 : 7.618923808517841 Python scipy-stats-functions Python-scipy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n18 Feb, 2019" }, { "code": null, "e": 143, "s": 28, "text": "scipy.stats.sem(arr, axis=0, ddof=0) function is used to compute the standard error of the mean of the input data." }, { "code": null, "e": 379, "s": 143, "text": "Parameters :arr : [array_like]Input array or object having the elements to calculate the standard error.axis : Axis along which the mean is to be computed. By default axis = 0.ddof : Degree of freedom correction for Standard Deviation." }, { "code": null, "e": 435, "s": 379, "text": "Results : standard error of the mean of the input data." }, { "code": null, "e": 444, "s": 435, "text": "Example:" }, { "code": "# stats.sem() method import numpy as npfrom scipy import stats arr1 = [[20, 2, 7, 1, 34], [50, 12, 12, 34, 4]] arr2 = [50, 12, 12, 34, 4] print (\"\\narr1 : \", arr1)print (\"\\narr2 : \", arr2) print (\"\\nsem ratio for arr1 : \", stats.sem(arr1, axis = 0, ddof = 0)) print (\"\\nsem ratio for arr1 : \", stats.sem(arr1, axis = 1, ddof = 0)) print (\"\\nsem ratio for arr1 : \", stats.sem(arr2, axis = 0, ddof = 0)) ", "e": 885, "s": 444, "text": null }, { "code": null, "e": 894, "s": 885, "text": "Output :" }, { "code": null, "e": 1145, "s": 894, "text": "arr1 : [[20, 2, 7, 1, 34], [50, 12, 12, 34, 4]]\n\narr2 : [50, 12, 12, 34, 4]\n\nsem ratio for arr1 : [10.60660172 3.53553391 1.76776695 11.66726189 10.60660172]\n\nsem ratio for arr1 : [5.62423328 7.61892381]\n\nsem ratio for arr1 : 7.618923808517841" }, { "code": null, "e": 1174, "s": 1145, "text": "Python scipy-stats-functions" }, { "code": null, "e": 1187, "s": 1174, "text": "Python-scipy" }, { "code": null, "e": 1194, "s": 1187, "text": "Python" } ]
NumPy.histogram() Method in Python
16 Dec, 2021 A histogram is the best way to visualize the frequency distribution of a dataset by splitting it into small equal-sized intervals called bins. The Numpy histogram function is similar to the hist() function of matplotlib library, the only difference is that the Numpy histogram gives the numerical representation of the dataset while the hist() gives graphical representation of the dataset. Numpy has a built-in numpy.histogram() function which represents the frequency of data distribution in the graphical form. The rectangles having equal horizontal size corresponds to class interval called bin and variable height corresponding to the frequency.Syntax: numpy.histogram(data, bins=10, range=None, normed=None, weights=None, density=None) Attributes of the above function are listed below: The function has two return values hist which gives the array of values of the histogram, and edge_bin which is an array of float datatype containing the bin edges having length one more than the hist.Example: Python3 # Import librariesimport numpy as np # Creating dataseta = np.random.randint(100, size =(50)) # Creating histogramnp.histogram(a, bins = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]) hist, bins = np.histogram(a, bins = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]) # printing histogramprint()print (hist)print (bins)print() Output: The above numeric representation of histogram can be converted into a graphical form.The plt() function present in pyplot submodule of Matplotlib takes the array of dataset and array of bin as parameter and creates a histogram of the corresponding data values.Example: Python3 # import librariesfrom matplotlib import pyplot as pltimport numpy as np # Creating dataseta = np.random.randint(100, size =(50)) # Creating plotfig = plt.figure(figsize =(10, 7)) plt.hist(a, bins = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]) plt.title("Numpy Histogram") # show plotplt.show() Output: as5853535 Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n16 Dec, 2021" }, { "code": null, "e": 420, "s": 28, "text": "A histogram is the best way to visualize the frequency distribution of a dataset by splitting it into small equal-sized intervals called bins. The Numpy histogram function is similar to the hist() function of matplotlib library, the only difference is that the Numpy histogram gives the numerical representation of the dataset while the hist() gives graphical representation of the dataset. " }, { "code": null, "e": 687, "s": 420, "text": "Numpy has a built-in numpy.histogram() function which represents the frequency of data distribution in the graphical form. The rectangles having equal horizontal size corresponds to class interval called bin and variable height corresponding to the frequency.Syntax:" }, { "code": null, "e": 771, "s": 687, "text": "numpy.histogram(data, bins=10, range=None, normed=None, weights=None, density=None)" }, { "code": null, "e": 823, "s": 771, "text": "Attributes of the above function are listed below: " }, { "code": null, "e": 1033, "s": 823, "text": "The function has two return values hist which gives the array of values of the histogram, and edge_bin which is an array of float datatype containing the bin edges having length one more than the hist.Example:" }, { "code": null, "e": 1041, "s": 1033, "text": "Python3" }, { "code": "# Import librariesimport numpy as np # Creating dataseta = np.random.randint(100, size =(50)) # Creating histogramnp.histogram(a, bins = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]) hist, bins = np.histogram(a, bins = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]) # printing histogramprint()print (hist)print (bins)print()", "e": 1592, "s": 1041, "text": null }, { "code": null, "e": 1601, "s": 1592, "text": "Output: " }, { "code": null, "e": 1870, "s": 1601, "text": "The above numeric representation of histogram can be converted into a graphical form.The plt() function present in pyplot submodule of Matplotlib takes the array of dataset and array of bin as parameter and creates a histogram of the corresponding data values.Example:" }, { "code": null, "e": 1878, "s": 1870, "text": "Python3" }, { "code": "# import librariesfrom matplotlib import pyplot as pltimport numpy as np # Creating dataseta = np.random.randint(100, size =(50)) # Creating plotfig = plt.figure(figsize =(10, 7)) plt.hist(a, bins = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]) plt.title(\"Numpy Histogram\") # show plotplt.show()", "e": 2214, "s": 1878, "text": null }, { "code": null, "e": 2223, "s": 2214, "text": "Output: " }, { "code": null, "e": 2233, "s": 2223, "text": "as5853535" }, { "code": null, "e": 2246, "s": 2233, "text": "Python-numpy" }, { "code": null, "e": 2253, "s": 2246, "text": "Python" } ]
Draw a Chessboard in Java Applet - GeeksforGeeks
22 Apr, 2022 Given task is to draw a Chessboard in Java Applet Approach: Create a rectangle with length and breadth of 20 unit each, with 10 rows and columns of chess.As soon as even position occurs in row and column change the color of a rectangle with BLACK, else it will be WHITE Create a rectangle with length and breadth of 20 unit each, with 10 rows and columns of chess. As soon as even position occurs in row and column change the color of a rectangle with BLACK, else it will be WHITE Below is the implementation of the above approach: Applet Program: Java import java.applet.*;import java.awt.*;/*<applet code="Chess" width=600 height=600></applet>*/// Extends Applet Classpublic class Chess extends Applet { static int N = 10; // Use paint() method public void paint(Graphics g) { int x, y; for (int row = 0; row & lt; N; row++) { for (int col = 0; col & lt; N; col++) { // Set x coordinates of rectangle // by 20 times x = row * 20; // Set y coordinates of rectangle // by 20 times y = col * 20; // Check whether row and column // are in even position // If it is true set Black color if ((row % 2 == 0) == (col % 2 == 0)) g.setColor(Color.BLACK); else g.setColor(Color.WHITE); // Create a rectangle with // length and breadth of 20 g.fillRect(x, y, 20, 20); } } }} Output: Note: To run the applet in command line use the following commands. > javac Chess.java > appletviewer Chess.java You can also refer to: https://www.geeksforgeeks.org/different-ways-to-run-applet-in-java to run applet program. java-applet Java Technical Scripter Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Constructors in Java Stream In Java Exceptions in Java Functional Interfaces in Java Different ways of Reading a text file in Java Java Programming Examples Internal Working of HashMap in Java Checked vs Unchecked Exceptions in Java Strings in Java StringBuilder Class in Java with Examples
[ { "code": null, "e": 23892, "s": 23864, "text": "\n22 Apr, 2022" }, { "code": null, "e": 23943, "s": 23892, "text": "Given task is to draw a Chessboard in Java Applet " }, { "code": null, "e": 23953, "s": 23943, "text": "Approach:" }, { "code": null, "e": 24163, "s": 23953, "text": "Create a rectangle with length and breadth of 20 unit each, with 10 rows and columns of chess.As soon as even position occurs in row and column change the color of a rectangle with BLACK, else it will be WHITE" }, { "code": null, "e": 24258, "s": 24163, "text": "Create a rectangle with length and breadth of 20 unit each, with 10 rows and columns of chess." }, { "code": null, "e": 24374, "s": 24258, "text": "As soon as even position occurs in row and column change the color of a rectangle with BLACK, else it will be WHITE" }, { "code": null, "e": 24426, "s": 24374, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 24443, "s": 24426, "text": "Applet Program: " }, { "code": null, "e": 24448, "s": 24443, "text": "Java" }, { "code": "import java.applet.*;import java.awt.*;/*<applet code=\"Chess\" width=600 height=600></applet>*/// Extends Applet Classpublic class Chess extends Applet { static int N = 10; // Use paint() method public void paint(Graphics g) { int x, y; for (int row = 0; row & lt; N; row++) { for (int col = 0; col & lt; N; col++) { // Set x coordinates of rectangle // by 20 times x = row * 20; // Set y coordinates of rectangle // by 20 times y = col * 20; // Check whether row and column // are in even position // If it is true set Black color if ((row % 2 == 0) == (col % 2 == 0)) g.setColor(Color.BLACK); else g.setColor(Color.WHITE); // Create a rectangle with // length and breadth of 20 g.fillRect(x, y, 20, 20); } } }}", "e": 25473, "s": 24448, "text": null }, { "code": null, "e": 25481, "s": 25473, "text": "Output:" }, { "code": null, "e": 25551, "s": 25483, "text": "Note: To run the applet in command line use the following commands." }, { "code": null, "e": 25596, "s": 25551, "text": "> javac Chess.java\n> appletviewer Chess.java" }, { "code": null, "e": 25709, "s": 25596, "text": "You can also refer to: https://www.geeksforgeeks.org/different-ways-to-run-applet-in-java to run applet program." }, { "code": null, "e": 25721, "s": 25709, "text": "java-applet" }, { "code": null, "e": 25726, "s": 25721, "text": "Java" }, { "code": null, "e": 25745, "s": 25726, "text": "Technical Scripter" }, { "code": null, "e": 25750, "s": 25745, "text": "Java" }, { "code": null, "e": 25848, "s": 25750, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25857, "s": 25848, "text": "Comments" }, { "code": null, "e": 25870, "s": 25857, "text": "Old Comments" }, { "code": null, "e": 25891, "s": 25870, "text": "Constructors in Java" }, { "code": null, "e": 25906, "s": 25891, "text": "Stream In Java" }, { "code": null, "e": 25925, "s": 25906, "text": "Exceptions in Java" }, { "code": null, "e": 25955, "s": 25925, "text": "Functional Interfaces in Java" }, { "code": null, "e": 26001, "s": 25955, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 26027, "s": 26001, "text": "Java Programming Examples" }, { "code": null, "e": 26063, "s": 26027, "text": "Internal Working of HashMap in Java" }, { "code": null, "e": 26103, "s": 26063, "text": "Checked vs Unchecked Exceptions in Java" }, { "code": null, "e": 26119, "s": 26103, "text": "Strings in Java" } ]
How to delay a JavaScript function call using JavaScript?
To delay a function call, use setTimeout() function. setTimeout(functionname, milliseconds, arg1, arg2, arg3...) The following are the parameters − functionname − The function name for the function to be executed. milliseconds − The number of milliseconds. arg1, arg2, arg3 − These are the arguments passed to the function. You can try to run the following code to delay a JavaScript function call with a setTimeout() callback. Live Demo <!DOCTYPE html> <html> <body> <button onclick="timeFunction()">Submit</button> <script> function timeFunction() { setTimeout(function(){ alert("After 5 seconds!"); }, 5000); } </script> <p>Click the above button and wait for 5 seconds.</p> </body> </html>
[ { "code": null, "e": 1115, "s": 1062, "text": "To delay a function call, use setTimeout() function." }, { "code": null, "e": 1175, "s": 1115, "text": "setTimeout(functionname, milliseconds, arg1, arg2, arg3...)" }, { "code": null, "e": 1210, "s": 1175, "text": "The following are the parameters −" }, { "code": null, "e": 1276, "s": 1210, "text": "functionname − The function name for the function to be executed." }, { "code": null, "e": 1319, "s": 1276, "text": "milliseconds − The number of milliseconds." }, { "code": null, "e": 1386, "s": 1319, "text": "arg1, arg2, arg3 − These are the arguments passed to the function." }, { "code": null, "e": 1490, "s": 1386, "text": "You can try to run the following code to delay a JavaScript function call with a setTimeout() callback." }, { "code": null, "e": 1501, "s": 1490, "text": " Live Demo" }, { "code": null, "e": 1801, "s": 1501, "text": "<!DOCTYPE html>\n<html>\n <body>\n <button onclick=\"timeFunction()\">Submit</button>\n <script>\n function timeFunction() {\n setTimeout(function(){ alert(\"After 5 seconds!\"); }, 5000);\n }\n</script>\n<p>Click the above button and wait for 5 seconds.</p>\n</body>\n</html>" } ]
LISP - Basic Syntax
LISP programs are made up of three basic building blocks − atom atom list list string string An atom is a number or string of contiguous characters. It includes numbers and special characters. Following are examples of some valid atoms − hello-from-tutorials-point name 123008907 *hello* Block#221 abc123 A list is a sequence of atoms and/or other lists enclosed in parentheses. Following are examples of some valid lists − ( i am a list) (a ( a b c) d e fgh) (father tom ( susan bill joe)) (sun mon tue wed thur fri sat) ( ) A string is a group of characters enclosed in double quotation marks. Following are examples of some valid strings − " I am a string" "a ba c d efg #$%^&!" "Please enter the following details :" "Hello from 'Tutorials Point'! " The semicolon symbol (;) is used for indicating a comment line. For Example, (write-line "Hello World") ; greet the world ; tell them your whereabouts (write-line "I am at 'Tutorials Point'! Learning LISP") When you click the Execute button, or type Ctrl+E, LISP executes it immediately and the result returned is − Hello World I am at 'Tutorials Point'! Learning LISP Following are some of the important points to note − The basic numeric operations in LISP are +, -, *, and / The basic numeric operations in LISP are +, -, *, and / LISP represents a function call f(x) as (f x), for example cos(45) is written as cos 45 LISP represents a function call f(x) as (f x), for example cos(45) is written as cos 45 LISP expressions are case-insensitive, cos 45 or COS 45 are same. LISP expressions are case-insensitive, cos 45 or COS 45 are same. LISP tries to evaluate everything, including the arguments of a function. Only three types of elements are constants and always return their own value Numbers The letter t, that stands for logical true. The value nil, that stands for logical false, as well as an empty list. LISP tries to evaluate everything, including the arguments of a function. Only three types of elements are constants and always return their own value Numbers Numbers The letter t, that stands for logical true. The letter t, that stands for logical true. The value nil, that stands for logical false, as well as an empty list. The value nil, that stands for logical false, as well as an empty list. In the previous chapter, we mentioned that the evaluation process of LISP code takes the following steps. The reader translates the strings of characters to LISP objects or s-expressions. The reader translates the strings of characters to LISP objects or s-expressions. The evaluator defines syntax of Lisp forms that are built from s-expressions. This second level of evaluation defines a syntax that determines which s-expressions are LISP forms. The evaluator defines syntax of Lisp forms that are built from s-expressions. This second level of evaluation defines a syntax that determines which s-expressions are LISP forms. Now, a LISP forms could be. An Atom An Atom An empty or non-list An empty or non-list Any list that has a symbol as its first element Any list that has a symbol as its first element The evaluator works as a function that takes a valid LISP form as an argument and returns a value. This is the reason why we put the LISP expression in parenthesis, because we are sending the entire expression/form to the evaluator as arguments. Name or symbols can consist of any number of alphanumeric characters other than whitespace, open and closing parentheses, double and single quotes, backslash, comma, colon, semicolon and vertical bar. To use these characters in a name, you need to use escape character (\). A name can have digits but not entirely made of digits, because then it would be read as a number. Similarly a name can have periods, but can't be made entirely of periods. LISP evaluates everything including the function arguments and list members. At times, we need to take atoms or lists literally and don't want them evaluated or treated as function calls. To do this, we need to precede the atom or the list with a single quotation mark. The following example demonstrates this. Create a file named main.lisp and type the following code into it. (write-line "single quote used, it inhibits evaluation") (write '(* 2 3)) (write-line " ") (write-line "single quote not used, so expression evaluated") (write (* 2 3)) When you click the Execute button, or type Ctrl+E, LISP executes it immediately and the result returned is − single quote used, it inhibits evaluation (* 2 3) single quote not used, so expression evaluated 6 79 Lectures 7 hours Arnold Higuit Print Add Notes Bookmark this page
[ { "code": null, "e": 2119, "s": 2060, "text": "LISP programs are made up of three basic building blocks −" }, { "code": null, "e": 2124, "s": 2119, "text": "atom" }, { "code": null, "e": 2129, "s": 2124, "text": "atom" }, { "code": null, "e": 2134, "s": 2129, "text": "list" }, { "code": null, "e": 2139, "s": 2134, "text": "list" }, { "code": null, "e": 2146, "s": 2139, "text": "string" }, { "code": null, "e": 2153, "s": 2146, "text": "string" }, { "code": null, "e": 2253, "s": 2153, "text": "An atom is a number or string of contiguous characters. It includes numbers and special characters." }, { "code": null, "e": 2298, "s": 2253, "text": "Following are examples of some valid atoms −" }, { "code": null, "e": 2365, "s": 2298, "text": "hello-from-tutorials-point\nname\n123008907\n*hello*\nBlock#221\nabc123" }, { "code": null, "e": 2439, "s": 2365, "text": "A list is a sequence of atoms and/or other lists enclosed in parentheses." }, { "code": null, "e": 2484, "s": 2439, "text": "Following are examples of some valid lists −" }, { "code": null, "e": 2586, "s": 2484, "text": "( i am a list)\n(a ( a b c) d e fgh)\n(father tom ( susan bill joe))\n(sun mon tue wed thur fri sat)\n( )" }, { "code": null, "e": 2656, "s": 2586, "text": "A string is a group of characters enclosed in double quotation marks." }, { "code": null, "e": 2703, "s": 2656, "text": "Following are examples of some valid strings −" }, { "code": null, "e": 2814, "s": 2703, "text": "\" I am a string\"\n\"a ba c d efg #$%^&!\"\n\"Please enter the following details :\"\n\"Hello from 'Tutorials Point'! \"" }, { "code": null, "e": 2878, "s": 2814, "text": "The semicolon symbol (;) is used for indicating a comment line." }, { "code": null, "e": 2891, "s": 2878, "text": "For Example," }, { "code": null, "e": 3023, "s": 2891, "text": "(write-line \"Hello World\") ; greet the world\n\n; tell them your whereabouts\n\n(write-line \"I am at 'Tutorials Point'! Learning LISP\")" }, { "code": null, "e": 3132, "s": 3023, "text": "When you click the Execute button, or type Ctrl+E, LISP executes it immediately and the result returned is −" }, { "code": null, "e": 3187, "s": 3132, "text": "Hello World\n\nI am at 'Tutorials Point'! Learning LISP\n" }, { "code": null, "e": 3240, "s": 3187, "text": "Following are some of the important points to note −" }, { "code": null, "e": 3296, "s": 3240, "text": "The basic numeric operations in LISP are +, -, *, and /" }, { "code": null, "e": 3352, "s": 3296, "text": "The basic numeric operations in LISP are +, -, *, and /" }, { "code": null, "e": 3440, "s": 3352, "text": "LISP represents a function call f(x) as (f x), for example cos(45) is written as cos 45" }, { "code": null, "e": 3528, "s": 3440, "text": "LISP represents a function call f(x) as (f x), for example cos(45) is written as cos 45" }, { "code": null, "e": 3594, "s": 3528, "text": "LISP expressions are case-insensitive, cos 45 or COS 45 are same." }, { "code": null, "e": 3660, "s": 3594, "text": "LISP expressions are case-insensitive, cos 45 or COS 45 are same." }, { "code": null, "e": 3938, "s": 3660, "text": "LISP tries to evaluate everything, including the arguments of a function. Only three types of elements are constants and always return their own value\n\nNumbers\nThe letter t, that stands for logical true.\nThe value nil, that stands for logical false, as well as an empty list.\n\n" }, { "code": null, "e": 4089, "s": 3938, "text": "LISP tries to evaluate everything, including the arguments of a function. Only three types of elements are constants and always return their own value" }, { "code": null, "e": 4097, "s": 4089, "text": "Numbers" }, { "code": null, "e": 4105, "s": 4097, "text": "Numbers" }, { "code": null, "e": 4149, "s": 4105, "text": "The letter t, that stands for logical true." }, { "code": null, "e": 4193, "s": 4149, "text": "The letter t, that stands for logical true." }, { "code": null, "e": 4265, "s": 4193, "text": "The value nil, that stands for logical false, as well as an empty list." }, { "code": null, "e": 4337, "s": 4265, "text": "The value nil, that stands for logical false, as well as an empty list." }, { "code": null, "e": 4443, "s": 4337, "text": "In the previous chapter, we mentioned that the evaluation process of LISP code takes the following steps." }, { "code": null, "e": 4525, "s": 4443, "text": "The reader translates the strings of characters to LISP objects or s-expressions." }, { "code": null, "e": 4607, "s": 4525, "text": "The reader translates the strings of characters to LISP objects or s-expressions." }, { "code": null, "e": 4786, "s": 4607, "text": "The evaluator defines syntax of Lisp forms that are built from s-expressions. This second level of evaluation defines a syntax that determines which s-expressions are LISP forms." }, { "code": null, "e": 4965, "s": 4786, "text": "The evaluator defines syntax of Lisp forms that are built from s-expressions. This second level of evaluation defines a syntax that determines which s-expressions are LISP forms." }, { "code": null, "e": 4993, "s": 4965, "text": "Now, a LISP forms could be." }, { "code": null, "e": 5001, "s": 4993, "text": "An Atom" }, { "code": null, "e": 5009, "s": 5001, "text": "An Atom" }, { "code": null, "e": 5030, "s": 5009, "text": "An empty or non-list" }, { "code": null, "e": 5051, "s": 5030, "text": "An empty or non-list" }, { "code": null, "e": 5099, "s": 5051, "text": "Any list that has a symbol as its first element" }, { "code": null, "e": 5147, "s": 5099, "text": "Any list that has a symbol as its first element" }, { "code": null, "e": 5393, "s": 5147, "text": "The evaluator works as a function that takes a valid LISP form as an argument and returns a value. This is the reason why we put the LISP expression in parenthesis, because we are sending the entire expression/form to the evaluator as arguments." }, { "code": null, "e": 5667, "s": 5393, "text": "Name or symbols can consist of any number of alphanumeric characters other than whitespace, open and closing parentheses, double and single quotes, backslash, comma, colon, semicolon and vertical bar. To use these characters in a name, you need to use escape character (\\)." }, { "code": null, "e": 5840, "s": 5667, "text": "A name can have digits but not entirely made of digits, because then it would be read as a number. Similarly a name can have periods, but can't be made entirely of periods." }, { "code": null, "e": 5917, "s": 5840, "text": "LISP evaluates everything including the function arguments and list members." }, { "code": null, "e": 6028, "s": 5917, "text": "At times, we need to take atoms or lists literally and don't want them evaluated or treated as function calls." }, { "code": null, "e": 6110, "s": 6028, "text": "To do this, we need to precede the atom or the list with a single quotation mark." }, { "code": null, "e": 6151, "s": 6110, "text": "The following example demonstrates this." }, { "code": null, "e": 6218, "s": 6151, "text": "Create a file named main.lisp and type the following code into it." }, { "code": null, "e": 6387, "s": 6218, "text": "(write-line \"single quote used, it inhibits evaluation\")\n(write '(* 2 3))\n(write-line \" \")\n(write-line \"single quote not used, so expression evaluated\")\n(write (* 2 3))" }, { "code": null, "e": 6496, "s": 6387, "text": "When you click the Execute button, or type Ctrl+E, LISP executes it immediately and the result returned is −" }, { "code": null, "e": 6597, "s": 6496, "text": "single quote used, it inhibits evaluation\n(* 2 3) \nsingle quote not used, so expression evaluated\n6\n" }, { "code": null, "e": 6630, "s": 6597, "text": "\n 79 Lectures \n 7 hours \n" }, { "code": null, "e": 6645, "s": 6630, "text": " Arnold Higuit" }, { "code": null, "e": 6652, "s": 6645, "text": " Print" }, { "code": null, "e": 6663, "s": 6652, "text": " Add Notes" } ]
Is it mandatory to close JDBC connections?
At the end of your JDBC program, it is required explicitly to close all the connections to the database to end each database session. However, if you forget, Java's garbage collector will close the connection when it cleans up stale objects. Relying on the garbage collection, especially in database programming, is a very poor programming practice. You should make a habit of always closing the connection with the close() method associated with connection object. To ensure that a connection is closed, you could provide a 'finally' block in your code. A finally block always executes, regardless of an exception occurs or not. To close a JDBC connection, you should call close() method as: conn.close();
[ { "code": null, "e": 1304, "s": 1062, "text": "At the end of your JDBC program, it is required explicitly to close all the connections to the database to end each database session. However, if you forget, Java's garbage collector will close the connection when it cleans up stale objects." }, { "code": null, "e": 1528, "s": 1304, "text": "Relying on the garbage collection, especially in database programming, is a very poor programming practice. You should make a habit of always closing the connection with the close() method associated with connection object." }, { "code": null, "e": 1692, "s": 1528, "text": "To ensure that a connection is closed, you could provide a 'finally' block in your code. A finally block always executes, regardless of an exception occurs or not." }, { "code": null, "e": 1755, "s": 1692, "text": "To close a JDBC connection, you should call close() method as:" }, { "code": null, "e": 1769, "s": 1755, "text": "conn.close();" } ]
How to cast a list of strings to a string array?
The java.util.ArrayList.toArray() method returns an array containing all of the elements in this list in proper sequence (from first to last element).This acts as bridge between array-based and collection-based APIs. You can convert a list to array using this method of the List class − Live Demo import java.util.ArrayList; import java.util.List; public class ListOfStringsToStringArray { public static void main(String args[]) { List<String> list = new ArrayList<String>(); list.add("JavaFX"); list.add("HBase"); list.add("OpenCV"); String[] myArray = new String[list.size()]; list.toArray(myArray ); System.out.println("Contents of the String array are :: "); for(int i = 0; i<myArray.length; i++) { System.out.println(myArray[i]); } } } Contents of the String array are :: JavaFX HBase OpenCV
[ { "code": null, "e": 1279, "s": 1062, "text": "The java.util.ArrayList.toArray() method returns an array containing all of the elements in this list in proper sequence (from first to last element).This acts as bridge between array-based and collection-based APIs." }, { "code": null, "e": 1349, "s": 1279, "text": "You can convert a list to array using this method of the List class −" }, { "code": null, "e": 1360, "s": 1349, "text": " Live Demo" }, { "code": null, "e": 1896, "s": 1360, "text": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class ListOfStringsToStringArray {\n public static void main(String args[]) {\n List<String> list = new ArrayList<String>();\n \n list.add(\"JavaFX\");\n list.add(\"HBase\");\n list.add(\"OpenCV\");\n \n String[] myArray = new String[list.size()];\n \n list.toArray(myArray );\n System.out.println(\"Contents of the String array are :: \");\n\n for(int i = 0; i<myArray.length; i++) {\n System.out.println(myArray[i]);\n }\n }\n}" }, { "code": null, "e": 1953, "s": 1896, "text": "Contents of the String array are ::\nJavaFX\nHBase\nOpenCV\n" } ]
How do I use the conditional operator in C/C++?
This conditional operator is also known as the Ternary Operator. This operator has three phase. Exp1 ? Exp2 : Exp3; where Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon. The value of a ? expression is determined like this: Exp1 is evaluated. If it is true, then Exp2 is evaluated and becomes the value of the entire ? expression. If Exp1 is false, then Exp3 is evaluated and its value becomes the value of the expression. The ? is called a ternary operator because it requires three operands and can be used to replace if-else statements, which have the following form if(condition) { var = X; } else { var = Y; } For example, consider the following code if(y < 10) { var = 30; } else { var = 40; } Above code can be rewritten like this var = (y < 10) ? 30 : 40; #include <iostream> using namespace std; int main () { // Local variable declaration: int x, y = 10; x = (y < 10) ? 30 : 40; cout << "value of x: " << x << endl; return 0; } value of x: 40
[ { "code": null, "e": 1158, "s": 1062, "text": "This conditional operator is also known as the Ternary Operator. This operator has three phase." }, { "code": null, "e": 1178, "s": 1158, "text": "Exp1 ? Exp2 : Exp3;" }, { "code": null, "e": 1517, "s": 1178, "text": "where Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon. The value of a ? expression is determined like this: Exp1 is evaluated. If it is true, then Exp2 is evaluated and becomes the value of the entire ? expression. If Exp1 is false, then Exp3 is evaluated and its value becomes the value of the expression." }, { "code": null, "e": 1664, "s": 1517, "text": "The ? is called a ternary operator because it requires three operands and can be used to replace if-else statements, which have the following form" }, { "code": null, "e": 1717, "s": 1664, "text": "if(condition) {\n var = X;\n} else {\n var = Y;\n}" }, { "code": null, "e": 1758, "s": 1717, "text": "For example, consider the following code" }, { "code": null, "e": 1807, "s": 1758, "text": "if(y < 10) {\n var = 30;\n} else {\n var = 40;\n}" }, { "code": null, "e": 1845, "s": 1807, "text": "Above code can be rewritten like this" }, { "code": null, "e": 1871, "s": 1845, "text": "var = (y < 10) ? 30 : 40;" }, { "code": null, "e": 2060, "s": 1871, "text": "#include <iostream>\nusing namespace std;\nint main () {\n // Local variable declaration:\n int x, y = 10;\n x = (y < 10) ? 30 : 40;\n cout << \"value of x: \" << x << endl;\n return 0;\n}" }, { "code": null, "e": 2075, "s": 2060, "text": "value of x: 40" } ]